@microsoft/teamsfx 0.5.1 → 0.5.2-alpha.0535e2d27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- import jwt_decode from 'jwt-decode';
2
1
  import { __awaiter } from 'tslib';
2
+ import jwt_decode from 'jwt-decode';
3
3
  import * as microsoftTeams from '@microsoft/teams-js';
4
4
  import { PublicClientApplication } from '@azure/msal-browser';
5
5
  import { Client } from '@microsoft/microsoft-graph-client';
@@ -60,6 +60,10 @@ var ErrorCode;
60
60
  * Invalid response error.
61
61
  */
62
62
  ErrorCode["InvalidResponse"] = "InvalidResponse";
63
+ /**
64
+ * Identity type error.
65
+ */
66
+ ErrorCode["IdentityTypeNotSupported"] = "IdentityTypeNotSupported";
63
67
  })(ErrorCode || (ErrorCode = {}));
64
68
  /**
65
69
  * @internal
@@ -79,6 +83,8 @@ ErrorMessage.NodejsRuntimeNotSupported = "{0} is not supported in Node.";
79
83
  ErrorMessage.FailToAcquireTokenOnBehalfOfUser = "Failed to acquire access token on behalf of user: {0}";
80
84
  // ChannelNotSupported Error
81
85
  ErrorMessage.OnlyMSTeamsChannelSupported = "{0} is only supported in MS Teams Channel";
86
+ // IdentityTypeNotSupported Error
87
+ ErrorMessage.IdentityTypeNotSupported = "{0} identity is not supported in {1}";
82
88
  /**
83
89
  * Error class with code and message thrown by the SDK.
84
90
  *
@@ -105,26 +111,6 @@ class ErrorWithCode extends Error {
105
111
  }
106
112
  }
107
113
 
108
- // Copyright (c) Microsoft Corporation.
109
- // Licensed under the MIT license.
110
- /**
111
- * Available resource type.
112
- * @beta
113
- */
114
- var ResourceType;
115
- (function (ResourceType) {
116
- /**
117
- * SQL database.
118
- *
119
- */
120
- ResourceType[ResourceType["SQL"] = 0] = "SQL";
121
- /**
122
- * Rest API.
123
- *
124
- */
125
- ResourceType[ResourceType["API"] = 1] = "API";
126
- })(ResourceType || (ResourceType = {}));
127
-
128
114
  // Copyright (c) Microsoft Corporation.
129
115
  // Licensed under the MIT license.
