Add PBandGraphOauth scaffold and auth UI

This commit is contained in:
2025-12-19 05:42:29 +00:00
commit b51963f5d7
6264 changed files with 606430 additions and 0 deletions
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018 Microsoft Corporation
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+227
View File
@@ -0,0 +1,227 @@
# Microsoft Graph JavaScript Client Library
[![npm version badge](https://img.shields.io/npm/v/@microsoft/microsoft-graph-client.svg?maxAge=86400)](https://www.npmjs.com/package/@microsoft/microsoft-graph-client) [![Known Vulnerabilities](https://snyk.io/test/github/microsoftgraph/msgraph-sdk-javascript/badge.svg?maxAge=86400)](https://snyk.io/test/github/microsoftgraph/msgraph-sdk-javascript) [![Licence](https://img.shields.io/github/license/microsoftgraph/msgraph-sdk-javascript.svg)](https://github.com/microsoftgraph/msgraph-sdk-javascript) [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg)](https://github.com/microsoftgraph/msgraph-sdk-javascript) [![Downloads](https://img.shields.io/npm/dm/@microsoft/microsoft-graph-client.svg?maxAge=86400)](https://www.npmjs.com/package/@microsoft/microsoft-graph-client)
The Microsoft Graph JavaScript client library is a lightweight wrapper around the Microsoft Graph API that can be used server-side and in the browser.
- [Microsoft Graph JavaScript Client Library](#microsoft-graph-javascript-client-library)
- [Installation](#installation)
- [Via npm](#via-npm)
- [Via Script Tag](#via-script-tag)
- [Getting started](#getting-started)
- [1. Register your application](#1-register-your-application)
- [2. Create a Client Instance](#2-create-a-client-instance)
- [3. Make requests to the graph](#3-make-requests-to-the-graph)
- Documentation
- [HTTP Actions](docs/Actions.md)
- [Chained APIs to call Microsoft Graph](docs/CallingPattern.md)
- [OData system query options - Query Parameters](docs/QueryParameters.md)
- [Batch multiple requests into single HTTP request](docs/content/Batching.md)
- [Cancel a HTTP request](docs/CancellingAHTTPRequest.md)
- [Configurations to your request](docs/OtherAPIs.md)
- [Query](docs/OtherAPIs.md#QUERY)
- [Version](docs/OtherAPIs.md#VERSION)
- [Headers](docs/OtherAPIs.md#HEADER-AND-HEADERS)
- [Options](docs/OtherAPIs.md#OPTION-AND-OPTIONS)
- [MiddlewareOptions](docs/OtherAPIs.md#MIDDLEWAREOPTIONS)
- [ResponseType](docs/OtherAPIs.md#RESPONSETYPE)
- [Upload large files to OneDrive, Outlook, Print API](docs/tasks/LargeFileUploadTask.md)
- [Page Iteration](docs/tasks/PageIterator.md)
- [Getting Raw Response](docs/GettingRawResponse.md)
- [Creating an instance of TokenCredentialAuthenticationProvider](docs/TokenCredentialAuthenticationProvider.md)
- [Samples and tutorials](#samples-and-tutorials)
- Step-by-step training exercises on creating a basic application using the Microsoft Graph JavaScript SDK:
- [Build Angular single-page apps with Microsoft Graph](https://docs.microsoft.com/graph/tutorials/angular)
- [Build Node.js Express apps with Microsoft Graph](https://docs.microsoft.com/graph/tutorials/node)
- [Build React Native apps with Microsoft Graph](https://docs.microsoft.com/graph/tutorials/react-native)
- [Build React single-page apps with Microsoft Graph](https://docs.microsoft.com/graph/tutorials/react)
- [Build JavaScript single-page apps with Microsoft Graph](https://docs.microsoft.com/graph/tutorials/javascript)
- [Explore Microsoft Graph scenarios for JavaScript development](https://docs.microsoft.com/learn/paths/m365-msgraph-scenarios/)
- Samples using `TokenCredentialAuthenticationProvider` with the `@azure/identity` library:
- [TokenCredentialAuthenticationProvider Samples](samples/)
- Samples using `LargeFileUploadTask` and `OneDriveLargeFileTask`:
- [LargeFileUploadTask Samples](samples/)
- Samples to learn more about authentication using `MSAL`libraries:
- [Azure-Sample Vanilla JS SPA using MSAL Browser and Microsoft Graph JavaScript SDK](https://github.com/Azure-Samples/ms-identity-javascript-tutorial/tree/main/2-Authorization-I/1-call-graph)
- [ Azure-Sample Angular SPA using MSAL Angular and Microsoft Graph JavaScript SDK](https://github.com/Azure-Samples/ms-identity-javascript-angular-tutorial/tree/main/2-Authorization-I/1-call-graph)
- [ Azure-Sample React SPA using MSAL React and Microsoft Graph JavaScript SDK](https://github.com/Azure-Samples/ms-identity-javascript-react-tutorial/tree/main/2-Authorization-I/1-call-graph)
- [Questions and comments](#questions-and-comments)
- [Contributing](#contributing)
- [Additional resources](#additional-resources)
- [Third Party Notices](#third-party-notices)
- [Security Reporting](#security-reporting)
- [License](#license)
- [We Value and Adhere to the Microsoft Open Source Code of Conduct](#we-value-and-adhere-to-the-microsoft-open-source-code-of-conduct)
**Looking for IntelliSense on models (Users, Groups, etc.)? Check out the Microsoft Graph Types [v1.0](https://github.com/microsoftgraph/msgraph-typescript-typings) and [beta](https://github.com/microsoftgraph/msgraph-beta-typescript-typings)!!**
[![TypeScript demo](https://raw.githubusercontent.com/microsoftgraph/msgraph-sdk-javascript/master/types-demo.PNG)](https://github.com/microsoftgraph/msgraph-typescript-typings)
## Node version requirement
Node.js 12 LTS or higher. The active Long Term Service (LTS) version of Node.js is used for on-going testing of existing and upcoming product features.
For Node.js 18 users, it is recommended to disable the experimental `fetch` feature by supplying the `--no-experimental-fetch` command-line flag while using the Microsoft Graph JavaScript client library.
## Installation
### Via npm
```cmd
npm install @microsoft/microsoft-graph-client
```
import `@microsoft/microsoft-graph-client` into your module.
Also, you will need to import any fetch polyfill which suits your requirements. Following are some fetch polyfills -
- [isomorphic-fetch](https://www.npmjs.com/package/isomorphic-fetch).
- [cross-fetch](https://www.npmjs.com/package/cross-fetch)
- [whatwg-fetch](https://www.npmjs.com/package/whatwg-fetch)
```typescript
import "isomorphic-fetch"; // or import the fetch polyfill you installed
import { Client } from "@microsoft/microsoft-graph-client";
```
### Via Script Tag
Include [graph-js-sdk.js](https://cdn.jsdelivr.net/npm/@microsoft/microsoft-graph-client/lib/graph-js-sdk.js) in your HTML page.
```HTML
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/@microsoft/microsoft-graph-client/lib/graph-js-sdk.js"></script>
```
In case your browser doesn't have support for [Fetch](https://developer.mozilla.org/docs/Web/API/Fetch_API) [[support](https://developer.mozilla.org/docs/Web/API/Fetch_API#Browser_compatibility)] or [Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise) [[support](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#Browser_compatibility)], you need to use polyfills like [github/fetch](https://github.com/github/fetch) for fetch and [es6-promise](https://github.com/stefanpenner/es6-promise) for promise.
```HTML
<!-- polyfilling promise -->
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/es6-promise/dist/es6-promise.auto.min.js"></script>
<!-- polyfilling fetch -->
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/whatwg-fetch/dist/fetch.umd.min.js"></script>
<!-- depending on your browser you might wanna include babel polyfill -->
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/@babel/polyfill@7.4.4/dist/polyfill.min.js"></script>
```
## Getting started
### 1. Register your application
To call Microsoft Graph, your app must acquire an access token from the Microsoft identity platform. Learn more about this -
- [Authentication and authorization basics for Microsoft Graph](https://docs.microsoft.com/graph/auth/auth-concepts)
- [Register your app with the Microsoft identity platform](https://docs.microsoft.com/graph/auth-register-app-v2)
### 2. Create a Client Instance
The Microsoft Graph client is designed to make it simple to make calls to Microsoft Graph. You can use a single client instance for the lifetime of the application.
For information on how to create a client instance, see [Creating Client Instance](./docs/CreatingClientInstance.md)
### 3. Make requests to the graph
Once you have authentication setup and an instance of Client, you can begin to make calls to the service. All requests should start with `client.api(path)` and end with an [action](./docs/Actions.md).
Example of getting user details:
```typescript
try {
let userDetails = await client.api("/me").get();
console.log(userDetails);
} catch (error) {
throw error;
}
```
Example of sending an email to the recipients:
```typescript
// Construct email object
const mail = {
subject: "Microsoft Graph JavaScript Sample",
toRecipients: [
{
emailAddress: {
address: "example@example.com",
},
},
],
body: {
content: "<h1>MicrosoftGraph JavaScript Sample</h1>Check out https://github.com/microsoftgraph/msgraph-sdk-javascript",
contentType: "html",
},
};
try {
let response = await client.api("/me/sendMail").post({ message: mail });
console.log(response);
} catch (error) {
throw error;
}
```
For more information, refer: [Calling Pattern](docs/CallingPattern.md), [Actions](docs/Actions.md), [Query Params](docs/QueryParameters.md), [API Methods](docs/OtherAPIs.md) and [more](docs/).
## Samples and tutorials
Step-by-step training exercises that guide you through creating a basic application that accesses data via the Microsoft Graph:
- [Build Angular single-page apps with Microsoft Graph](https://docs.microsoft.com/graph/tutorials/angular)
- [Build Node.js Express apps with Microsoft Graph](https://docs.microsoft.com/graph/tutorials/node)
- [Build React Native apps with Microsoft Graph](https://docs.microsoft.com/graph/tutorials/react-native)
- [Build React single-page apps with Microsoft Graph](https://docs.microsoft.com/graph/tutorials/react)
- [Build JavaScript single-page apps with Microsoft Graph](https://docs.microsoft.com/graph/tutorials/javascript)
- [Explore Microsoft Graph scenarios for JavaScript development](https://docs.microsoft.com/learn/paths/m365-msgraph-scenarios/)
The Microsoft Graph JavaScript SDK provides a `TokenCredentialAuthenticationProvider` to authenticate using the `@azure/identity` auth library. Learn more:
- [Documentation for creating an instance of TokenCredentialAuthenticationProvider](docs/TokenCredentialAuthenticationProvider.md)
- [TokenCredentialAuthenticationProvider Samples](samples/)
The Microsoft Graph JavaScript SDK provides a `LargeFileUploadTask` to upload large files to OneDrive, Outlook and Print API:
- [LargeFileUploadTask documentation](docs/tasks/LargeFileUploadTask.md)
- [Samples using `LargeFileUploadTask` and `OneDriveLargeFileTask`](samples/) The following `MSAL` samples provide information on authentication using `MSAL` libraries and how to use the Microsoft Graph JavaScript SDK client with MSAL as a custom authentication provider to query the Graph API:
- [Azure-Sample Vanilla JS SPA using MSAL Browser and Microsoft Graph JavaScript SDK](https://github.com/Azure-Samples/ms-identity-javascript-tutorial/tree/main/2-Authorization-I/1-call-graph)
- [Azure-Sample Angular SPA using MSAL Angular and Microsoft Graph JavaScript SDK](https://github.com/Azure-Samples/ms-identity-javascript-angular-tutorial/tree/main/2-Authorization-I/1-call-graph)
- [Azure-Sample React SPA using MSAL React and Microsoft Graph JavaScript SDK](https://github.com/Azure-Samples/ms-identity-javascript-react-tutorial/tree/main/2-Authorization-I/1-call-graph)
## Questions and comments
We'd love to get your feedback about the Microsoft Graph JavaScript client library. You can send your questions and suggestions to us in the [Issues](https://github.com/microsoftgraph/msgraph-sdk-javascript/issues) section of this repository.
## Contributing
Please see the [contributing guidelines](CONTRIBUTING.md).
## Additional resources
- [Microsoft Graph website](https://graph.microsoft.io)
- The Microsoft Graph TypeScript definitions enable editors to provide intellisense on Microsoft Graph objects including users, messages, and groups.
- [@microsoft/microsoft-graph-types](https://www.npmjs.com/package/@microsoft/microsoft-graph-types) or [@types/microsoft-graph](https://www.npmjs.com/package/@types/microsoft-graph)
- [@microsoft/microsoft-graph-types-beta](https://www.npmjs.com/package/@microsoft/microsoft-graph-types-beta)
- [Microsoft Graph Toolkit: UI Components and Authentication Providers for Microsoft Graph](https://docs.microsoft.com/graph/toolkit/overview)
- [Office Dev Center](http://dev.office.com/)
## Tips and Tricks
- [Microsoft Graph SDK `n.call is not a function` by Lee Ford](https://www.lee-ford.co.uk/posts/graph-sdk-is-not-a-function/)
- [Example of using the Graph JS library with ESM and `importmaps` ](https://github.com/waldekmastykarz/js-graph-101/blob/main/index_esm.html)
## Third Party Notices
See [Third Party Notices](./THIRD%20PARTY%20NOTICES) for information on the packages that are included in the [package.json](./package.json)
## Security Reporting
If you find a security issue with our libraries or services please report it to [secure@microsoft.com](mailto:secure@microsoft.com) with as much detail as possible. Your submission may be eligible for a bounty through the [Microsoft Bounty](http://aka.ms/bugbounty) program. Please do not post security issues to GitHub Issues or any other public site. We will contact you shortly upon receiving the information. We encourage you to get notifications of when security incidents occur by visiting [this page](https://technet.microsoft.com/security/dd252948) and subscribing to Security Advisory Alerts.
## License
Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License (the "[License](./LICENSE)");
## We Value and Adhere to the Microsoft Open Source Code of Conduct
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.
@@ -0,0 +1,5 @@
The authProviderOptions/ folders contains barrels for exporting Authentication Provider options such as MSAL and Azure Identity Token Credentials.
[tsconfig-sub-cjs.json](../tsconfig-sub-es.json) and [tsconfig-sub-cjs.json](../tsconfig-sub-es.json) contains the config for transpiling the files to authProviders/ output folder.
This approach is used because of the limitations of creating a submodule structure - References - https://github.com/microsoft/TypeScript/issues/8305 https://github.com/microsoft/TypeScript/issues/33079
@@ -0,0 +1,8 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
export * from "../../lib/src/authentication/msal-browser/AuthCodeMSALBrowserAuthenticationProvider";
export * from "../../lib/src/authentication/msalOptions/MSALAuthenticationProviderOptions";
@@ -0,0 +1,8 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
export * from "../../lib/src/authentication/azureTokenCredentials/TokenCredentialAuthenticationProvider";
export * from "../../lib/src/authentication/azureTokenCredentials/ITokenCredentialAuthenticationProviderOptions";
@@ -0,0 +1,8 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
export * from "../../../lib/es/src/authentication/msal-browser/AuthCodeMSALBrowserAuthenticationProvider";
export * from "../../../lib/es/src/authentication/msalOptions/MSALAuthenticationProviderOptions";
@@ -0,0 +1,8 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
export * from "../../../lib/es/src/authentication/azureTokenCredentials/TokenCredentialAuthenticationProvider";
export * from "../../../lib/es/src/authentication/azureTokenCredentials/ITokenCredentialAuthenticationProviderOptions";
@@ -0,0 +1,8 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
export * from "../../lib/src/authentication/msal-browser/AuthCodeMSALBrowserAuthenticationProvider";
export * from "../../lib/src/authentication/msalOptions/MSALAuthenticationProviderOptions";
@@ -0,0 +1,12 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
tslib_1.__exportStar(require("../../lib/src/authentication/msal-browser/AuthCodeMSALBrowserAuthenticationProvider"), exports);
tslib_1.__exportStar(require("../../lib/src/authentication/msalOptions/MSALAuthenticationProviderOptions"), exports);
//# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../authProviderOptions/authCodeMsalBrowser/index.ts"],"names":[],"mappings":";;;AAAA;;;;;GAKG;AACH,8HAAoG;AACpG,qHAA2F"}
@@ -0,0 +1,8 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
export * from "../../lib/src/authentication/azureTokenCredentials/TokenCredentialAuthenticationProvider";
export * from "../../lib/src/authentication/azureTokenCredentials/ITokenCredentialAuthenticationProviderOptions";
@@ -0,0 +1,12 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
tslib_1.__exportStar(require("../../lib/src/authentication/azureTokenCredentials/TokenCredentialAuthenticationProvider"), exports);
tslib_1.__exportStar(require("../../lib/src/authentication/azureTokenCredentials/ITokenCredentialAuthenticationProviderOptions"), exports);
//# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../authProviderOptions/azureTokenCredentials/index.ts"],"names":[],"mappings":";;;AAAA;;;;;GAKG;AACH,mIAAyG;AACzG,2IAAiH"}
@@ -0,0 +1,8 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
export * from "../../../lib/es/src/authentication/msal-browser/AuthCodeMSALBrowserAuthenticationProvider";
export * from "../../../lib/es/src/authentication/msalOptions/MSALAuthenticationProviderOptions";
@@ -0,0 +1,9 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
export * from "../../../lib/es/src/authentication/msal-browser/AuthCodeMSALBrowserAuthenticationProvider";
export * from "../../../lib/es/src/authentication/msalOptions/MSALAuthenticationProviderOptions";
//# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../authProviderOptions/es/authCodeMsalBrowser/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,cAAc,2FAA2F,CAAC;AAC1G,cAAc,kFAAkF,CAAC"}
@@ -0,0 +1,8 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
export * from "../../../lib/es/src/authentication/azureTokenCredentials/TokenCredentialAuthenticationProvider";
export * from "../../../lib/es/src/authentication/azureTokenCredentials/ITokenCredentialAuthenticationProviderOptions";
@@ -0,0 +1,9 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
export * from "../../../lib/es/src/authentication/azureTokenCredentials/TokenCredentialAuthenticationProvider";
export * from "../../../lib/es/src/authentication/azureTokenCredentials/ITokenCredentialAuthenticationProviderOptions";
//# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../authProviderOptions/es/azureTokenCredentials/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,cAAc,gGAAgG,CAAC;AAC/G,cAAc,wGAAwG,CAAC"}
+51
View File
@@ -0,0 +1,51 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
import { GraphRequest } from "./GraphRequest";
import { ClientOptions } from "./IClientOptions";
import { Options } from "./IOptions";
export declare class Client {
/**
* @private
* A member which stores the Client instance options
*/
private config;
/**
* @private
* A member which holds the HTTPClient instance
*/
private httpClient;
/**
* @public
* @static
* To create a client instance with options and initializes the default middleware chain
* @param {Options} options - The options for client instance
* @returns The Client instance
*/
static init(options: Options): Client;
/**
* @public
* @static
* To create a client instance with the Client Options
* @param {ClientOptions} clientOptions - The options object for initializing the client
* @returns The Client instance
*/
static initWithMiddleware(clientOptions: ClientOptions): Client;
/**
* @private
* @constructor
* Creates an instance of Client
* @param {ClientOptions} clientOptions - The options to instantiate the client object
*/
private constructor();
/**
* @public
* Entry point to make requests
* @param {string} path - The path string value
* @returns The graph request instance
*/
api(path: string): GraphRequest;
}
+96
View File
@@ -0,0 +1,96 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @module Client
*/
import { GRAPH_API_VERSION, GRAPH_BASE_URL } from "./Constants";
import { CustomAuthenticationProvider } from "./CustomAuthenticationProvider";
import { GraphRequest } from "./GraphRequest";
import { HTTPClient } from "./HTTPClient";
import { HTTPClientFactory } from "./HTTPClientFactory";
import { validatePolyFilling } from "./ValidatePolyFilling";
export class Client {
/**
* @public
* @static
* To create a client instance with options and initializes the default middleware chain
* @param {Options} options - The options for client instance
* @returns The Client instance
*/
static init(options) {
const clientOptions = {};
for (const i in options) {
if (Object.prototype.hasOwnProperty.call(options, i)) {
clientOptions[i] = i === "authProvider" ? new CustomAuthenticationProvider(options[i]) : options[i];
}
}
return Client.initWithMiddleware(clientOptions);
}
/**
* @public
* @static
* To create a client instance with the Client Options
* @param {ClientOptions} clientOptions - The options object for initializing the client
* @returns The Client instance
*/
static initWithMiddleware(clientOptions) {
return new Client(clientOptions);
}
/**
* @private
* @constructor
* Creates an instance of Client
* @param {ClientOptions} clientOptions - The options to instantiate the client object
*/
constructor(clientOptions) {
/**
* @private
* A member which stores the Client instance options
*/
this.config = {
baseUrl: GRAPH_BASE_URL,
debugLogging: false,
defaultVersion: GRAPH_API_VERSION,
};
validatePolyFilling();
for (const key in clientOptions) {
if (Object.prototype.hasOwnProperty.call(clientOptions, key)) {
this.config[key] = clientOptions[key];
}
}
let httpClient;
if (clientOptions.authProvider !== undefined && clientOptions.middleware !== undefined) {
const error = new Error();
error.name = "AmbiguityInInitialization";
error.message = "Unable to Create Client, Please provide either authentication provider for default middleware chain or custom middleware chain not both";
throw error;
}
else if (clientOptions.authProvider !== undefined) {
httpClient = HTTPClientFactory.createWithAuthenticationProvider(clientOptions.authProvider);
}
else if (clientOptions.middleware !== undefined) {
httpClient = new HTTPClient(...[].concat(clientOptions.middleware));
}
else {
const error = new Error();
error.name = "InvalidMiddlewareChain";
error.message = "Unable to Create Client, Please provide either authentication provider for default middleware chain or custom middleware chain";
throw error;
}
this.httpClient = httpClient;
}
/**
* @public
* Entry point to make requests
* @param {string} path - The path string value
* @returns The graph request instance
*/
api(path) {
return new GraphRequest(this.httpClient, this.config, path);
}
}
//# sourceMappingURL=Client.js.map
@@ -0,0 +1 @@
{"version":3,"file":"Client.js","sourceRoot":"","sources":["../../../src/Client.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH;;GAEG;AAEH,OAAO,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAChE,OAAO,EAAE,4BAA4B,EAAE,MAAM,gCAAgC,CAAC;AAC9E,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAGxD,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAE5D,MAAM,OAAO,MAAM;IAiBlB;;;;;;OAMG;IACI,MAAM,CAAC,IAAI,CAAC,OAAgB;QAClC,MAAM,aAAa,GAAkB,EAAE,CAAC;QACxC,KAAK,MAAM,CAAC,IAAI,OAAO,EAAE;YACxB,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC,EAAE;gBACrD,aAAa,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,cAAc,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C,MAAM,CAAC,aAAa,CAAC,UAAU,CAAC,CAAC,CAAC;SACpE;aAAM;YACN,MAAM,KAAK,GAAG,IAAI,KAAK,EAAE,CAAC;YAC1B,KAAK,CAAC,IAAI,GAAG,wBAAwB,CAAC;YACtC,KAAK,CAAC,OAAO,GAAG,gIAAgI,CAAC;YACjJ,MAAM,KAAK,CAAC;SACZ;QACD,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IAC9B,CAAC;IAED;;;;;OAKG;IACI,GAAG,CAAC,IAAY;QACtB,OAAO,IAAI,YAAY,CAAC,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;IAC7D,CAAC;CACD"}
@@ -0,0 +1,24 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @module Constants
*/
/**
* @constant
* A Default API endpoint version for a request
*/
export declare const GRAPH_API_VERSION = "v1.0";
/**
* @constant
* A Default base url for a request
*/
export declare const GRAPH_BASE_URL = "https://graph.microsoft.com/";
/**
* To hold list of the service root endpoints for Microsoft Graph and Graph Explorer for each national cloud.
* Set(iterable:Object) is not supported in Internet Explorer. The consumer is recommended to use a suitable polyfill.
*/
export declare const GRAPH_URLS: Set<string>;
+25
View File
@@ -0,0 +1,25 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @module Constants
*/
/**
* @constant
* A Default API endpoint version for a request
*/
export const GRAPH_API_VERSION = "v1.0";
/**
* @constant
* A Default base url for a request
*/
export const GRAPH_BASE_URL = "https://graph.microsoft.com/";
/**
* To hold list of the service root endpoints for Microsoft Graph and Graph Explorer for each national cloud.
* Set(iterable:Object) is not supported in Internet Explorer. The consumer is recommended to use a suitable polyfill.
*/
export const GRAPH_URLS = new Set(["graph.microsoft.com", "graph.microsoft.us", "dod-graph.microsoft.us", "graph.microsoft.de", "microsoftgraph.chinacloudapi.cn", "canary.graph.microsoft.com"]);
//# sourceMappingURL=Constants.js.map
@@ -0,0 +1 @@
{"version":3,"file":"Constants.js","sourceRoot":"","sources":["../../../src/Constants.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH;;GAEG;AAEH;;;GAGG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,MAAM,CAAC;AAExC;;;GAGG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,8BAA8B,CAAC;AAE7D;;;GAGG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,IAAI,GAAG,CAAS,CAAC,qBAAqB,EAAE,oBAAoB,EAAE,wBAAwB,EAAE,oBAAoB,EAAE,iCAAiC,EAAE,4BAA4B,CAAC,CAAC,CAAC"}
@@ -0,0 +1,35 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
import { AuthenticationProvider } from "./IAuthenticationProvider";
import { AuthProvider } from "./IAuthProvider";
/**
* @class
* Class representing CustomAuthenticationProvider
* @extends AuthenticationProvider
*/
export declare class CustomAuthenticationProvider implements AuthenticationProvider {
/**
* @private
* A member to hold authProvider callback
*/
private provider;
/**
* @public
* @constructor
* Creates an instance of CustomAuthenticationProvider
* @param {AuthProviderCallback} provider - An authProvider function
* @returns An instance of CustomAuthenticationProvider
*/
constructor(provider: AuthProvider);
/**
* @public
* @async
* To get the access token
* @returns The promise that resolves to an access token
*/
getAccessToken(): Promise<any>;
}
@@ -0,0 +1,56 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
import { __awaiter } from "tslib";
/**
* @module CustomAuthenticationProvider
*/
import { GraphClientError } from "./GraphClientError";
/**
* @class
* Class representing CustomAuthenticationProvider
* @extends AuthenticationProvider
*/
export class CustomAuthenticationProvider {
/**
* @public
* @constructor
* Creates an instance of CustomAuthenticationProvider
* @param {AuthProviderCallback} provider - An authProvider function
* @returns An instance of CustomAuthenticationProvider
*/
constructor(provider) {
this.provider = provider;
}
/**
* @public
* @async
* To get the access token
* @returns The promise that resolves to an access token
*/
getAccessToken() {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
this.provider((error, accessToken) => __awaiter(this, void 0, void 0, function* () {
if (accessToken) {
resolve(accessToken);
}
else {
if (!error) {
const invalidTokenMessage = "Access token is undefined or empty.\
Please provide a valid token.\
For more help - https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/CustomAuthenticationProvider.md";
error = new GraphClientError(invalidTokenMessage);
}
const err = yield GraphClientError.setGraphClientError(error);
reject(err);
}
}));
});
});
}
}
//# sourceMappingURL=CustomAuthenticationProvider.js.map
@@ -0,0 +1 @@
{"version":3,"file":"CustomAuthenticationProvider.js","sourceRoot":"","sources":["../../../src/CustomAuthenticationProvider.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;;AAEH;;GAEG;AAEH,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAItD;;;;GAIG;AACH,MAAM,OAAO,4BAA4B;IAOxC;;;;;;OAMG;IACH,YAAmB,QAAsB;QACxC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC1B,CAAC;IAED;;;;;OAKG;IACU,cAAc;;YAC1B,OAAO,IAAI,OAAO,CAAC,CAAC,OAAsC,EAAE,MAA4B,EAAE,EAAE;gBAC3F,IAAI,CAAC,QAAQ,CAAC,CAAO,KAAU,EAAE,WAA0B,EAAE,EAAE;oBAC9D,IAAI,WAAW,EAAE;wBAChB,OAAO,CAAC,WAAW,CAAC,CAAC;qBACrB;yBAAM;wBACN,IAAI,CAAC,KAAK,EAAE;4BACX,MAAM,mBAAmB,GAAG;;6HAE2F,CAAC;4BACxH,KAAK,GAAG,IAAI,gBAAgB,CAAC,mBAAmB,CAAC,CAAC;yBAClD;wBACD,MAAM,GAAG,GAAG,MAAM,gBAAgB,CAAC,mBAAmB,CAAC,KAAK,CAAC,CAAC;wBAC9D,MAAM,CAAC,GAAG,CAAC,CAAC;qBACZ;gBACF,CAAC,CAAA,CAAC,CAAC;YACJ,CAAC,CAAC,CAAC;QACJ,CAAC;KAAA;CACD"}
@@ -0,0 +1,44 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @module GraphClientError
*/
/**
* @class
* Create GraphClientError object to handle client-side errors
* encountered within the JavaScript Client SDK.
* Whereas GraphError Class should be used to handle errors in the response from the Graph API.
*/
export declare class GraphClientError extends Error {
/**
* @public
* A custom error. This property should set be when the error is not of instanceOf Error/GraphClientError.
* Example =
* const client = MicrosoftGraph.Client.init({
* defaultVersion: "v1.0",
* authProvider: (done) => { done({TokenError:"AccessToken cannot be null"}, "<ACCESS_TOKEN>");
* });
*/
customError?: any;
/**
* @public
* @static
* @async
* To set the GraphClientError object
* @param {any} error - The error returned encountered by the Graph JavaScript Client SDK while processing request
* @returns GraphClientError object set to the error passed
*/
static setGraphClientError(error: any): GraphClientError;
/**
* @public
* @constructor
* Creates an instance of GraphClientError
* @param {string} message? - Error message
* @returns An instance of GraphClientError
*/
constructor(message?: string);
}
@@ -0,0 +1,48 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @module GraphClientError
*/
/**
* @class
* Create GraphClientError object to handle client-side errors
* encountered within the JavaScript Client SDK.
* Whereas GraphError Class should be used to handle errors in the response from the Graph API.
*/
export class GraphClientError extends Error {
/**
* @public
* @static
* @async
* To set the GraphClientError object
* @param {any} error - The error returned encountered by the Graph JavaScript Client SDK while processing request
* @returns GraphClientError object set to the error passed
*/
static setGraphClientError(error) {
let graphClientError;
if (error instanceof Error) {
graphClientError = error;
}
else {
graphClientError = new GraphClientError();
graphClientError.customError = error;
}
return graphClientError;
}
/**
* @public
* @constructor
* Creates an instance of GraphClientError
* @param {string} message? - Error message
* @returns An instance of GraphClientError
*/
constructor(message) {
super(message);
Object.setPrototypeOf(this, GraphClientError.prototype);
}
}
//# sourceMappingURL=GraphClientError.js.map
@@ -0,0 +1 @@
{"version":3,"file":"GraphClientError.js","sourceRoot":"","sources":["../../../src/GraphClientError.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH;;GAEG;AAEH;;;;;GAKG;AAEH,MAAM,OAAO,gBAAiB,SAAQ,KAAK;IAY1C;;;;;;;OAOG;IACI,MAAM,CAAC,mBAAmB,CAAC,KAAU;QAC3C,IAAI,gBAAkC,CAAC;QACvC,IAAI,KAAK,YAAY,KAAK,EAAE;YAC3B,gBAAgB,GAAG,KAAK,CAAC;SACzB;aAAM;YACN,gBAAgB,GAAG,IAAI,gBAAgB,EAAE,CAAC;YAC1C,gBAAgB,CAAC,WAAW,GAAG,KAAK,CAAC;SACrC;QACD,OAAO,gBAAgB,CAAC;IACzB,CAAC;IAED;;;;;;OAMG;IACH,YAAmB,OAAgB;QAClC,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,gBAAgB,CAAC,SAAS,CAAC,CAAC;IACzD,CAAC;CACD"}
@@ -0,0 +1,54 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @module GraphError
*/
/**
* @class
* Class for GraphError
* @NOTE: This is NOT what is returned from the Graph
* GraphError is created from parsing JSON errors returned from the graph
* Some fields are renamed ie, "request-id" => requestId so you can use dot notation
*/
export declare class GraphError extends Error {
/**
* @public
* A member holding status code of the error
*/
statusCode: number;
/**
* @public
* A member holding code i.e name of the error
*/
code: string | null;
/**
* @public
* A member holding request-id i.e identifier of the request
*/
requestId: string | null;
/**
* @public
* A member holding processed date and time of the request
*/
date: Date;
headers?: Headers;
/**
* @public
* A member holding original error response by the graph service
*/
body: any;
/**
* @public
* @constructor
* Creates an instance of GraphError
* @param {number} [statusCode = -1] - The status code of the error
* @param {string} [message] - The message of the error
* @param {Error} [baseError] - The base error
* @returns An instance of GraphError
*/
constructor(statusCode?: number, message?: string, baseError?: Error);
}
@@ -0,0 +1,39 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @module GraphError
*/
/**
* @class
* Class for GraphError
* @NOTE: This is NOT what is returned from the Graph
* GraphError is created from parsing JSON errors returned from the graph
* Some fields are renamed ie, "request-id" => requestId so you can use dot notation
*/
export class GraphError extends Error {
/**
* @public
* @constructor
* Creates an instance of GraphError
* @param {number} [statusCode = -1] - The status code of the error
* @param {string} [message] - The message of the error
* @param {Error} [baseError] - The base error
* @returns An instance of GraphError
*/
constructor(statusCode = -1, message, baseError) {
super(message || (baseError && baseError.message));
// https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
Object.setPrototypeOf(this, GraphError.prototype);
this.statusCode = statusCode;
this.code = null;
this.requestId = null;
this.date = new Date();
this.body = null;
this.stack = baseError ? baseError.stack : this.stack;
}
}
//# sourceMappingURL=GraphError.js.map
@@ -0,0 +1 @@
{"version":3,"file":"GraphError.js","sourceRoot":"","sources":["../../../src/GraphError.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH;;GAEG;AAEH;;;;;;GAMG;AAEH,MAAM,OAAO,UAAW,SAAQ,KAAK;IAiCpC;;;;;;;;OAQG;IACH,YAAmB,UAAU,GAAG,CAAC,CAAC,EAAE,OAAgB,EAAE,SAAiB;QACtE,KAAK,CAAC,OAAO,IAAI,CAAC,SAAS,IAAI,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC;QACnD,gIAAgI;QAChI,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,UAAU,CAAC,SAAS,CAAC,CAAC;QAClD,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,IAAI,CAAC,IAAI,GAAG,IAAI,IAAI,EAAE,CAAC;QACvB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,KAAK,GAAG,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC;IACvD,CAAC;CACD"}
@@ -0,0 +1,60 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @module GraphErrorHandler
*/
import { GraphError } from "./GraphError";
import { GraphRequestCallback } from "./IGraphRequestCallback";
/**
* @class
* Class for GraphErrorHandler
*/
export declare class GraphErrorHandler {
/**
* @private
* @static
* Populates the GraphError instance with Error instance values
* @param {Error} error - The error returned by graph service or some native error
* @param {number} [statusCode] - The status code of the response
* @returns The GraphError instance
*/
private static constructError;
/**
* @private
* @static
* @async
* Populates the GraphError instance from the Error returned by graph service
* @param {GraphAPIErrorResponse} graphError - The error possibly returned by graph service or some native error
* @param {number} statusCode - The status code of the response
* @returns A promise that resolves to GraphError instance
*
* Example error for https://graph.microsoft.com/v1.0/me/events?$top=3&$search=foo
* {
* "error": {
* "code": "SearchEvents",
* "message": "The parameter $search is not currently supported on the Events resource.",
* "innerError": {
* "request-id": "b31c83fd-944c-4663-aa50-5d9ceb367e19",
* "date": "2016-11-17T18:37:45"
* }
* }
* }
*/
private static constructErrorFromResponse;
/**
* @public
* @static
* @async
* To get the GraphError object
* Reference - https://docs.microsoft.com/en-us/graph/errors
* @param {any} [error = null] - The error returned by graph service or some native error
* @param {number} [statusCode = -1] - The status code of the response
* @param {GraphRequestCallback} [callback] - The graph request callback function
* @returns A promise that resolves to GraphError instance
*/
static getError(error?: any, statusCode?: number, callback?: GraphRequestCallback, rawResponse?: Response): Promise<GraphError>;
}
@@ -0,0 +1,101 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
import { __awaiter } from "tslib";
/**
* @module GraphErrorHandler
*/
import { GraphError } from "./GraphError";
/**
* @class
* Class for GraphErrorHandler
*/
export class GraphErrorHandler {
/**
* @private
* @static
* Populates the GraphError instance with Error instance values
* @param {Error} error - The error returned by graph service or some native error
* @param {number} [statusCode] - The status code of the response
* @returns The GraphError instance
*/
static constructError(error, statusCode, rawResponse) {
const gError = new GraphError(statusCode, "", error);
if (error.name !== undefined) {
gError.code = error.name;
}
gError.body = error.toString();
gError.date = new Date();
gError.headers = rawResponse === null || rawResponse === void 0 ? void 0 : rawResponse.headers;
return gError;
}
/**
* @private
* @static
* @async
* Populates the GraphError instance from the Error returned by graph service
* @param {GraphAPIErrorResponse} graphError - The error possibly returned by graph service or some native error
* @param {number} statusCode - The status code of the response
* @returns A promise that resolves to GraphError instance
*
* Example error for https://graph.microsoft.com/v1.0/me/events?$top=3&$search=foo
* {
* "error": {
* "code": "SearchEvents",
* "message": "The parameter $search is not currently supported on the Events resource.",
* "innerError": {
* "request-id": "b31c83fd-944c-4663-aa50-5d9ceb367e19",
* "date": "2016-11-17T18:37:45"
* }
* }
* }
*/
static constructErrorFromResponse(graphError, statusCode, rawResponse) {
const error = graphError.error;
const gError = new GraphError(statusCode, error.message);
gError.code = error.code;
if (error.innerError !== undefined) {
gError.requestId = error.innerError["request-id"];
gError.date = new Date(error.innerError.date);
}
gError.body = JSON.stringify(error);
gError.headers = rawResponse === null || rawResponse === void 0 ? void 0 : rawResponse.headers;
return gError;
}
/**
* @public
* @static
* @async
* To get the GraphError object
* Reference - https://docs.microsoft.com/en-us/graph/errors
* @param {any} [error = null] - The error returned by graph service or some native error
* @param {number} [statusCode = -1] - The status code of the response
* @param {GraphRequestCallback} [callback] - The graph request callback function
* @returns A promise that resolves to GraphError instance
*/
static getError(error = null, statusCode = -1, callback, rawResponse) {
return __awaiter(this, void 0, void 0, function* () {
let gError;
if (error && error.error) {
gError = GraphErrorHandler.constructErrorFromResponse(error, statusCode, rawResponse);
}
else if (error instanceof Error) {
gError = GraphErrorHandler.constructError(error, statusCode, rawResponse);
}
else {
gError = new GraphError(statusCode);
gError.body = error; // if a custom error is passed which is not instance of Error object or a graph API response
}
if (typeof callback === "function") {
callback(gError, null);
}
else {
return gError;
}
});
}
}
//# sourceMappingURL=GraphErrorHandler.js.map
@@ -0,0 +1 @@
{"version":3,"file":"GraphErrorHandler.js","sourceRoot":"","sources":["../../../src/GraphErrorHandler.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;;AAEH;;GAEG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAiB1C;;;GAGG;AAEH,MAAM,OAAO,iBAAiB;IAC7B;;;;;;;OAOG;IACK,MAAM,CAAC,cAAc,CAAC,KAAY,EAAE,UAAmB,EAAE,WAAsB;QACtF,MAAM,MAAM,GAAG,IAAI,UAAU,CAAC,UAAU,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;QACrD,IAAI,KAAK,CAAC,IAAI,KAAK,SAAS,EAAE;YAC7B,MAAM,CAAC,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC;SACzB;QACD,MAAM,CAAC,IAAI,GAAG,KAAK,CAAC,QAAQ,EAAE,CAAC;QAC/B,MAAM,CAAC,IAAI,GAAG,IAAI,IAAI,EAAE,CAAC;QACzB,MAAM,CAAC,OAAO,GAAG,WAAW,aAAX,WAAW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CAAC,CAAC;gBACpC,MAAM,CAAC,IAAI,GAAG,KAAK,CAAC,CAAC,4FAA4F;aACjH;YACD,IAAI,OAAO,QAAQ,KAAK,UAAU,EAAE;gBACnC,QAAQ,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;aACvB;iBAAM;gBACN,OAAO,MAAM,CAAC;aACd;QACF,CAAC;KAAA;CACD"}
@@ -0,0 +1,380 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
import { HTTPClient } from "./HTTPClient";
import { ClientOptions } from "./IClientOptions";
import { GraphRequestCallback } from "./IGraphRequestCallback";
import { MiddlewareOptions } from "./middleware/options/IMiddlewareOptions";
import { ResponseType } from "./ResponseType";
/**
* @interface
* Signature to representing key value pairs
* @property {[key: string] : string | number} - The Key value pair
*/
interface KeyValuePairObjectStringNumber {
[key: string]: string | number;
}
/**
* @interface
* Signature to define URL components
* @template http://graph.microsoft.com/VERSION/PATH?QUERYSTRING&OTHER_QUERY_PARAMS
*
* @property {string} host - The host to which the request needs to be made
* @property {string} version - Version of the graph endpoint
* @property {string} [path] - The path of the resource request
* @property {KeyValuePairObjectStringNumber} oDataQueryParams - The oData Query Params
* @property {KeyValuePairObjectStringNumber} otherURLQueryParams - The other query params for a request
* @property {string[]} otherURLQueryOptions - The non key-value query parameters. Example- '/me?$whatif'
*/
export interface URLComponents {
host: string;
version: string;
path?: string;
oDataQueryParams: KeyValuePairObjectStringNumber;
otherURLQueryParams: KeyValuePairObjectStringNumber;
otherURLQueryOptions?: string[];
}
/**
* @class
* A Class representing GraphRequest
*/
export declare class GraphRequest {
/**
* @private
* A member variable to hold HTTPClient instance
*/
private httpClient;
/**
* @private
* A member variable to hold client options
*/
private config;
/**
* @private
* A member to hold URL Components data
*/
private urlComponents;
/**
* @private
* A member to hold custom header options for a request
*/
private _headers;
/**
* @private
* A member to hold custom options for a request
*/
private _options;
/**
* @private
* A member to hold the array of middleware options for a request
*/
private _middlewareOptions;
/**
* @private
* A member to hold custom response type for a request
*/
private _responseType;
/**
* @public
* @constructor
* Creates an instance of GraphRequest
* @param {HTTPClient} httpClient - The HTTPClient instance
* @param {ClientOptions} config - The options for making request
* @param {string} path - A path string
*/
constructor(httpClient: HTTPClient, config: ClientOptions, path: string);
/**
* @private
* Parses the path string and creates URLComponents out of it
* @param {string} path - The request path string
* @returns Nothing
*/
private parsePath;
/**
* @private
* Adds the query parameter as comma separated values
* @param {string} propertyName - The name of a property
* @param {string|string[]} propertyValue - The vale of a property
* @param {IArguments} additionalProperties - The additional properties
* @returns Nothing
*/
private addCsvQueryParameter;
/**
* @private
* Builds the full url from the URLComponents to make a request
* @returns The URL string that is qualified to make a request to graph endpoint
*/
private buildFullUrl;
/**
* @private
* Builds the query string from the URLComponents
* @returns The Constructed query string
*/
private createQueryString;
/**
* @private
* Parses the query parameters to set the urlComponents property of the GraphRequest object
* @param {string|KeyValuePairObjectStringNumber} queryDictionaryOrString - The query parameter
* @returns The same GraphRequest instance that is being called with
*/
private parseQueryParameter;
/**
* @private
* Parses the query parameter of string type to set the urlComponents property of the GraphRequest object
* @param {string} queryParameter - the query parameters
* returns nothing
*/
private parseQueryParamenterString;
/**
* @private
* Sets values into the urlComponents property of GraphRequest object.
* @param {string} paramKey - the query parameter key
* @param {string} paramValue - the query paramter value
* @returns nothing
*/
private setURLComponentsQueryParamater;
/**
* @private
* Check if the query parameter string has a valid key-value structure
* @param {string} queryString - the query parameter string. Example -> "name=value"
* #returns true if the query string has a valid key-value structure else false
*/
private isValidQueryKeyValuePair;
/**
* @private
* Updates the custom headers and options for a request
* @param {FetchOptions} options - The request options object
* @returns Nothing
*/
private updateRequestOptions;
/**
* @private
* @async
* Adds the custom headers and options to the request and makes the HTTPClient send request call
* @param {RequestInfo} request - The request url string or the Request object value
* @param {FetchOptions} options - The options to make a request
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the response content
*/
private send;
/**
* @private
* Checks if the content-type is present in the _headers property. If not present, defaults the content-type to application/json
* @param none
* @returns nothing
*/
private setHeaderContentType;
/**
* @public
* Sets the custom header for a request
* @param {string} headerKey - A header key
* @param {string} headerValue - A header value
* @returns The same GraphRequest instance that is being called with
*/
header(headerKey: string, headerValue: string): GraphRequest;
/**
* @public
* Sets the custom headers for a request
* @param {KeyValuePairObjectStringNumber | HeadersInit} headers - The request headers
* @returns The same GraphRequest instance that is being called with
*/
headers(headers: KeyValuePairObjectStringNumber | HeadersInit): GraphRequest;
/**
* @public
* Sets the option for making a request
* @param {string} key - The key value
* @param {any} value - The value
* @returns The same GraphRequest instance that is being called with
*/
option(key: string, value: any): GraphRequest;
/**
* @public
* Sets the options for making a request
* @param {{ [key: string]: any }} options - The options key value pair
* @returns The same GraphRequest instance that is being called with
*/
options(options: {
[key: string]: any;
}): GraphRequest;
/**
* @public
* Sets the middleware options for a request
* @param {MiddlewareOptions[]} options - The array of middleware options
* @returns The same GraphRequest instance that is being called with
*/
middlewareOptions(options: MiddlewareOptions[]): GraphRequest;
/**
* @public
* Sets the api endpoint version for a request
* @param {string} version - The version value
* @returns The same GraphRequest instance that is being called with
*/
version(version: string): GraphRequest;
/**
* @public
* Sets the api endpoint version for a request
* @param {ResponseType} responseType - The response type value
* @returns The same GraphRequest instance that is being called with
*/
responseType(responseType: ResponseType): GraphRequest;
/**
* @public
* To add properties for select OData Query param
* @param {string|string[]} properties - The Properties value
* @returns The same GraphRequest instance that is being called with, after adding the properties for $select query
*/
select(properties: string | string[]): GraphRequest;
/**
* @public
* To add properties for expand OData Query param
* @param {string|string[]} properties - The Properties value
* @returns The same GraphRequest instance that is being called with, after adding the properties for $expand query
*/
expand(properties: string | string[]): GraphRequest;
/**
* @public
* To add properties for orderby OData Query param
* @param {string|string[]} properties - The Properties value
* @returns The same GraphRequest instance that is being called with, after adding the properties for $orderby query
*/
orderby(properties: string | string[]): GraphRequest;
/**
* @public
* To add query string for filter OData Query param. The request URL accepts only one $filter Odata Query option and its value is set to the most recently passed filter query string.
* @param {string} filterStr - The filter query string
* @returns The same GraphRequest instance that is being called with, after adding the $filter query
*/
filter(filterStr: string): GraphRequest;
/**
* @public
* To add criterion for search OData Query param. The request URL accepts only one $search Odata Query option and its value is set to the most recently passed search criterion string.
* @param {string} searchStr - The search criterion string
* @returns The same GraphRequest instance that is being called with, after adding the $search query criteria
*/
search(searchStr: string): GraphRequest;
/**
* @public
* To add number for top OData Query param. The request URL accepts only one $top Odata Query option and its value is set to the most recently passed number value.
* @param {number} n - The number value
* @returns The same GraphRequest instance that is being called with, after adding the number for $top query
*/
top(n: number): GraphRequest;
/**
* @public
* To add number for skip OData Query param. The request URL accepts only one $skip Odata Query option and its value is set to the most recently passed number value.
* @param {number} n - The number value
* @returns The same GraphRequest instance that is being called with, after adding the number for the $skip query
*/
skip(n: number): GraphRequest;
/**
* @public
* To add token string for skipToken OData Query param. The request URL accepts only one $skipToken Odata Query option and its value is set to the most recently passed token value.
* @param {string} token - The token value
* @returns The same GraphRequest instance that is being called with, after adding the token string for $skipToken query option
*/
skipToken(token: string): GraphRequest;
/**
* @public
* To add boolean for count OData Query param. The URL accepts only one $count Odata Query option and its value is set to the most recently passed boolean value.
* @param {boolean} isCount - The count boolean
* @returns The same GraphRequest instance that is being called with, after adding the boolean value for the $count query option
*/
count(isCount?: boolean): GraphRequest;
/**
* @public
* Appends query string to the urlComponent
* @param {string|KeyValuePairObjectStringNumber} queryDictionaryOrString - The query value
* @returns The same GraphRequest instance that is being called with, after appending the query string to the url component
*/
query(queryDictionaryOrString: string | KeyValuePairObjectStringNumber): GraphRequest;
/**
* @public
* @async
* Makes a http request with GET method
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the get response
*/
get(callback?: GraphRequestCallback): Promise<any>;
/**
* @public
* @async
* Makes a http request with POST method
* @param {any} content - The content that needs to be sent with the request
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the post response
*/
post(content: any, callback?: GraphRequestCallback): Promise<any>;
/**
* @public
* @async
* Alias for Post request call
* @param {any} content - The content that needs to be sent with the request
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the post response
*/
create(content: any, callback?: GraphRequestCallback): Promise<any>;
/**
* @public
* @async
* Makes http request with PUT method
* @param {any} content - The content that needs to be sent with the request
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the put response
*/
put(content: any, callback?: GraphRequestCallback): Promise<any>;
/**
* @public
* @async
* Makes http request with PATCH method
* @param {any} content - The content that needs to be sent with the request
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the patch response
*/
patch(content: any, callback?: GraphRequestCallback): Promise<any>;
/**
* @public
* @async
* Alias for PATCH request
* @param {any} content - The content that needs to be sent with the request
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the patch response
*/
update(content: any, callback?: GraphRequestCallback): Promise<any>;
/**
* @public
* @async
* Makes http request with DELETE method
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the delete response
*/
delete(callback?: GraphRequestCallback): Promise<any>;
/**
* @public
* @async
* Alias for delete request call
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the delete response
*/
del(callback?: GraphRequestCallback): Promise<any>;
/**
* @public
* @async
* Makes a http request with GET method to read response as a stream.
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the getStream response
*/
getStream(callback?: GraphRequestCallback): Promise<any>;
/**
* @public
* @async
* Makes a http request with GET method to read response as a stream.
* @param {any} stream - The stream instance
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the putStream response
*/
putStream(stream: any, callback?: GraphRequestCallback): Promise<any>;
}
export {};
@@ -0,0 +1,688 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
import { __awaiter } from "tslib";
/**
* @module GraphRequest
*/
import { GraphClientError } from "./GraphClientError";
import { GraphErrorHandler } from "./GraphErrorHandler";
import { oDataQueryNames, serializeContent, urlJoin } from "./GraphRequestUtil";
import { GraphResponseHandler } from "./GraphResponseHandler";
import { MiddlewareControl } from "./middleware/MiddlewareControl";
import { RequestMethod } from "./RequestMethod";
import { ResponseType } from "./ResponseType";
/**
* @class
* A Class representing GraphRequest
*/
export class GraphRequest {
/**
* @public
* @constructor
* Creates an instance of GraphRequest
* @param {HTTPClient} httpClient - The HTTPClient instance
* @param {ClientOptions} config - The options for making request
* @param {string} path - A path string
*/
constructor(httpClient, config, path) {
/**
* @private
* Parses the path string and creates URLComponents out of it
* @param {string} path - The request path string
* @returns Nothing
*/
this.parsePath = (path) => {
// Strips out the base of the url if they passed in
if (path.indexOf("https://") !== -1) {
path = path.replace("https://", "");
// Find where the host ends
const endOfHostStrPos = path.indexOf("/");
if (endOfHostStrPos !== -1) {
// Parse out the host
this.urlComponents.host = "https://" + path.substring(0, endOfHostStrPos);
// Strip the host from path
path = path.substring(endOfHostStrPos + 1, path.length);
}
// Remove the following version
const endOfVersionStrPos = path.indexOf("/");
if (endOfVersionStrPos !== -1) {
// Parse out the version
this.urlComponents.version = path.substring(0, endOfVersionStrPos);
// Strip version from path
path = path.substring(endOfVersionStrPos + 1, path.length);
}
}
// Strip out any leading "/"
if (path.charAt(0) === "/") {
path = path.substr(1);
}
const queryStrPos = path.indexOf("?");
if (queryStrPos === -1) {
// No query string
this.urlComponents.path = path;
}
else {
this.urlComponents.path = path.substr(0, queryStrPos);
// Capture query string into oDataQueryParams and otherURLQueryParams
const queryParams = path.substring(queryStrPos + 1, path.length).split("&");
for (const queryParam of queryParams) {
this.parseQueryParameter(queryParam);
}
}
};
this.httpClient = httpClient;
this.config = config;
this.urlComponents = {
host: this.config.baseUrl,
version: this.config.defaultVersion,
oDataQueryParams: {},
otherURLQueryParams: {},
otherURLQueryOptions: [],
};
this._headers = {};
this._options = {};
this._middlewareOptions = [];
this.parsePath(path);
}
/**
* @private
* Adds the query parameter as comma separated values
* @param {string} propertyName - The name of a property
* @param {string|string[]} propertyValue - The vale of a property
* @param {IArguments} additionalProperties - The additional properties
* @returns Nothing
*/
addCsvQueryParameter(propertyName, propertyValue, additionalProperties) {
// If there are already $propertyName value there, append a ","
this.urlComponents.oDataQueryParams[propertyName] = this.urlComponents.oDataQueryParams[propertyName] ? this.urlComponents.oDataQueryParams[propertyName] + "," : "";
let allValues = [];
if (additionalProperties.length > 1 && typeof propertyValue === "string") {
allValues = Array.prototype.slice.call(additionalProperties);
}
else if (typeof propertyValue === "string") {
allValues.push(propertyValue);
}
else {
allValues = allValues.concat(propertyValue);
}
this.urlComponents.oDataQueryParams[propertyName] += allValues.join(",");
}
/**
* @private
* Builds the full url from the URLComponents to make a request
* @returns The URL string that is qualified to make a request to graph endpoint
*/
buildFullUrl() {
const url = urlJoin([this.urlComponents.host, this.urlComponents.version, this.urlComponents.path]) + this.createQueryString();
if (this.config.debugLogging) {
console.log(url);
}
return url;
}
/**
* @private
* Builds the query string from the URLComponents
* @returns The Constructed query string
*/
createQueryString() {
// Combining query params from oDataQueryParams and otherURLQueryParams
const urlComponents = this.urlComponents;
const query = [];
if (Object.keys(urlComponents.oDataQueryParams).length !== 0) {
for (const property in urlComponents.oDataQueryParams) {
if (Object.prototype.hasOwnProperty.call(urlComponents.oDataQueryParams, property)) {
query.push(property + "=" + urlComponents.oDataQueryParams[property]);
}
}
}
if (Object.keys(urlComponents.otherURLQueryParams).length !== 0) {
for (const property in urlComponents.otherURLQueryParams) {
if (Object.prototype.hasOwnProperty.call(urlComponents.otherURLQueryParams, property)) {
query.push(property + "=" + urlComponents.otherURLQueryParams[property]);
}
}
}
if (urlComponents.otherURLQueryOptions.length !== 0) {
for (const str of urlComponents.otherURLQueryOptions) {
query.push(str);
}
}
return query.length > 0 ? "?" + query.join("&") : "";
}
/**
* @private
* Parses the query parameters to set the urlComponents property of the GraphRequest object
* @param {string|KeyValuePairObjectStringNumber} queryDictionaryOrString - The query parameter
* @returns The same GraphRequest instance that is being called with
*/
parseQueryParameter(queryDictionaryOrString) {
if (typeof queryDictionaryOrString === "string") {
if (queryDictionaryOrString.charAt(0) === "?") {
queryDictionaryOrString = queryDictionaryOrString.substring(1);
}
if (queryDictionaryOrString.indexOf("&") !== -1) {
const queryParams = queryDictionaryOrString.split("&");
for (const str of queryParams) {
this.parseQueryParamenterString(str);
}
}
else {
this.parseQueryParamenterString(queryDictionaryOrString);
}
}
else if (queryDictionaryOrString.constructor === Object) {
for (const key in queryDictionaryOrString) {
if (Object.prototype.hasOwnProperty.call(queryDictionaryOrString, key)) {
this.setURLComponentsQueryParamater(key, queryDictionaryOrString[key]);
}
}
}
return this;
}
/**
* @private
* Parses the query parameter of string type to set the urlComponents property of the GraphRequest object
* @param {string} queryParameter - the query parameters
* returns nothing
*/
parseQueryParamenterString(queryParameter) {
/* The query key-value pair must be split on the first equals sign to avoid errors in parsing nested query parameters.
Example-> "/me?$expand=home($select=city)" */
if (this.isValidQueryKeyValuePair(queryParameter)) {
const indexOfFirstEquals = queryParameter.indexOf("=");
const paramKey = queryParameter.substring(0, indexOfFirstEquals);
const paramValue = queryParameter.substring(indexOfFirstEquals + 1);
this.setURLComponentsQueryParamater(paramKey, paramValue);
}
else {
/* Push values which are not of key-value structure.
Example-> Handle an invalid input->.query(test), .query($select($select=name)) and let the Graph API respond with the error in the URL*/
this.urlComponents.otherURLQueryOptions.push(queryParameter);
}
}
/**
* @private
* Sets values into the urlComponents property of GraphRequest object.
* @param {string} paramKey - the query parameter key
* @param {string} paramValue - the query paramter value
* @returns nothing
*/
setURLComponentsQueryParamater(paramKey, paramValue) {
if (oDataQueryNames.indexOf(paramKey) !== -1) {
const currentValue = this.urlComponents.oDataQueryParams[paramKey];
const isValueAppendable = currentValue && (paramKey === "$expand" || paramKey === "$select" || paramKey === "$orderby");
this.urlComponents.oDataQueryParams[paramKey] = isValueAppendable ? currentValue + "," + paramValue : paramValue;
}
else {
this.urlComponents.otherURLQueryParams[paramKey] = paramValue;
}
}
/**
* @private
* Check if the query parameter string has a valid key-value structure
* @param {string} queryString - the query parameter string. Example -> "name=value"
* #returns true if the query string has a valid key-value structure else false
*/
isValidQueryKeyValuePair(queryString) {
const indexofFirstEquals = queryString.indexOf("=");
if (indexofFirstEquals === -1) {
return false;
}
const indexofOpeningParanthesis = queryString.indexOf("(");
if (indexofOpeningParanthesis !== -1 && queryString.indexOf("(") < indexofFirstEquals) {
// Example -> .query($select($expand=true));
return false;
}
return true;
}
/**
* @private
* Updates the custom headers and options for a request
* @param {FetchOptions} options - The request options object
* @returns Nothing
*/
updateRequestOptions(options) {
const optionsHeaders = Object.assign({}, options.headers);
if (this.config.fetchOptions !== undefined) {
const fetchOptions = Object.assign({}, this.config.fetchOptions);
Object.assign(options, fetchOptions);
if (typeof this.config.fetchOptions.headers !== undefined) {
options.headers = Object.assign({}, this.config.fetchOptions.headers);
}
}
Object.assign(options, this._options);
if (options.headers !== undefined) {
Object.assign(optionsHeaders, options.headers);
}
Object.assign(optionsHeaders, this._headers);
options.headers = optionsHeaders;
}
/**
* @private
* @async
* Adds the custom headers and options to the request and makes the HTTPClient send request call
* @param {RequestInfo} request - The request url string or the Request object value
* @param {FetchOptions} options - The options to make a request
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the response content
*/
send(request, options, callback) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
let rawResponse;
const middlewareControl = new MiddlewareControl(this._middlewareOptions);
this.updateRequestOptions(options);
const customHosts = (_a = this.config) === null || _a === void 0 ? void 0 : _a.customHosts;
try {
const context = yield this.httpClient.sendRequest({
request,
options,
middlewareControl,
customHosts,
});
rawResponse = context.response;
const response = yield GraphResponseHandler.getResponse(rawResponse, this._responseType, callback);
return response;
}
catch (error) {
if (error instanceof GraphClientError) {
throw error;
}
let statusCode;
if (rawResponse) {
statusCode = rawResponse.status;
}
const gError = yield GraphErrorHandler.getError(error, statusCode, callback, rawResponse);
throw gError;
}
});
}
/**
* @private
* Checks if the content-type is present in the _headers property. If not present, defaults the content-type to application/json
* @param none
* @returns nothing
*/
setHeaderContentType() {
if (!this._headers) {
this.header("Content-Type", "application/json");
return;
}
const headerKeys = Object.keys(this._headers);
for (const headerKey of headerKeys) {
if (headerKey.toLowerCase() === "content-type") {
return;
}
}
// Default the content-type to application/json in case the content-type is not present in the header
this.header("Content-Type", "application/json");
}
/**
* @public
* Sets the custom header for a request
* @param {string} headerKey - A header key
* @param {string} headerValue - A header value
* @returns The same GraphRequest instance that is being called with
*/
header(headerKey, headerValue) {
this._headers[headerKey] = headerValue;
return this;
}
/**
* @public
* Sets the custom headers for a request
* @param {KeyValuePairObjectStringNumber | HeadersInit} headers - The request headers
* @returns The same GraphRequest instance that is being called with
*/
headers(headers) {
for (const key in headers) {
if (Object.prototype.hasOwnProperty.call(headers, key)) {
this._headers[key] = headers[key];
}
}
return this;
}
/**
* @public
* Sets the option for making a request
* @param {string} key - The key value
* @param {any} value - The value
* @returns The same GraphRequest instance that is being called with
*/
option(key, value) {
this._options[key] = value;
return this;
}
/**
* @public
* Sets the options for making a request
* @param {{ [key: string]: any }} options - The options key value pair
* @returns The same GraphRequest instance that is being called with
*/
options(options) {
for (const key in options) {
if (Object.prototype.hasOwnProperty.call(options, key)) {
this._options[key] = options[key];
}
}
return this;
}
/**
* @public
* Sets the middleware options for a request
* @param {MiddlewareOptions[]} options - The array of middleware options
* @returns The same GraphRequest instance that is being called with
*/
middlewareOptions(options) {
this._middlewareOptions = options;
return this;
}
/**
* @public
* Sets the api endpoint version for a request
* @param {string} version - The version value
* @returns The same GraphRequest instance that is being called with
*/
version(version) {
this.urlComponents.version = version;
return this;
}
/**
* @public
* Sets the api endpoint version for a request
* @param {ResponseType} responseType - The response type value
* @returns The same GraphRequest instance that is being called with
*/
responseType(responseType) {
this._responseType = responseType;
return this;
}
/**
* @public
* To add properties for select OData Query param
* @param {string|string[]} properties - The Properties value
* @returns The same GraphRequest instance that is being called with, after adding the properties for $select query
*/
/*
* Accepts .select("displayName,birthday")
* and .select(["displayName", "birthday"])
* and .select("displayName", "birthday")
*
*/
select(properties) {
this.addCsvQueryParameter("$select", properties, arguments);
return this;
}
/**
* @public
* To add properties for expand OData Query param
* @param {string|string[]} properties - The Properties value
* @returns The same GraphRequest instance that is being called with, after adding the properties for $expand query
*/
expand(properties) {
this.addCsvQueryParameter("$expand", properties, arguments);
return this;
}
/**
* @public
* To add properties for orderby OData Query param
* @param {string|string[]} properties - The Properties value
* @returns The same GraphRequest instance that is being called with, after adding the properties for $orderby query
*/
orderby(properties) {
this.addCsvQueryParameter("$orderby", properties, arguments);
return this;
}
/**
* @public
* To add query string for filter OData Query param. The request URL accepts only one $filter Odata Query option and its value is set to the most recently passed filter query string.
* @param {string} filterStr - The filter query string
* @returns The same GraphRequest instance that is being called with, after adding the $filter query
*/
filter(filterStr) {
this.urlComponents.oDataQueryParams.$filter = filterStr;
return this;
}
/**
* @public
* To add criterion for search OData Query param. The request URL accepts only one $search Odata Query option and its value is set to the most recently passed search criterion string.
* @param {string} searchStr - The search criterion string
* @returns The same GraphRequest instance that is being called with, after adding the $search query criteria
*/
search(searchStr) {
this.urlComponents.oDataQueryParams.$search = searchStr;
return this;
}
/**
* @public
* To add number for top OData Query param. The request URL accepts only one $top Odata Query option and its value is set to the most recently passed number value.
* @param {number} n - The number value
* @returns The same GraphRequest instance that is being called with, after adding the number for $top query
*/
top(n) {
this.urlComponents.oDataQueryParams.$top = n;
return this;
}
/**
* @public
* To add number for skip OData Query param. The request URL accepts only one $skip Odata Query option and its value is set to the most recently passed number value.
* @param {number} n - The number value
* @returns The same GraphRequest instance that is being called with, after adding the number for the $skip query
*/
skip(n) {
this.urlComponents.oDataQueryParams.$skip = n;
return this;
}
/**
* @public
* To add token string for skipToken OData Query param. The request URL accepts only one $skipToken Odata Query option and its value is set to the most recently passed token value.
* @param {string} token - The token value
* @returns The same GraphRequest instance that is being called with, after adding the token string for $skipToken query option
*/
skipToken(token) {
this.urlComponents.oDataQueryParams.$skipToken = token;
return this;
}
/**
* @public
* To add boolean for count OData Query param. The URL accepts only one $count Odata Query option and its value is set to the most recently passed boolean value.
* @param {boolean} isCount - The count boolean
* @returns The same GraphRequest instance that is being called with, after adding the boolean value for the $count query option
*/
count(isCount = true) {
this.urlComponents.oDataQueryParams.$count = isCount.toString();
return this;
}
/**
* @public
* Appends query string to the urlComponent
* @param {string|KeyValuePairObjectStringNumber} queryDictionaryOrString - The query value
* @returns The same GraphRequest instance that is being called with, after appending the query string to the url component
*/
/*
* Accepts .query("displayName=xyz")
* and .select({ name: "value" })
*/
query(queryDictionaryOrString) {
return this.parseQueryParameter(queryDictionaryOrString);
}
/**
* @public
* @async
* Makes a http request with GET method
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the get response
*/
get(callback) {
return __awaiter(this, void 0, void 0, function* () {
const url = this.buildFullUrl();
const options = {
method: RequestMethod.GET,
};
const response = yield this.send(url, options, callback);
return response;
});
}
/**
* @public
* @async
* Makes a http request with POST method
* @param {any} content - The content that needs to be sent with the request
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the post response
*/
post(content, callback) {
return __awaiter(this, void 0, void 0, function* () {
const url = this.buildFullUrl();
const options = {
method: RequestMethod.POST,
body: serializeContent(content),
};
const className = content && content.constructor && content.constructor.name;
if (className === "FormData") {
// Content-Type headers should not be specified in case the of FormData type content
options.headers = {};
}
else {
this.setHeaderContentType();
options.headers = this._headers;
}
return yield this.send(url, options, callback);
});
}
/**
* @public
* @async
* Alias for Post request call
* @param {any} content - The content that needs to be sent with the request
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the post response
*/
create(content, callback) {
return __awaiter(this, void 0, void 0, function* () {
return yield this.post(content, callback);
});
}
/**
* @public
* @async
* Makes http request with PUT method
* @param {any} content - The content that needs to be sent with the request
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the put response
*/
put(content, callback) {
return __awaiter(this, void 0, void 0, function* () {
const url = this.buildFullUrl();
this.setHeaderContentType();
const options = {
method: RequestMethod.PUT,
body: serializeContent(content),
};
return yield this.send(url, options, callback);
});
}
/**
* @public
* @async
* Makes http request with PATCH method
* @param {any} content - The content that needs to be sent with the request
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the patch response
*/
patch(content, callback) {
return __awaiter(this, void 0, void 0, function* () {
const url = this.buildFullUrl();
this.setHeaderContentType();
const options = {
method: RequestMethod.PATCH,
body: serializeContent(content),
};
return yield this.send(url, options, callback);
});
}
/**
* @public
* @async
* Alias for PATCH request
* @param {any} content - The content that needs to be sent with the request
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the patch response
*/
update(content, callback) {
return __awaiter(this, void 0, void 0, function* () {
return yield this.patch(content, callback);
});
}
/**
* @public
* @async
* Makes http request with DELETE method
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the delete response
*/
delete(callback) {
return __awaiter(this, void 0, void 0, function* () {
const url = this.buildFullUrl();
const options = {
method: RequestMethod.DELETE,
};
return yield this.send(url, options, callback);
});
}
/**
* @public
* @async
* Alias for delete request call
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the delete response
*/
del(callback) {
return __awaiter(this, void 0, void 0, function* () {
return yield this.delete(callback);
});
}
/**
* @public
* @async
* Makes a http request with GET method to read response as a stream.
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the getStream response
*/
getStream(callback) {
return __awaiter(this, void 0, void 0, function* () {
const url = this.buildFullUrl();
const options = {
method: RequestMethod.GET,
};
this.responseType(ResponseType.STREAM);
return yield this.send(url, options, callback);
});
}
/**
* @public
* @async
* Makes a http request with GET method to read response as a stream.
* @param {any} stream - The stream instance
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the putStream response
*/
putStream(stream, callback) {
return __awaiter(this, void 0, void 0, function* () {
const url = this.buildFullUrl();
const options = {
method: RequestMethod.PUT,
headers: {
"Content-Type": "application/octet-stream",
},
body: stream,
};
return yield this.send(url, options, callback);
});
}
}
//# sourceMappingURL=GraphRequest.js.map
File diff suppressed because one or more lines are too long
@@ -0,0 +1,42 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* To hold list of OData query params
*/
export declare const oDataQueryNames: string[];
/**
* To construct the URL by appending the segments with "/"
* @param {string[]} urlSegments - The array of strings
* @returns The constructed URL string
*/
export declare const urlJoin: (urlSegments: string[]) => string;
/**
* Serializes the content
* @param {any} content - The content value that needs to be serialized
* @returns The serialized content
*
* Note:
* This conversion is required due to the following reasons:
* Body parameter of Request method of isomorphic-fetch only accepts Blob, ArrayBuffer, FormData, TypedArrays string.
* Node.js platform does not support Blob, FormData. Javascript File object inherits from Blob so it is also not supported in node. Therefore content of type Blob, File, FormData will only come from browsers.
* Parallel to ArrayBuffer in javascript, node provides Buffer interface. Node's Buffer is able to send the arbitrary binary data to the server successfully for both Browser and Node platform. Whereas sending binary data via ArrayBuffer or TypedArrays was only possible using Browser. To support both Node and Browser, `serializeContent` converts TypedArrays or ArrayBuffer to `Node Buffer`.
* If the data received is in JSON format, `serializeContent` converts the JSON to string.
*/
export declare const serializeContent: (content: any) => any;
/**
* Checks if the url is one of the service root endpoints for Microsoft Graph and Graph Explorer.
* @param {string} url - The url to be verified
* @returns {boolean} - Returns true if the url is a Graph URL
*/
export declare const isGraphURL: (url: string) => boolean;
/**
* Checks if the url is for one of the custom hosts provided during client initialization
* @param {string} url - The url to be verified
* @param {Set} customHosts - The url to be verified
* @returns {boolean} - Returns true if the url is a for a custom host
*/
export declare const isCustomHost: (url: string, customHosts: Set<string>) => boolean;
@@ -0,0 +1,116 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @module GraphRequestUtil
*/
import { GRAPH_URLS } from "./Constants";
import { GraphClientError } from "./GraphClientError";
/**
* To hold list of OData query params
*/
export const oDataQueryNames = ["$select", "$expand", "$orderby", "$filter", "$top", "$skip", "$skipToken", "$count"];
/**
* To construct the URL by appending the segments with "/"
* @param {string[]} urlSegments - The array of strings
* @returns The constructed URL string
*/
export const urlJoin = (urlSegments) => {
const removePostSlash = (s) => s.replace(/\/+$/, "");
const removePreSlash = (s) => s.replace(/^\/+/, "");
const joiner = (pre, cur) => [removePostSlash(pre), removePreSlash(cur)].join("/");
const parts = Array.prototype.slice.call(urlSegments);
return parts.reduce(joiner);
};
/**
* Serializes the content
* @param {any} content - The content value that needs to be serialized
* @returns The serialized content
*
* Note:
* This conversion is required due to the following reasons:
* Body parameter of Request method of isomorphic-fetch only accepts Blob, ArrayBuffer, FormData, TypedArrays string.
* Node.js platform does not support Blob, FormData. Javascript File object inherits from Blob so it is also not supported in node. Therefore content of type Blob, File, FormData will only come from browsers.
* Parallel to ArrayBuffer in javascript, node provides Buffer interface. Node's Buffer is able to send the arbitrary binary data to the server successfully for both Browser and Node platform. Whereas sending binary data via ArrayBuffer or TypedArrays was only possible using Browser. To support both Node and Browser, `serializeContent` converts TypedArrays or ArrayBuffer to `Node Buffer`.
* If the data received is in JSON format, `serializeContent` converts the JSON to string.
*/
export const serializeContent = (content) => {
const className = content && content.constructor && content.constructor.name;
if (className === "Buffer" || className === "Blob" || className === "File" || className === "FormData" || typeof content === "string") {
return content;
}
if (className === "ArrayBuffer") {
content = Buffer.from(content);
}
else if (className === "Int8Array" || className === "Int16Array" || className === "Int32Array" || className === "Uint8Array" || className === "Uint16Array" || className === "Uint32Array" || className === "Uint8ClampedArray" || className === "Float32Array" || className === "Float64Array" || className === "DataView") {
content = Buffer.from(content.buffer);
}
else {
try {
content = JSON.stringify(content);
}
catch (error) {
throw new Error("Unable to stringify the content");
}
}
return content;
};
/**
* Checks if the url is one of the service root endpoints for Microsoft Graph and Graph Explorer.
* @param {string} url - The url to be verified
* @returns {boolean} - Returns true if the url is a Graph URL
*/
export const isGraphURL = (url) => {
return isValidEndpoint(url);
};
/**
* Checks if the url is for one of the custom hosts provided during client initialization
* @param {string} url - The url to be verified
* @param {Set} customHosts - The url to be verified
* @returns {boolean} - Returns true if the url is a for a custom host
*/
export const isCustomHost = (url, customHosts) => {
customHosts.forEach((host) => isCustomHostValid(host));
return isValidEndpoint(url, customHosts);
};
/**
* Checks if the url is for one of the provided hosts.
* @param {string} url - The url to be verified
* @param {Set<string>} allowedHosts - A set of hosts.
* @returns {boolean} - Returns true is for one of the provided endpoints.
*/
const isValidEndpoint = (url, allowedHosts = GRAPH_URLS) => {
// Valid Graph URL pattern - https://graph.microsoft.com/{version}/{resource}?{query-parameters}
// Valid Graph URL example - https://graph.microsoft.com/v1.0/
url = url.toLowerCase();
if (url.indexOf("https://") !== -1) {
url = url.replace("https://", "");
// Find where the host ends
const startofPortNoPos = url.indexOf(":");
const endOfHostStrPos = url.indexOf("/");
let hostName = "";
if (endOfHostStrPos !== -1) {
if (startofPortNoPos !== -1 && startofPortNoPos < endOfHostStrPos) {
hostName = url.substring(0, startofPortNoPos);
return allowedHosts.has(hostName);
}
// Parse out the host
hostName = url.substring(0, endOfHostStrPos);
return allowedHosts.has(hostName);
}
}
return false;
};
/**
* Throws error if the string is not a valid host/hostname and contains other url parts.
* @param {string} host - The host to be verified
*/
const isCustomHostValid = (host) => {
if (host.indexOf("/") !== -1) {
throw new GraphClientError("Please add only hosts or hostnames to the CustomHosts config. If the url is `http://example.com:3000/`, host is `example:3000`");
}
};
//# sourceMappingURL=GraphRequestUtil.js.map
@@ -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AAU,EAAW,EAAE;IACxF,gGAAgG;IAChG,8DAA8D;IAC9D,GAAG,GAAG,GAAG,CAAC,WAAW,EAAE,CAAC;IAExB,IAAI,GAAG,CAAC,OAAO,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,EAAE;QACnC,GAAG,GAAG,GAAG,CAAC,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC;QAElC,2BAA2B;QAC3B,MAAM,gBAAgB,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;QAC1C,MAAM,eAAe,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;QACzC,IAAI,QAAQ,GAAG,EAAE,CAAC;QAClB,IAAI,eAAe,KAAK,CAAC,CAAC,EAAE;YAC3B,IAAI,gBAAgB,KAAK,CAAC,CAAC,IAAI,gBAAgB,GAAG,eAAe,EAAE;gBAClE,QAAQ,GAAG,GAAG,CAAC,SAAS,CAAC,CAAC,EAAE,gBAAgB,CAAC,CAAC;gBAC9C,OAAO,YAAY,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;aAClC;YACD,qBAAqB;YACrB,QAAQ,GAAG,GAAG,CAAC,SAAS,CAAC,CAAC,EAAE,eAAe,CAAC,CAAC;YAC7C,OAAO,YAAY,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;SAClC;KACD;IAED,OAAO,KAAK,CAAC;AACd,CAAC,CAAC;AAEF;;;GAGG;AACH,MAAM,iBAAiB,GAAG,CAAC,IAAY,EAAE,EAAE;IAC1C,IAAI,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE;QAC7B,MAAM,IAAI,gBAAgB,CAAC,gIAAgI,CAAC,CAAC;KAC7J;AACF,CAAC,CAAC"}
@@ -0,0 +1,62 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @module GraphResponseHandler
* References - https://fetch.spec.whatwg.org/#responses
*/
import { GraphRequestCallback } from "./IGraphRequestCallback";
import { ResponseType } from "./ResponseType";
/**
* @enum
* Enum for document types
* @property {string} TEXT_HTML - The text/html content type
* @property {string} TEXT_XML - The text/xml content type
* @property {string} APPLICATION_XML - The application/xml content type
* @property {string} APPLICATION_XHTML - The application/xhml+xml content type
*/
export declare enum DocumentType {
TEXT_HTML = "text/html",
TEXT_XML = "text/xml",
APPLICATION_XML = "application/xml",
APPLICATION_XHTML = "application/xhtml+xml"
}
/**
* @class
* Class for GraphResponseHandler
*/
export declare class GraphResponseHandler {
/**
* @private
* @static
* To parse Document response
* @param {Response} rawResponse - The response object
* @param {DocumentType} type - The type to which the document needs to be parsed
* @returns A promise that resolves to a document content
*/
private static parseDocumentResponse;
/**
* @private
* @static
* @async
* To convert the native Response to response content
* @param {Response} rawResponse - The response object
* @param {ResponseType} [responseType] - The response type value
* @returns A promise that resolves to the converted response content
*/
private static convertResponse;
/**
* @public
* @static
* @async
* To get the parsed response
* @param {Response} rawResponse - The response object
* @param {ResponseType} [responseType] - The response type value
* @param {GraphRequestCallback} [callback] - The graph request callback function
* @returns The parsed response
*/
static getResponse(rawResponse: Response, responseType?: ResponseType, callback?: GraphRequestCallback): Promise<any>;
}
@@ -0,0 +1,186 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
import { __awaiter } from "tslib";
import { ResponseType } from "./ResponseType";
/**
* @enum
* Enum for document types
* @property {string} TEXT_HTML - The text/html content type
* @property {string} TEXT_XML - The text/xml content type
* @property {string} APPLICATION_XML - The application/xml content type
* @property {string} APPLICATION_XHTML - The application/xhml+xml content type
*/
export var DocumentType;
(function (DocumentType) {
DocumentType["TEXT_HTML"] = "text/html";
DocumentType["TEXT_XML"] = "text/xml";
DocumentType["APPLICATION_XML"] = "application/xml";
DocumentType["APPLICATION_XHTML"] = "application/xhtml+xml";
})(DocumentType || (DocumentType = {}));
/**
* @enum
* Enum for Content types
* @property {string} TEXT_PLAIN - The text/plain content type
* @property {string} APPLICATION_JSON - The application/json content type
*/
var ContentType;
(function (ContentType) {
ContentType["TEXT_PLAIN"] = "text/plain";
ContentType["APPLICATION_JSON"] = "application/json";
})(ContentType || (ContentType = {}));
/**
* @enum
* Enum for Content type regex
* @property {string} DOCUMENT - The regex to match document content types
* @property {string} IMAGE - The regex to match image content types
*/
var ContentTypeRegexStr;
(function (ContentTypeRegexStr) {
ContentTypeRegexStr["DOCUMENT"] = "^(text\\/(html|xml))|(application\\/(xml|xhtml\\+xml))$";
ContentTypeRegexStr["IMAGE"] = "^image\\/.+";
})(ContentTypeRegexStr || (ContentTypeRegexStr = {}));
/**
* @class
* Class for GraphResponseHandler
*/
export class GraphResponseHandler {
/**
* @private
* @static
* To parse Document response
* @param {Response} rawResponse - The response object
* @param {DocumentType} type - The type to which the document needs to be parsed
* @returns A promise that resolves to a document content
*/
static parseDocumentResponse(rawResponse, type) {
if (typeof DOMParser !== "undefined") {
return new Promise((resolve, reject) => {
rawResponse.text().then((xmlString) => {
try {
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, type);
resolve(xmlDoc);
}
catch (error) {
reject(error);
}
});
});
}
else {
return Promise.resolve(rawResponse.body);
}
}
/**
* @private
* @static
* @async
* To convert the native Response to response content
* @param {Response} rawResponse - The response object
* @param {ResponseType} [responseType] - The response type value
* @returns A promise that resolves to the converted response content
*/
static convertResponse(rawResponse, responseType) {
return __awaiter(this, void 0, void 0, function* () {
if (rawResponse.status === 204) {
// NO CONTENT
return Promise.resolve();
}
let responseValue;
const contentType = rawResponse.headers.get("Content-type");
switch (responseType) {
case ResponseType.ARRAYBUFFER:
responseValue = yield rawResponse.arrayBuffer();
break;
case ResponseType.BLOB:
responseValue = yield rawResponse.blob();
break;
case ResponseType.DOCUMENT:
responseValue = yield GraphResponseHandler.parseDocumentResponse(rawResponse, DocumentType.TEXT_XML);
break;
case ResponseType.JSON:
responseValue = yield rawResponse.json();
break;
case ResponseType.STREAM:
responseValue = yield Promise.resolve(rawResponse.body);
break;
case ResponseType.TEXT:
responseValue = yield rawResponse.text();
break;
default:
if (contentType !== null) {
const mimeType = contentType.split(";")[0];
if (new RegExp(ContentTypeRegexStr.DOCUMENT).test(mimeType)) {
responseValue = yield GraphResponseHandler.parseDocumentResponse(rawResponse, mimeType);
}
else if (new RegExp(ContentTypeRegexStr.IMAGE).test(mimeType)) {
responseValue = rawResponse.blob();
}
else if (mimeType === ContentType.TEXT_PLAIN) {
responseValue = yield rawResponse.text();
}
else if (mimeType === ContentType.APPLICATION_JSON) {
responseValue = yield rawResponse.json();
}
else {
responseValue = Promise.resolve(rawResponse.body);
}
}
else {
/**
* RFC specification {@link https://tools.ietf.org/html/rfc7231#section-3.1.1.5} says:
* A sender that generates a message containing a payload body SHOULD
* generate a Content-Type header field in that message unless the
* intended media type of the enclosed representation is unknown to the
* sender. If a Content-Type header field is not present, the recipient
* MAY either assume a media type of "application/octet-stream"
* ([RFC2046], Section 4.5.1) or examine the data to determine its type.
*
* So assuming it as a stream type so returning the body.
*/
responseValue = Promise.resolve(rawResponse.body);
}
break;
}
return responseValue;
});
}
/**
* @public
* @static
* @async
* To get the parsed response
* @param {Response} rawResponse - The response object
* @param {ResponseType} [responseType] - The response type value
* @param {GraphRequestCallback} [callback] - The graph request callback function
* @returns The parsed response
*/
static getResponse(rawResponse, responseType, callback) {
return __awaiter(this, void 0, void 0, function* () {
if (responseType === ResponseType.RAW) {
return Promise.resolve(rawResponse);
}
else {
const response = yield GraphResponseHandler.convertResponse(rawResponse, responseType);
if (rawResponse.ok) {
// Status Code 2XX
if (typeof callback === "function") {
callback(null, response);
}
else {
return response;
}
}
else {
// NOT OK Response
throw response;
}
}
});
}
}
//# sourceMappingURL=GraphResponseHandler.js.map
@@ -0,0 +1 @@
{"version":3,"file":"GraphResponseHandler.js","sourceRoot":"","sources":["../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BACN,kBAAkB;oBAClB,MAAM,QAAQ,CAAC;iBACf;aACD;QACF,CAAC;KAAA;CACD"}
@@ -0,0 +1,54 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @module HTTPClient
*/
import { Context } from "./IContext";
import { Middleware } from "./middleware/IMiddleware";
/**
* @class
* Class representing HTTPClient
*/
export declare class HTTPClient {
/**
* @private
* A member holding first middleware of the middleware chain
*/
private middleware;
/**
* @public
* @constructor
* Creates an instance of a HTTPClient
* @param {...Middleware} middleware - The first middleware of the middleware chain or a sequence of all the Middleware handlers
*/
constructor(...middleware: Middleware[]);
/**
* @private
* Processes the middleware parameter passed to set this.middleware property
* The calling function should validate if middleware is not undefined or not empty.
* @param {...Middleware} middleware - The middleware passed
* @returns Nothing
*/
private setMiddleware;
/**
* @private
* Processes the middleware array to construct the chain
* and sets this.middleware property to the first middleware handler of the array
* The calling function should validate if middleware is not undefined or not empty
* @param {Middleware[]} middlewareArray - The array of middleware handlers
* @returns Nothing
*/
private parseMiddleWareArray;
/**
* @public
* @async
* To send the request through the middleware chain
* @param {Context} context - The context of a request
* @returns A promise that resolves to the Context
*/
sendRequest(context: Context): Promise<Context>;
}
@@ -0,0 +1,79 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
import { __awaiter } from "tslib";
/**
* @class
* Class representing HTTPClient
*/
export class HTTPClient {
/**
* @public
* @constructor
* Creates an instance of a HTTPClient
* @param {...Middleware} middleware - The first middleware of the middleware chain or a sequence of all the Middleware handlers
*/
constructor(...middleware) {
if (!middleware || !middleware.length) {
const error = new Error();
error.name = "InvalidMiddlewareChain";
error.message = "Please provide a default middleware chain or custom middleware chain";
throw error;
}
this.setMiddleware(...middleware);
}
/**
* @private
* Processes the middleware parameter passed to set this.middleware property
* The calling function should validate if middleware is not undefined or not empty.
* @param {...Middleware} middleware - The middleware passed
* @returns Nothing
*/
setMiddleware(...middleware) {
if (middleware.length > 1) {
this.parseMiddleWareArray(middleware);
}
else {
this.middleware = middleware[0];
}
}
/**
* @private
* Processes the middleware array to construct the chain
* and sets this.middleware property to the first middleware handler of the array
* The calling function should validate if middleware is not undefined or not empty
* @param {Middleware[]} middlewareArray - The array of middleware handlers
* @returns Nothing
*/
parseMiddleWareArray(middlewareArray) {
middlewareArray.forEach((element, index) => {
if (index < middlewareArray.length - 1) {
element.setNext(middlewareArray[index + 1]);
}
});
this.middleware = middlewareArray[0];
}
/**
* @public
* @async
* To send the request through the middleware chain
* @param {Context} context - The context of a request
* @returns A promise that resolves to the Context
*/
sendRequest(context) {
return __awaiter(this, void 0, void 0, function* () {
if (typeof context.request === "string" && context.options === undefined) {
const error = new Error();
error.name = "InvalidRequestOptions";
error.message = "Unable to execute the middleware, Please provide valid options for a request";
throw error;
}
yield this.middleware.execute(context);
return context;
});
}
}
//# sourceMappingURL=HTTPClient.js.map
@@ -0,0 +1 @@
{"version":3,"file":"HTTPClient.js","sourceRoot":"","sources":["../../../src/HTTPClient.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;;AASH;;;GAGG;AACH,MAAM,OAAO,UAAU;IAOtB;;;;;OAKG;IACH,YAAmB,GAAG,UAAwB;QAC7C,IAAI,CAAC,UAAU,IAAI,CAAC,UAAU,CAAC,MAAM,EAAE;YACtC,MAAM,KAAK,GAAG,IAAI,KAAK,EAAE,CAAC;YAC1B,KAAK,CAAC,IAAI,GAAG,wBAAwB,CAAC;YACtC,KAAK,CAAC,OAAO,GAAG,sEAAsE,CAAC;YACvF,MAAM,KAAK,CAAC;SACZ;QACD,IAAI,CAAC,aAAa,CAAC,GAAG,UAAU,CAAC,CAAC;IACnC,CAAC;IAED;;;;;;OAMG;IACK,aAAa,CAAC,GAAG,UAAwB;QAChD,IAAI,UAAU,CAAC,MAAM,GAAG,CAAC,EAAE;YAC1B,IAAI,CAAC,oBAAoB,CAAC,UAAU,CAAC,CAAC;SACtC;aAAM;YACN,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC,CAAC,CAAC,CAAC;SAChC;IACF,CAAC;IAED;;;;;;;OAOG;IACK,oBAAoB,CAAC,eAA6B;QACzD,eAAe,CAAC,OAAO,CAAC,CAAC,OAAO,EAAE,KAAK,EAAE,EAAE;YAC1C,IAAI,KAAK,GAAG,eAAe,CAAC,MAAM,GAAG,CAAC,EAAE;gBACvC,OAAO,CAAC,OAAO,CAAC,eAAe,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC;aAC5C;QACF,CAAC,CAAC,CAAC;QACH,IAAI,CAAC,UAAU,GAAG,eAAe,CAAC,CAAC,CAAC,CAAC;IACtC,CAAC;IAED;;;;;;OAMG;IACU,WAAW,CAAC,OAAgB;;YACxC,IAAI,OAAO,OAAO,CAAC,OAAO,KAAK,QAAQ,IAAI,OAAO,CAAC,OAAO,KAAK,SAAS,EAAE;gBACzE,MAAM,KAAK,GAAG,IAAI,KAAK,EAAE,CAAC;gBAC1B,KAAK,CAAC,IAAI,GAAG,uBAAuB,CAAC;gBACrC,KAAK,CAAC,OAAO,GAAG,8EAA8E,CAAC;gBAC/F,MAAM,KAAK,CAAC;aACZ;YACD,MAAM,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;YACvC,OAAO,OAAO,CAAC;QAChB,CAAC;KAAA;CACD"}
@@ -0,0 +1,40 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @module HTTPClientFactory
*/
import { HTTPClient } from "./HTTPClient";
import { AuthenticationProvider } from "./IAuthenticationProvider";
import { Middleware } from "./middleware/IMiddleware";
/**
* @class
* Class representing HTTPClientFactory
*/
export declare class HTTPClientFactory {
/**
* @public
* @static
* Creates HTTPClient with default middleware chain
* @param {AuthenticationProvider} authProvider - The authentication provider instance
* @returns A HTTPClient instance
*
* NOTE: These are the things that we need to remember while doing modifications in the below default pipeline.
* * HTTPMessageHandler should be the last one in the middleware pipeline, because this makes the actual network call of the request
* * TelemetryHandler should be the one prior to the last middleware in the chain, because this is the one which actually collects and appends the usage flag and placing this handler * before making the actual network call ensures that the usage of all features are recorded in the flag.
* * The best place for AuthenticationHandler is in the starting of the pipeline, because every other handler might have to work for multiple times for a request but the auth token for
* them will remain same. For example, Retry and Redirect handlers might be working multiple times for a request based on the response but their auth token would remain same.
*/
static createWithAuthenticationProvider(authProvider: AuthenticationProvider): HTTPClient;
/**
* @public
* @static
* Creates a middleware chain with the given one
* @property {...Middleware} middleware - The first middleware of the middleware chain or a sequence of all the Middleware handlers
* @returns A HTTPClient instance
*/
static createWithMiddleware(...middleware: Middleware[]): HTTPClient;
}
@@ -0,0 +1,73 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @module HTTPClientFactory
*/
import { HTTPClient } from "./HTTPClient";
import { AuthenticationHandler } from "./middleware/AuthenticationHandler";
import { HTTPMessageHandler } from "./middleware/HTTPMessageHandler";
import { RedirectHandlerOptions } from "./middleware/options/RedirectHandlerOptions";
import { RetryHandlerOptions } from "./middleware/options/RetryHandlerOptions";
import { RedirectHandler } from "./middleware/RedirectHandler";
import { RetryHandler } from "./middleware/RetryHandler";
import { TelemetryHandler } from "./middleware/TelemetryHandler";
/**
* @private
* To check whether the environment is node or not
* @returns A boolean representing the environment is node or not
*/
const isNodeEnvironment = () => {
return typeof process === "object" && typeof require === "function";
};
/**
* @class
* Class representing HTTPClientFactory
*/
export class HTTPClientFactory {
/**
* @public
* @static
* Creates HTTPClient with default middleware chain
* @param {AuthenticationProvider} authProvider - The authentication provider instance
* @returns A HTTPClient instance
*
* NOTE: These are the things that we need to remember while doing modifications in the below default pipeline.
* * HTTPMessageHandler should be the last one in the middleware pipeline, because this makes the actual network call of the request
* * TelemetryHandler should be the one prior to the last middleware in the chain, because this is the one which actually collects and appends the usage flag and placing this handler * before making the actual network call ensures that the usage of all features are recorded in the flag.
* * The best place for AuthenticationHandler is in the starting of the pipeline, because every other handler might have to work for multiple times for a request but the auth token for
* them will remain same. For example, Retry and Redirect handlers might be working multiple times for a request based on the response but their auth token would remain same.
*/
static createWithAuthenticationProvider(authProvider) {
const authenticationHandler = new AuthenticationHandler(authProvider);
const retryHandler = new RetryHandler(new RetryHandlerOptions());
const telemetryHandler = new TelemetryHandler();
const httpMessageHandler = new HTTPMessageHandler();
authenticationHandler.setNext(retryHandler);
if (isNodeEnvironment()) {
const redirectHandler = new RedirectHandler(new RedirectHandlerOptions());
retryHandler.setNext(redirectHandler);
redirectHandler.setNext(telemetryHandler);
}
else {
retryHandler.setNext(telemetryHandler);
}
telemetryHandler.setNext(httpMessageHandler);
return HTTPClientFactory.createWithMiddleware(authenticationHandler);
}
/**
* @public
* @static
* Creates a middleware chain with the given one
* @property {...Middleware} middleware - The first middleware of the middleware chain or a sequence of all the Middleware handlers
* @returns A HTTPClient instance
*/
static createWithMiddleware(...middleware) {
// Middleware should not empty or undefined. This is check is present in the HTTPClient constructor.
return new HTTPClient(...middleware);
}
}
//# sourceMappingURL=HTTPClientFactory.js.map
@@ -0,0 +1 @@
{"version":3,"file":"HTTPClientFactory.js","sourceRoot":"","sources":["../../../src/HTTPClientFactory.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH;;GAEG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAE1C,OAAO,EAAE,qBAAqB,EAAE,MAAM,oCAAoC,CAAC;AAC3E,OAAO,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAC;AAErE,OAAO,EAAE,sBAAsB,EAAE,MAAM,6CAA6C,CAAC;AACrF,OAAO,EAAE,mBAAmB,EAAE,MAA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AAG,UAAU,CAAC,CAAC;IACtC,CAAC;CACD"}
@@ -0,0 +1,13 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
import { AuthProviderCallback } from "./IAuthProviderCallback";
/**
* @interface
* Signature that holds authProvider
* @callback - The anonymous callback function which takes a single param
*/
export type AuthProvider = (done: AuthProviderCallback) => void;
@@ -0,0 +1,8 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
export {};
//# sourceMappingURL=IAuthProvider.js.map
@@ -0,0 +1 @@
{"version":3,"file":"IAuthProvider.js","sourceRoot":"","sources":["../../../src/IAuthProvider.ts"],"names":[],"mappings":"AAAA;;;;;GAKG"}
@@ -0,0 +1,12 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @interface
* Signature that defines callback for an authentication provider
* @callback - The anonymous callback function which takes two params
*/
export type AuthProviderCallback = (error: any, accessToken: string | null) => void;
@@ -0,0 +1,8 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
export {};
//# sourceMappingURL=IAuthProviderCallback.js.map
@@ -0,0 +1 @@
{"version":3,"file":"IAuthProviderCallback.js","sourceRoot":"","sources":["../../../src/IAuthProviderCallback.ts"],"names":[],"mappings":"AAAA;;;;;GAKG"}
@@ -0,0 +1,20 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
import { AuthenticationProviderOptions } from "./IAuthenticationProviderOptions";
/**
* @interface
* A signature representing Authentication provider
* @property {Function} getAccessToken - The function to get the access token from the authentication provider
*/
export interface AuthenticationProvider {
/**
* To get access token from the authentication provider
* @param {AuthenticationProviderOptions} [authenticationProviderOptions] - The authentication provider options instance
* @returns A promise that resolves to an access token
*/
getAccessToken: (authenticationProviderOptions?: AuthenticationProviderOptions) => Promise<string>;
}
@@ -0,0 +1,8 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
export {};
//# sourceMappingURL=IAuthenticationProvider.js.map
@@ -0,0 +1 @@
{"version":3,"file":"IAuthenticationProvider.js","sourceRoot":"","sources":["../../../src/IAuthenticationProvider.ts"],"names":[],"mappings":"AAAA;;;;;GAKG"}
@@ -0,0 +1,14 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @interface
* A signature represents the Authentication provider options
* @property {string[]} [scopes] - The array of scopes
*/
export interface AuthenticationProviderOptions {
scopes?: string[];
}
@@ -0,0 +1,8 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
export {};
//# sourceMappingURL=IAuthenticationProviderOptions.js.map
@@ -0,0 +1 @@
{"version":3,"file":"IAuthenticationProviderOptions.js","sourceRoot":"","sources":["../../../src/IAuthenticationProviderOptions.ts"],"names":[],"mappings":"AAAA;;;;;GAKG"}
@@ -0,0 +1,32 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
import { AuthenticationProvider } from "./IAuthenticationProvider";
import { FetchOptions } from "./IFetchOptions";
import { Middleware } from "./middleware/IMiddleware";
/**
* @interface
* Options for initializing the Graph Client
* @property {Function} [authProvider] - The authentication provider instance
* @property {string} [baseUrl] - Base url that needs to be appended to every request
* @property {boolean} [debugLogging] - The boolean to enable/disable debug logging
* @property {string} [defaultVersion] - The default version that needs to be used while making graph api request
* @property {FetchOptions} [fetchOptions] - The options for fetch request
* @property {Middleware| Middleware[]} [middleware] - The first middleware of the middleware chain or an array of the Middleware handlers
* @property {Set<string>}[customHosts] - A set of custom host names. Should contain hostnames only.
*/
export interface ClientOptions {
authProvider?: AuthenticationProvider;
baseUrl?: string;
debugLogging?: boolean;
defaultVersion?: string;
fetchOptions?: FetchOptions;
middleware?: Middleware | Middleware[];
/**
* Example - If URL is "https://test_host/v1.0", then set property "customHosts" as "customHosts: Set<string>(["test_host"])"
*/
customHosts?: Set<string>;
}
@@ -0,0 +1,8 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
export {};
//# sourceMappingURL=IClientOptions.js.map
@@ -0,0 +1 @@
{"version":3,"file":"IClientOptions.js","sourceRoot":"","sources":["../../../src/IClientOptions.ts"],"names":[],"mappings":"AAAA;;;;;GAKG"}
@@ -0,0 +1,27 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
import { FetchOptions } from "./IFetchOptions";
import { MiddlewareControl } from "./middleware/MiddlewareControl";
/**
* @interface
* @property {RequestInfo} request - The request url string or the Request instance
* @property {FetchOptions} [options] - The options for the request
* @property {Response} [response] - The response content
* @property {MiddlewareControl} [middlewareControl] - The options for the middleware chain
* @property {Set<string>}[customHosts] - A set of custom host names. Should contain hostnames only.
*
*/
export interface Context {
request: RequestInfo;
options?: FetchOptions;
response?: Response;
middlewareControl?: MiddlewareControl;
/**
* Example - If URL is "https://test_host", then set property "customHosts" as "customHosts: Set<string>(["test_host"])"
*/
customHosts?: Set<string>;
}
@@ -0,0 +1,8 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
export {};
//# sourceMappingURL=IContext.js.map
@@ -0,0 +1 @@
{"version":3,"file":"IContext.js","sourceRoot":"","sources":["../../../src/IContext.ts"],"names":[],"mappings":"AAAA;;;;;GAKG"}
@@ -0,0 +1,32 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @interface {@link https://github.com/bitinn/node-fetch/#options}
* Signature to define the fetch request options for node environment
* @property {number} [follow] - node-fetch option: maximum redirect count. 0 to not follow redirect
* @property {number} [compress] - node-fetch option: support gzip/deflate content encoding. false to disable
* @property {number} [size] - node-fetch option: maximum response body size in bytes. 0 to disable
* @property {any} [agent] - node-fetch option: HTTP(S).Agent instance, allows custom proxy, certificate, lookup, family etc.
* @property {number} [highWaterMark] - node-fetch option: maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource.
* @property {boolean} [insecureHTTPParser] - node-fetch option: use an insecure HTTP parser that accepts invalid HTTP headers when `true`.
*/
export interface NodeFetchInit {
follow?: number;
compress?: boolean;
size?: number;
agent?: any;
highWaterMark?: number;
insecureHTTPParser?: boolean;
}
/**
* @interface
* Signature to define the fetch api options which includes both fetch standard options and also the extended node fetch options
* @extends RequestInit @see {@link https://fetch.spec.whatwg.org/#requestinit}
* @extends NodeFetchInit
*/
export interface FetchOptions extends RequestInit, NodeFetchInit {
}
@@ -0,0 +1,8 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
export {};
//# sourceMappingURL=IFetchOptions.js.map
@@ -0,0 +1 @@
{"version":3,"file":"IFetchOptions.js","sourceRoot":"","sources":["../../../src/IFetchOptions.ts"],"names":[],"mappings":"AAAA;;;;;GAKG"}
@@ -0,0 +1,13 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
import { GraphError } from "./GraphError";
/**
* @interface
* Signature to define the GraphRequest callback
* @callback - The anonymous callback function
*/
export type GraphRequestCallback = (error: GraphError, response: any, rawResponse?: any) => void;
@@ -0,0 +1,8 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
export {};
//# sourceMappingURL=IGraphRequestCallback.js.map
@@ -0,0 +1 @@
{"version":3,"file":"IGraphRequestCallback.js","sourceRoot":"","sources":["../../../src/IGraphRequestCallback.ts"],"names":[],"mappings":"AAAA;;;;;GAKG"}
@@ -0,0 +1,29 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
import { AuthProvider } from "./IAuthProvider";
import { FetchOptions } from "./IFetchOptions";
/**
* @interface
* Options for initializing the Graph Client
* @property {AuthProvider} authProvider - The function to get the authentication token
* @property {string} [baseUrl] - Base url that needs to be appended to every request
* @property {boolean} [debugLogging] - The boolean to enable/disable debug logging
* @property {string} [defaultVersion] - The default version that needs to be used while making graph api request
* @property {FetchOptions} [fetchOptions] - The options for fetch request
* @property {Set<string>}[customHosts] - A set of custom host names. Should contain hostnames only.
*/
export interface Options {
authProvider: AuthProvider;
baseUrl?: string;
debugLogging?: boolean;
defaultVersion?: string;
fetchOptions?: FetchOptions;
/**
* Example - If URL is "https://test_host/v1.0", then set property "customHosts" as "customHosts: Set<string>(["test_host"])"
*/
customHosts?: Set<string>;
}
@@ -0,0 +1,8 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
export {};
//# sourceMappingURL=IOptions.js.map
@@ -0,0 +1 @@
{"version":3,"file":"IOptions.js","sourceRoot":"","sources":["../../../src/IOptions.ts"],"names":[],"mappings":"AAAA;;;;;GAKG"}
@@ -0,0 +1,22 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @enum
* Enum for RequestMethods
* @property {string} GET - The get request type
* @property {string} PATCH - The patch request type
* @property {string} POST - The post request type
* @property {string} PUT - The put request type
* @property {string} DELETE - The delete request type
*/
export declare enum RequestMethod {
GET = "GET",
PATCH = "PATCH",
POST = "POST",
PUT = "PUT",
DELETE = "DELETE"
}
@@ -0,0 +1,24 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @enum
* Enum for RequestMethods
* @property {string} GET - The get request type
* @property {string} PATCH - The patch request type
* @property {string} POST - The post request type
* @property {string} PUT - The put request type
* @property {string} DELETE - The delete request type
*/
export var RequestMethod;
(function (RequestMethod) {
RequestMethod["GET"] = "GET";
RequestMethod["PATCH"] = "PATCH";
RequestMethod["POST"] = "POST";
RequestMethod["PUT"] = "PUT";
RequestMethod["DELETE"] = "DELETE";
})(RequestMethod || (RequestMethod = {}));
//# sourceMappingURL=RequestMethod.js.map
@@ -0,0 +1 @@
{"version":3,"file":"RequestMethod.js","sourceRoot":"","sources":["../../../src/RequestMethod.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH;;;;;;;;GAQG;AACH,MAAM,CAAN,IAAY,aAMX;AAND,WAAY,aAAa;IACxB,4BAAW,CAAA;IACX,gCAAe,CAAA;IACf,8BAAa,CAAA;IACb,4BAAW,CAAA;IACX,kCAAiB,CAAA;AAClB,CAAC,EANW,aAAa,KAAb,aAAa,QAMxB"}
@@ -0,0 +1,25 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @enum
* Enum for ResponseType values
* @property {string} ARRAYBUFFER - To download response content as an [ArrayBuffer]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer}
* @property {string} BLOB - To download content as a [binary/blob] {@link https://developer.mozilla.org/en-US/docs/Web/API/Blob}
* @property {string} DOCUMENT - This downloads content as a document or stream
* @property {string} JSON - To download response content as a json
* @property {string} STREAM - To download response as a [stream]{@link https://nodejs.org/api/stream.html}
* @property {string} TEXT - For downloading response as a text
*/
export declare enum ResponseType {
ARRAYBUFFER = "arraybuffer",
BLOB = "blob",
DOCUMENT = "document",
JSON = "json",
RAW = "raw",
STREAM = "stream",
TEXT = "text"
}
@@ -0,0 +1,27 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @enum
* Enum for ResponseType values
* @property {string} ARRAYBUFFER - To download response content as an [ArrayBuffer]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer}
* @property {string} BLOB - To download content as a [binary/blob] {@link https://developer.mozilla.org/en-US/docs/Web/API/Blob}
* @property {string} DOCUMENT - This downloads content as a document or stream
* @property {string} JSON - To download response content as a json
* @property {string} STREAM - To download response as a [stream]{@link https://nodejs.org/api/stream.html}
* @property {string} TEXT - For downloading response as a text
*/
export var ResponseType;
(function (ResponseType) {
ResponseType["ARRAYBUFFER"] = "arraybuffer";
ResponseType["BLOB"] = "blob";
ResponseType["DOCUMENT"] = "document";
ResponseType["JSON"] = "json";
ResponseType["RAW"] = "raw";
ResponseType["STREAM"] = "stream";
ResponseType["TEXT"] = "text";
})(ResponseType || (ResponseType = {}));
//# sourceMappingURL=ResponseType.js.map
@@ -0,0 +1 @@
{"version":3,"file":"ResponseType.js","sourceRoot":"","sources":["../../../src/ResponseType.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH;;;;;;;;;GASG;AAEH,MAAM,CAAN,IAAY,YAQX;AARD,WAAY,YAAY;IACvB,2CAA2B,CAAA;IAC3B,6BAAa,CAAA;IACb,qCAAqB,CAAA;IACrB,6BAAa,CAAA;IACb,2BAAW,CAAA;IACX,iCAAiB,CAAA;IACjB,6BAAa,CAAA;AACd,CAAC,EARW,YAAY,KAAZ,YAAY,QAQvB"}
@@ -0,0 +1,13 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @constant
* @function
* Validates availability of Promise and fetch in global context
* @returns The true in case the Promise and fetch available, otherwise throws error
*/
export declare const validatePolyFilling: () => boolean;
@@ -0,0 +1,31 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @constant
* @function
* Validates availability of Promise and fetch in global context
* @returns The true in case the Promise and fetch available, otherwise throws error
*/
export const validatePolyFilling = () => {
if (typeof Promise === "undefined" && typeof fetch === "undefined") {
const error = new Error("Library cannot function without Promise and fetch. So, please provide polyfill for them.");
error.name = "PolyFillNotAvailable";
throw error;
}
else if (typeof Promise === "undefined") {
const error = new Error("Library cannot function without Promise. So, please provide polyfill for it.");
error.name = "PolyFillNotAvailable";
throw error;
}
else if (typeof fetch === "undefined") {
const error = new Error("Library cannot function without fetch. So, please provide polyfill for it.");
error.name = "PolyFillNotAvailable";
throw error;
}
return true;
};
//# sourceMappingURL=ValidatePolyFilling.js.map
@@ -0,0 +1 @@
{"version":3,"file":"ValidatePolyFilling.js","sourceRoot":"","sources":["../../../src/ValidatePolyFilling.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH;;;;;GAKG;AAEH,MAAM,CAAC,MAAM,mBAAmB,GAAG,GAAY,EAAE;IAChD,IAAI,OAAO,OAAO,KAAK,WAAW,IAAI,OAAO,KAAK,KAAK,WAAW,EAAE;QACnE,MAAM,KAAK,GAAG,IAAI,KAAK,CAAC,0FAA0F,CAAC,CAAC;QACpH,KAAK,CAAC,IAAI,GAAG,sBAAsB,CAAC;QACpC,MAAM,KAAK,CAAC;KACZ;SAAM,IAAI,OAAO,OAAO,KAAK,WAAW,EAAE;QAC1C,MAAM,KAAK,GAAG,IAAI,KAAK,CAAC,8EAA8E,CAAC,CAAC;QACxG,KAAK,CAAC,IAAI,GAAG,sBAAsB,CAAC;QACpC,MAAM,KAAK,CAAC;KACZ;SAAM,IAAI,OAAO,KAAK,KAAK,WAAW,EAAE;QACxC,MAAM,KAAK,GAAG,IAAI,KAAK,CAAC,4EAA4E,CAAC,CAAC;QACtG,KAAK,CAAC,IAAI,GAAG,sBAAsB,CAAC;QACpC,MAAM,KAAK,CAAC;KACZ;IACD,OAAO,IAAI,CAAC;AACb,CAAC,CAAC"}
+10
View File
@@ -0,0 +1,10 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @module Version
*/
export declare const PACKAGE_VERSION = "3.0.7";
+13
View File
@@ -0,0 +1,13 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
// THIS FILE IS AUTO GENERATED
// ANY CHANGES WILL BE LOST DURING BUILD
/**
* @module Version
*/
export const PACKAGE_VERSION = "3.0.7";
//# sourceMappingURL=Version.js.map
@@ -0,0 +1 @@
{"version":3,"file":"Version.js","sourceRoot":"","sources":["../../../src/Version.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,8BAA8B;AAC9B,wCAAwC;AAExC;;GAEG;AAEH,MAAM,CAAC,MAAM,eAAe,GAAG,OAAO,CAAC"}
@@ -0,0 +1,16 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
import { GetTokenOptions } from "@azure/identity";
import { AuthenticationProviderOptions } from "../../IAuthenticationProviderOptions";
/**
* @interface
* A signature represents the Authentication provider options for Token Credentials
* @property {getTokenOptions} [GetTokenOptions] - Defines options for TokenCredential.getToken.
*/
export interface TokenCredentialAuthenticationProviderOptions extends AuthenticationProviderOptions {
getTokenOptions?: GetTokenOptions;
}
@@ -0,0 +1,2 @@
export {};
//# sourceMappingURL=ITokenCredentialAuthenticationProviderOptions.js.map
@@ -0,0 +1 @@
{"version":3,"file":"ITokenCredentialAuthenticationProviderOptions.js","sourceRoot":"","sources":["../../../../../src/authentication/azureTokenCredentials/ITokenCredentialAuthenticationProviderOptions.ts"],"names":[],"mappings":""}
@@ -0,0 +1,48 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
import { TokenCredential } from "@azure/identity";
import { AuthenticationProvider } from "../../IAuthenticationProvider";
import { TokenCredentialAuthenticationProviderOptions } from "./ITokenCredentialAuthenticationProviderOptions";
/**
* @module TokenCredentialAuthenticationProvider
*/
/**
* @class
* Class representing TokenCredentialAuthenticationProvider
* This feature is introduced in Version 3.0.0
* @extends AuthenticationProvider
* Reference - https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/identity/identity/README.md
*/
export declare class TokenCredentialAuthenticationProvider implements AuthenticationProvider {
/**
* @private
* A member holding an instance of @azure/identity TokenCredential
*/
private tokenCredential;
/**
* @private
* A member holding an instance of TokenCredentialAuthenticationProviderOptions
*/
private authenticationProviderOptions;
/**
* @public
* @constructor
* Creates an instance of TokenCredentialAuthenticationProvider
* @param {TokenCredential} tokenCredential - An instance of @azure/identity TokenCredential
* @param {TokenCredentialAuthenticationProviderOptions} authenticationProviderOptions - An instance of TokenCredentialAuthenticationProviderOptions
* @returns An instance of TokenCredentialAuthenticationProvider
*/
constructor(tokenCredential: TokenCredential, authenticationProviderOptions: TokenCredentialAuthenticationProviderOptions);
/**
* @public
* @async
* To get the access token
* @param {TokenCredentialAuthenticationProviderOptions} authenticationProviderOptions - The authentication provider options object
* @returns The promise that resolves to an access token
*/
getAccessToken(): Promise<string>;
}
@@ -0,0 +1,64 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
import { __awaiter } from "tslib";
import { GraphClientError } from "../../GraphClientError";
/**
* @module TokenCredentialAuthenticationProvider
*/
/**
* @class
* Class representing TokenCredentialAuthenticationProvider
* This feature is introduced in Version 3.0.0
* @extends AuthenticationProvider
* Reference - https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/identity/identity/README.md
*/
export class TokenCredentialAuthenticationProvider {
/**
* @public
* @constructor
* Creates an instance of TokenCredentialAuthenticationProvider
* @param {TokenCredential} tokenCredential - An instance of @azure/identity TokenCredential
* @param {TokenCredentialAuthenticationProviderOptions} authenticationProviderOptions - An instance of TokenCredentialAuthenticationProviderOptions
* @returns An instance of TokenCredentialAuthenticationProvider
*/
constructor(tokenCredential, authenticationProviderOptions) {
if (!tokenCredential) {
throw new GraphClientError("Please pass a token credential object to the TokenCredentialAuthenticationProvider class constructor");
}
if (!authenticationProviderOptions) {
throw new GraphClientError("Please pass the TokenCredentialAuthenticationProviderOptions with scopes to the TokenCredentialAuthenticationProvider class constructor");
}
this.authenticationProviderOptions = authenticationProviderOptions;
this.tokenCredential = tokenCredential;
}
/**
* @public
* @async
* To get the access token
* @param {TokenCredentialAuthenticationProviderOptions} authenticationProviderOptions - The authentication provider options object
* @returns The promise that resolves to an access token
*/
getAccessToken() {
return __awaiter(this, void 0, void 0, function* () {
const scopes = this.authenticationProviderOptions.scopes;
const error = new GraphClientError();
if (!scopes || scopes.length === 0) {
error.name = "Empty Scopes";
error.message = "Scopes cannot be empty, Please provide scopes";
throw error;
}
const response = yield this.tokenCredential.getToken(scopes, this.authenticationProviderOptions.getTokenOptions);
if (response) {
return response.token;
}
error.message = "Cannot retrieve accessToken from the Token Credential object";
error.name = "Access token is undefined";
throw error;
});
}
}
//# sourceMappingURL=TokenCredentialAuthenticationProvider.js.map
@@ -0,0 +1 @@
{"version":3,"file":"TokenCredentialAuthenticationProvider.js","sourceRoot":"","sources":["../../../../../src/authentication/azureTokenCredentials/TokenCredentialAuthenticationProvider.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;;AAIH,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAI1D;;GAEG;AAEH;;;;;;GAMG;AACH,MAAM,OAAO,qCAAqC;IAajD;;;;;;;OAOG;IACH,YAAmB,eAAgC,EAAE,6BAA2E;QAC/H,IAAI,CAAC,eAAe,EAAE;YACrB,MAAM,IAAI,gBAAgB,CAAC,sGAAsG,CAAC,CAAC;SACnI;QACD,IAAI,CAAC,6BAA6B,EAAE;YACnC,MAAM,IAAI,gBAAgB,CAAC,yIAAyI,CAAC,CAAC;SACtK;QACD,IAAI,CAAC,6BAA6B,GAAG,6BAA6B,CAAC;QACnE,IAAI,CAAC,eAAe,GAAG,eAAe,CAAC;IACxC,CAAC;IAED;;;;;;OAMG;IACU,cAAc;;YAC1B,MAAM,MAAM,GAAG,IAAI,CAAC,6BAA6B,CAAC,MAAM,CAAC;YACzD,MAAM,KAAK,GAAG,IAAI,gBAAgB,EAAE,CAAC;YAErC,IAAI,CAAC,MAAM,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE;gBACnC,KAAK,CAAC,IAAI,GAAG,cAAc,CAAC;gBAC5B,KAAK,CAAC,OAAO,GAAG,+CAA+C,CAAC;gBAChE,MAAM,KAAK,CAAC;aACZ;YACD,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,eAAe,CAAC,QAAQ,CAAC,MAAM,EAAE,IAAI,CAAC,6BAA6B,CAAC,eAAe,CAAC,CAAC;YACjH,IAAI,QAAQ,EAAE;gBACb,OAAO,QAAQ,CAAC,KAAK,CAAC;aACtB;YACD,KAAK,CAAC,OAAO,GAAG,8DAA8D,CAAC;YAC/E,KAAK,CAAC,IAAI,GAAG,2BAA2B,CAAC;YACzC,MAAM,KAAK,CAAC;QACb,CAAC;KAAA;CACD"}
@@ -0,0 +1,8 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
export { TokenCredentialAuthenticationProviderOptions } from "./ITokenCredentialAuthenticationProviderOptions";
export { TokenCredentialAuthenticationProvider } from "./TokenCredentialAuthenticationProvider";
@@ -0,0 +1,2 @@
export { TokenCredentialAuthenticationProvider } from "./TokenCredentialAuthenticationProvider";
//# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/authentication/azureTokenCredentials/index.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,qCAAqC,EAAE,MAAM,yCAAyC,CAAC"}

Some files were not shown because too many files have changed in this diff Show More