130
116
  /**
@@ -404,131 +390,6 @@ function validateScopesType(value) {
404
390
  const errorMsg = "The type of scopes is not valid, it must be string or string array";
405
391
  internalLogger.error(errorMsg);
406
392
  throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);
407
- }
408
- /**
409
- * @internal
410
- */
411
- const isNode = typeof process !== "undefined" &&
412
- !!process.version &&
413
- !!process.versions &&
414
- !!process.versions.node;
415
-
416
- // Copyright (c) Microsoft Corporation.
417
- /**
418
- * Global configuration instance
419
- *
420
- */
421
- let config;
422
- /**
423
- * Initialize configuration from environment variables or configuration object and set the global instance
424
- *
425
- * @param {Configuration} configuration - Optional configuration that overrides the default configuration values. The override depth is 1.
426
- *
427
- * @throws {@link ErrorCode|InvalidParameter} when configuration is not passed in browser environment
428
- *
429
- * @beta
430
- */
431
- function loadConfiguration(configuration) {
432
- internalLogger.info("load configuration");
433
- // browser environment
434
- if (!isNode) {
435
- if (!configuration) {
436
- const errorMsg = "You are running the code in browser. Configuration must be passed in.";
437
- internalLogger.error(errorMsg);
438
- throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);
439
- }
440
- config = configuration;
441
- return;
442
- }
443
- // node environment
444
- let newAuthentication;
445
- let newResources = [];
446
- const defaultResourceName = "default";
447
- if (configuration === null || configuration === void 0 ? void 0 : configuration.authentication) {
448
- newAuthentication = configuration.authentication;
449
- }
450
- else {
451
- newAuthentication = {
452
- authorityHost: process.env.M365_AUTHORITY_HOST,
453
- tenantId: process.env.M365_TENANT_ID,
454
- clientId: process.env.M365_CLIENT_ID,
455
- clientSecret: process.env.M365_CLIENT_SECRET,
456
- simpleAuthEndpoint: process.env.SIMPLE_AUTH_ENDPOINT,
457
- initiateLoginEndpoint: process.env.INITIATE_LOGIN_ENDPOINT,
458
- applicationIdUri: process.env.M365_APPLICATION_ID_URI,
459
- };
460
- }
461
- if (configuration === null || configuration === void 0 ? void 0 : configuration.resources) {
462
- newResources = configuration.resources;
463
- }
464
- else {
465
- newResources = [
466
- {
467
- // SQL resource
468
- type: ResourceType.SQL,
469
- name: defaultResourceName,
470
- properties: {
471
- sqlServerEndpoint: process.env.SQL_ENDPOINT,
472
- sqlUsername: process.env.SQL_USER_NAME,
473
- sqlPassword: process.env.SQL_PASSWORD,
474
- sqlDatabaseName: process.env.SQL_DATABASE_NAME,
475
- sqlIdentityId: process.env.IDENTITY_ID,
476
- },
477
- },
478
- {
479
- // API resource
480
- type: ResourceType.API,
481
- name: defaultResourceName,
482
- properties: {
483
- endpoint: process.env.API_ENDPOINT,
484
- },
485
- },
486
- ];
487
- }
488
- config = {
489
- authentication: newAuthentication,
490
- resources: newResources,
491
- };
492
- }
493
- /**
494
- * Get configuration for a specific resource.
495
- * @param {ResourceType} resourceType - The type of resource
496
- * @param {string} resourceName - The name of resource, default value is "default".
497
- *
498
- * @returns Resource configuration for target resource from global configuration instance.
499
- *
500
- * @throws {@link ErrorCode|InvalidConfiguration} when resource configuration with the specific type and name is not found
501
- *
502
- * @beta
503
- */
504
- function getResourceConfiguration(resourceType, resourceName = "default") {
505
- var _a;
506
- internalLogger.info(`Get resource configuration of ${ResourceType[resourceType]} from ${resourceName}`);
507
- const result = (_a = config.resources) === null || _a === void 0 ? void 0 : _a.find((item) => item.type === resourceType && item.name === resourceName);
508
- if (result) {
509
- return result.properties;
510
- }
511
- const errorMsg = formatString(ErrorMessage.MissingResourceConfiguration, ResourceType[resourceType], resourceName);
512
- internalLogger.error(errorMsg);
513
- throw new ErrorWithCode(errorMsg, ErrorCode.InvalidConfiguration);
514
- }
515
- /**
516
- * Get configuration for authentication.
517
- *
518
- * @returns Authentication configuration from global configuration instance, the value may be undefined if no authentication config exists in current environment.
519
- *
520
- * @throws {@link ErrorCode|InvalidConfiguration} when global configuration does not exist
521
- *
522
- * @beta
523
- */
524
- function getAuthenticationConfiguration() {
525
- internalLogger.info("Get authentication configuration");
526
- if (config) {
527
- return config.authentication;
528
- }
529
- const errorMsg = "Please call loadConfiguration() first before calling getAuthenticationConfiguration().";
530
- internalLogger.error(errorMsg);
531
- throw new ErrorWithCode(formatString(ErrorMessage.ConfigurationNotExists, errorMsg), ErrorCode.InvalidConfiguration);
532
393
  }
533
394
 
534
395
  // Copyright (c) Microsoft Corporation.
@@ -540,16 +401,16 @@ function getAuthenticationConfiguration() {
540
401
  *
541
402
  * @beta
542
403
  */
543
- class M365TenantCredential {
404
+ class AppCredential {
544
405
  /**
545
- * Constructor of M365TenantCredential.
406
+ * Constructor of AppCredential.
546
407
  *
547
408
  * @remarks
548
409
  * Only works in in server side.
549
410
  * @beta
550
411
  */
551
- constructor() {
552
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "M365TenantCredential"), ErrorCode.RuntimeNotSupported);
412
+ constructor(authConfig) {
413
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "AppCredential"), ErrorCode.RuntimeNotSupported);
553
414
  }
554
415
  /**
555
416
  * Get access token for credential.
@@ -560,7 +421,7 @@ class M365TenantCredential {
560
421
  */
561
422
  getToken(scopes, options) {
562
423
  return __awaiter(this, void 0, void 0, function* () {
563
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "M365TenantCredential"), ErrorCode.RuntimeNotSupported);
424
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "AppCredential"), ErrorCode.RuntimeNotSupported);
564
425
  });
565
426
  }
566
427
  }
@@ -582,7 +443,7 @@ class OnBehalfOfUserCredential {
582
443
  * Can Only works in in server side.
583
444
  * @beta
584
445
  */
585
- constructor(ssoToken) {
446
+ constructor(ssoToken, config) {
586
447
  throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "OnBehalfOfUserCredential"), ErrorCode.RuntimeNotSupported);
587
448
  }
588
449
  /**
@@ -622,7 +483,6 @@ const loginPageHeight = 535;
622
483
  class TeamsUserCredential {
623
484
  /**
624
485
  * Constructor of TeamsUserCredential.
625
- * Developer need to call loadConfiguration(config) before using this class.
626
486
  *
627
487
  * @example
628
488
  * ```typescript
@@ -632,18 +492,22 @@ class TeamsUserCredential {
632
492
  * clientId: "xxx"
633
493
  * }
634
494
  * }
635
- loadConfiguration(config); // No default config from environment variables, developers must provide the config object.
636
- const credential = new TeamsUserCredential(["https://graph.microsoft.com/User.Read"]);
495
+ * // Use default configuration provided by Teams Toolkit
496
+ * const credential = new TeamsUserCredential();
497
+ * // Use a customized configuration
498
+ * const anotherCredential = new TeamsUserCredential(config);
637
499
  * ```
638
500
  *
501
+ * @param {AuthenticationConfiguration} authConfig - The authentication configuration. Use environment variables if not provided.
502
+ *
639
503
  * @throws {@link ErrorCode|InvalidConfiguration} when client id, initiate login endpoint or simple auth endpoint is not found in config.
640
504
  * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.
641
505
  *
642
506
  * @beta
643
507
  */
644
- constructor() {
508
+ constructor(authConfig) {
645
509
  internalLogger.info("Create teams user credential");
646
- this.config = this.loadAndValidateConfig();
510
+ this.config = this.loadAndValidateConfig(authConfig);
647
511
  this.ssoToken = null;
648
512
  this.initialized = false;
649
513
  }
@@ -912,15 +776,13 @@ class TeamsUserCredential {
912
776
  }
913
777
  /**
914
778
  * Load and validate authentication configuration
779
+ *
780
+ * @param {AuthenticationConfiguration?} config - The authentication configuration. Use environment variables if not provided.
781
+ *
915
782
  * @returns Authentication configuration
916
783
  */
917
- loadAndValidateConfig() {
784
+ loadAndValidateConfig(config) {
918
785
  internalLogger.verbose("Validate authentication configuration");
919
- const config = getAuthenticationConfiguration();
920
- if (!config) {
921
- internalLogger.error(ErrorMessage.AuthenticationConfigurationNotExists);
922
- throw new ErrorWithCode(ErrorMessage.AuthenticationConfigurationNotExists, ErrorCode.InvalidConfiguration);
923
- }
924
786
  if (config.initiateLoginEndpoint && config.clientId) {
925
787
  return config;
926
788
  }
@@ -973,7 +835,7 @@ class MsGraphAuthProvider {
973
835
  /**
974
836
  * Constructor of MsGraphAuthProvider.
975
837
  *
976
- * @param {TokenCredential} credential - Credential used to invoke Microsoft Graph APIs.
838
+ * @param {TeamsFx} teamsfx - Used to provide configuration and auth.
977
839
  * @param {string | string[]} scopes - The list of scopes for which the token will have access.
978
840
  *
979
841
  * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.
@@ -982,8 +844,8 @@ class MsGraphAuthProvider {
982
844
  *
983
845
  * @beta
984
846
  */
985
- constructor(credential, scopes) {
986
- this.credential = credential;
847
+ constructor(teamsfx, scopes) {
848
+ this.teamsfx = teamsfx;
987
849
  let scopesStr = defaultScope;
988
850
  if (scopes) {
989
851
  validateScopesType(scopes);
@@ -1010,7 +872,7 @@ class MsGraphAuthProvider {
1010
872
  getAccessToken() {
1011
873
  return __awaiter(this, void 0, void 0, function* () {
1012
874
  internalLogger.info(`Get Graph Access token with scopes: '${this.scopes}'`);
1013
- const accessToken = yield this.credential.getToken(this.scopes);
875
+ const accessToken = yield this.teamsfx.getCredential().getToken(this.scopes);
1014
876
  return new Promise((resolve, reject) => {
1015
877
  if (accessToken) {
1016
878
  resolve(accessToken.token);
@@ -1068,7 +930,7 @@ class MsGraphAuthProvider {
1068
930
  * }
1069
931
  * ```
1070
932
  *
1071
- * @param {TokenCredential} credential - token credential instance.
933
+ * @param {TeamsFx} teamsfx - Used to provide configuration and auth.
1072
934
  * @param scopes - The array of Microsoft Token scope of access. Default value is `[.default]`.
1073
935
  *
1074
936
  * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.
@@ -1077,36 +939,26 @@ class MsGraphAuthProvider {
1077
939
  *
1078
940
  * @beta
1079
941
  */
1080
- function createMicrosoftGraphClient(credential, scopes) {
942
+ function createMicrosoftGraphClient(teamsfx, scopes) {
1081
943
  internalLogger.info("Create Microsoft Graph Client");
1082
- const authProvider = new MsGraphAuthProvider(credential, scopes);
944
+ const authProvider = new MsGraphAuthProvider(teamsfx, scopes);
1083
945
  const graphClient = Client.initWithMiddleware({
1084
946
  authProvider,
1085
947
  });
1086
948
  return graphClient;
1087
949
  }
1088
950
 
951
+ // Copyright (c) Microsoft Corporation.
1089
952
  /**
1090
953
  * Generate connection configuration consumed by tedious.
1091
954
  * @remarks
1092
955
  * Only works in in server side.
1093
956
  * @beta
1094
957
  */
1095
- class DefaultTediousConnectionConfiguration {
1096
- constructor() {
958
+ function getTediousConnectionConfig(teamsfx, databaseName) {
959
+ return __awaiter(this, void 0, void 0, function* () {
1097
960
  throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "DefaultTediousConnectionConfiguration"), ErrorCode.RuntimeNotSupported);
1098
- }
1099
- /**
1100
- * Generate connection configuration consumed by tedious.
1101
- * @remarks
1102
- * Only works in in server side.
1103
- * @beta
1104
- */
1105
- getConfig(databaseName) {
1106
- return __awaiter(this, void 0, void 0, function* () {
1107
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "DefaultTediousConnectionConfiguration"), ErrorCode.RuntimeNotSupported);
1108
- });
1109
- }
961
+ });
1110
962
  }
1111
963
 
1112
964
  // Copyright (c) Microsoft Corporation.
@@ -1136,7 +988,6 @@ class DefaultTediousConnectionConfiguration {
1136
988
  * const dialogState = convoState.createProperty('dialogState');
1137
989
  * const dialogs = new DialogSet(dialogState);
1138
990
  *
1139
- * loadConfiguration();
1140
991
  * dialogs.add(new TeamsBotSsoPrompt('TeamsBotSsoPrompt', {
1141
992
  * scopes: ["User.Read"],
1142
993
  * }));
@@ -1173,7 +1024,8 @@ class TeamsBotSsoPrompt {
1173
1024
  *
1174
1025
  * @beta
1175
1026
  */
1176
- constructor(dialogId, settings) {
1027
+ constructor(teamsfx, dialogId, settings) {
1028
+ this.teamsfx = teamsfx;
1177
1029
  this.settings = settings;
1178
1030
  throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotSsoPrompt"), ErrorCode.RuntimeNotSupported);
1179
1031
  }
@@ -1223,5 +1075,125 @@ class TeamsBotSsoPrompt {
1223
1075
  }
1224
1076
  }
1225
1077
 
1226
- export { DefaultTediousConnectionConfiguration, ErrorCode, ErrorWithCode, LogLevel, M365TenantCredential, MsGraphAuthProvider, OnBehalfOfUserCredential, ResourceType, TeamsBotSsoPrompt, TeamsUserCredential, createMicrosoftGraphClient, getAuthenticationConfiguration, getLogLevel, getResourceConfiguration, loadConfiguration, setLogFunction, setLogLevel, setLogger };
1078
+ // Copyright (c) Microsoft Corporation.
1079
+ // Licensed under the MIT license.
1080
+ /**
1081
+ * Identity type to use in authentication.
1082
+ *
1083
+ * @beta
1084
+ */
1085
+ var IdentityType;
1086
+ (function (IdentityType) {
1087
+ /**
1088
+ * Represents the current user of Teams.
1089
+ */
1090
+ IdentityType["User"] = "User";
1091
+ /**
1092
+ * Represents the application itself.
1093
+ */
1094
+ IdentityType["App"] = "Application";
1095
+ })(IdentityType || (IdentityType = {}));
1096
+
1097
+ // Copyright (c) Microsoft Corporation.
1098
+ /**
1099
+ * A class providing credential and configuration.
1100
+ * @beta
1101
+ */
1102
+ class TeamsFx {
1103
+ constructor(identityType, customConfig) {
1104
+ this.identityType = identityType !== null && identityType !== void 0 ? identityType : IdentityType.User;
1105
+ if (this.identityType !== IdentityType.User) {
1106
+ const errorMsg = formatString(ErrorMessage.IdentityTypeNotSupported, this.identityType.toString(), "TeamsFx");
1107
+ internalLogger.error(errorMsg);
1108
+ throw new ErrorWithCode(errorMsg, ErrorCode.IdentityTypeNotSupported);
1109
+ }
1110
+ this.configuration = new Map();
1111
+ this.loadFromEnv();
1112
+ if (customConfig) {
1113
+ for (const key of Object.keys(customConfig)) {
1114
+ const value = customConfig[key];
1115
+ if (value) {
1116
+ this.configuration.set(key, value);
1117
+ }
1118
+ }
1119
+ }
1120
+ if (this.configuration.size === 0) {
1121
+ internalLogger.warn("No configuration is loaded, please pass required configs to TeamsFx constructor");
1122
+ }
1123
+ }
1124
+ loadFromEnv() {
1125
+ if (window && window.__env__) {
1126
+ // testing purpose
1127
+ const env = window.__env__;
1128
+ this.configuration.set("authorityHost", env.REACT_APP_AUTHORITY_HOST);
1129
+ this.configuration.set("tenantId", env.REACT_APP_TENANT_ID);
1130
+ this.configuration.set("clientId", env.REACT_APP_CLIENT_ID);
1131
+ this.configuration.set("initiateLoginEndpoint", env.REACT_APP_START_LOGIN_PAGE_URL);
1132
+ this.configuration.set("applicationIdUri", env.M365_APPLICATION_ID_URI);
1133
+ this.configuration.set("apiEndpoint", env.REACT_APP_FUNC_ENDPOINT);
1134
+ this.configuration.set("apiName", env.REACT_APP_FUNC_NAME);
1135
+ }
1136
+ else {
1137
+ // TODO: support common environment variable name
1138
+ try {
1139
+ this.configuration.set("authorityHost", process.env.REACT_APP_AUTHORITY_HOST);
1140
+ this.configuration.set("tenantId", process.env.REACT_APP_TENANT_ID);
1141
+ this.configuration.set("clientId", process.env.REACT_APP_CLIENT_ID);
1142
+ this.configuration.set("initiateLoginEndpoint", process.env.REACT_APP_START_LOGIN_PAGE_URL);
1143
+ this.configuration.set("applicationIdUri", process.env.M365_APPLICATION_ID_URI);
1144
+ this.configuration.set("apiEndpoint", process.env.REACT_APP_FUNC_ENDPOINT);
1145
+ this.configuration.set("apiName", process.env.REACT_APP_FUNC_NAME);
1146
+ }
1147
+ catch (_) {
1148
+ internalLogger.warn("Cannot read process.env, please use webpack if you want to use environment variables.");
1149
+ return;
1150
+ }
1151
+ }
1152
+ }
1153
+ getIdentityType() {
1154
+ return this.identityType;
1155
+ }
1156
+ getCredential() {
1157
+ if (!this.teamsUserCredential) {
1158
+ this.teamsUserCredential = new TeamsUserCredential(Object.fromEntries(this.configuration));
1159
+ }
1160
+ return this.teamsUserCredential;
1161
+ }
1162
+ getUserInfo() {
1163
+ return __awaiter(this, void 0, void 0, function* () {
1164
+ return yield this.getCredential().getUserInfo();
1165
+ });
1166
+ }
1167
+ login(scopes) {
1168
+ return __awaiter(this, void 0, void 0, function* () {
1169
+ yield this.getCredential().login(scopes);
1170
+ });
1171
+ }
1172
+ setSsoToken(ssoToken) {
1173
+ return this;
1174
+ }
1175
+ getConfig(key) {
1176
+ const value = this.configuration.get(key);
1177
+ if (!value) {
1178
+ throw new Error();
1179
+ }
1180
+ return value;
1181
+ }
1182
+ hasConfig(key) {
1183
+ const value = this.configuration.get(key);
1184
+ return !!value;
1185
+ }
1186
+ getConfigs() {
1187
+ const config = {};
1188
+ for (const key of this.configuration.keys()) {
1189
+ const value = this.configuration.get(key);
1190
+ if (value) {
1191
+ config[key] = value;
1192
+ }
1193
+ }
1194
+ return config;
1195
+ }
1196
+ }
1197
+
1198
+ export { AppCredential, ErrorCode, ErrorWithCode, IdentityType, LogLevel, MsGraphAuthProvider, OnBehalfOfUserCredential, TeamsBotSsoPrompt, TeamsFx, TeamsUserCredential, createMicrosoftGraphClient, getLogLevel, getTediousConnectionConfig, setLogFunction, setLogLevel, setLogger };
1227
1199
  //# sourceMappingURL=index.esm5.js.map