@microsoft/teamsfx 2.3.3 → 3.0.0-alpha.b8a9ab9fa.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,2538 +1,1720 @@
1
- import jwt_decode from 'jwt-decode';
1
+ import { jwtDecode } from 'jwt-decode';
2
2
  import { app, authentication } from '@microsoft/teams-js';
3
3
  import { PublicClientApplication } from '@azure/msal-browser';
4
- import { Client } from '@microsoft/microsoft-graph-client';
5
4
  import axios from 'axios';
6
5
 
7
- // Copyright (c) Microsoft Corporation.
8
- // Licensed under the MIT license.
9
- /**
10
- * Error code to trace the error types.
11
- */
12
- var ErrorCode;
13
- (function (ErrorCode) {
14
- /**
15
- * Invalid parameter error.
16
- */
17
- ErrorCode["InvalidParameter"] = "InvalidParameter";
18
- /**
19
- * Invalid configuration error.
20
- */
21
- ErrorCode["InvalidConfiguration"] = "InvalidConfiguration";
22
- /**
23
- * Invalid certificate error.
24
- */
25
- ErrorCode["InvalidCertificate"] = "InvalidCertificate";
26
- /**
27
- * Internal error.
28
- */
29
- ErrorCode["InternalError"] = "InternalError";
30
- /**
31
- * Channel is not supported error.
32
- */
33
- ErrorCode["ChannelNotSupported"] = "ChannelNotSupported";
34
- /**
35
- * Failed to retrieve sso token
36
- */
37
- ErrorCode["FailedToRetrieveSsoToken"] = "FailedToRetrieveSsoToken";
38
- /**
39
- * Failed to process sso handler
40
- */
41
- ErrorCode["FailedToProcessSsoHandler"] = "FailedToProcessSsoHandler";
42
- /**
43
- * Cannot find command
44
- */
45
- ErrorCode["CannotFindCommand"] = "CannotFindCommand";
46
- /**
47
- * Failed to run sso step
48
- */
49
- ErrorCode["FailedToRunSsoStep"] = "FailedToRunSsoStep";
50
- /**
51
- * Failed to run dedup step
52
- */
53
- ErrorCode["FailedToRunDedupStep"] = "FailedToRunDedupStep";
54
- /**
55
- * Sso activity handler is undefined
56
- */
57
- ErrorCode["SsoActivityHandlerIsUndefined"] = "SsoActivityHandlerIsUndefined";
58
- /**
59
- * Runtime is not supported error.
60
- */
61
- ErrorCode["RuntimeNotSupported"] = "RuntimeNotSupported";
62
- /**
63
- * User failed to finish the AAD consent flow failed.
64
- */
65
- ErrorCode["ConsentFailed"] = "ConsentFailed";
66
- /**
67
- * The user or administrator has not consented to use the application error.
68
- */
69
- ErrorCode["UiRequiredError"] = "UiRequiredError";
70
- /**
71
- * Token is not within its valid time range error.
72
- */
73
- ErrorCode["TokenExpiredError"] = "TokenExpiredError";
74
- /**
75
- * Call service (AAD or simple authentication server) failed.
76
- */
77
- ErrorCode["ServiceError"] = "ServiceError";
78
- /**
79
- * Operation failed.
80
- */
81
- ErrorCode["FailedOperation"] = "FailedOperation";
82
- /**
83
- * Invalid response error.
84
- */
85
- ErrorCode["InvalidResponse"] = "InvalidResponse";
86
- /**
87
- * Identity type error.
88
- */
89
- ErrorCode["IdentityTypeNotSupported"] = "IdentityTypeNotSupported";
90
- /**
91
- * Authentication info already exists error.
92
- */
93
- ErrorCode["AuthorizationInfoAlreadyExists"] = "AuthorizationInfoAlreadyExists";
94
- })(ErrorCode || (ErrorCode = {}));
95
- /**
96
- * @internal
97
- */
98
- class ErrorMessage {
99
- }
100
- // InvalidConfiguration Error
101
- ErrorMessage.InvalidConfiguration = "{0} in configuration is invalid: {1}.";
102
- ErrorMessage.ConfigurationNotExists = "Configuration does not exist. {0}";
103
- ErrorMessage.ResourceConfigurationNotExists = "{0} resource configuration does not exist.";
104
- ErrorMessage.MissingResourceConfiguration = "Missing resource configuration with type: {0}, name: {1}.";
105
- ErrorMessage.AuthenticationConfigurationNotExists = "Authentication configuration does not exist.";
106
- // RuntimeNotSupported Error
107
- ErrorMessage.BrowserRuntimeNotSupported = "{0} is not supported in browser.";
108
- ErrorMessage.NodejsRuntimeNotSupported = "{0} is not supported in Node.";
109
- // Internal Error
110
- ErrorMessage.FailToAcquireTokenOnBehalfOfUser = "Failed to acquire access token on behalf of user: {0}";
111
- // ChannelNotSupported Error
112
- ErrorMessage.OnlyMSTeamsChannelSupported = "{0} is only supported in MS Teams Channel";
113
- ErrorMessage.FailedToProcessSsoHandler = "Failed to process sso handler: {0}";
114
- // FailedToRetrieveSsoToken Error
115
- ErrorMessage.FailedToRetrieveSsoToken = "Failed to retrieve sso token, user failed to finish the AAD consent flow.";
116
- // CannotFindCommand Error
117
- ErrorMessage.CannotFindCommand = "Cannot find command: {0}";
118
- ErrorMessage.FailedToRunSsoStep = "Failed to run dialog to retrieve sso token: {0}";
119
- ErrorMessage.FailedToRunDedupStep = "Failed to run dialog to remove duplicated messages: {0}";
120
- // SsoActivityHandlerIsUndefined Error
121
- ErrorMessage.SsoActivityHandlerIsNull = "Sso command can only be used or added when sso activity handler is not undefined";
122
- // IdentityTypeNotSupported Error
123
- ErrorMessage.IdentityTypeNotSupported = "{0} identity is not supported in {1}";
124
- // AuthorizationInfoError
125
- ErrorMessage.AuthorizationHeaderAlreadyExists = "Authorization header already exists!";
126
- ErrorMessage.BasicCredentialAlreadyExists = "Basic credential already exists!";
127
- // InvalidParameter Error
128
- ErrorMessage.EmptyParameter = "Parameter {0} is empty";
129
- ErrorMessage.DuplicateHttpsOptionProperty = "Axios HTTPS agent already defined value for property {0}";
130
- ErrorMessage.DuplicateApiKeyInHeader = "The request already defined api key in request header with name {0}.";
131
- ErrorMessage.DuplicateApiKeyInQueryParam = "The request already defined api key in query parameter with name {0}.";
132
- ErrorMessage.OnlySupportInQueryActivity = "The handleMessageExtensionQueryWithToken only support in handleTeamsMessagingExtensionQuery with composeExtension/query type.";
133
- ErrorMessage.OnlySupportInLinkQueryActivity = "The handleMessageExtensionLinkQueryWithSSO only support in handleTeamsAppBasedLinkQuery with composeExtension/queryLink type.";
134
- /**
135
- * Error class with code and message thrown by the SDK.
136
- */
137
- class ErrorWithCode extends Error {
138
- /**
139
- * Constructor of ErrorWithCode.
140
- *
141
- * @param {string} message - error message.
142
- * @param {ErrorCode} code - error code.
143
- */
144
- constructor(message, code) {
145
- if (!code) {
146
- super(message);
147
- return this;
148
- }
149
- super(message);
150
- Object.setPrototypeOf(this, ErrorWithCode.prototype);
151
- this.name = `${new.target.name}.${code}`;
152
- this.code = code;
153
- }
6
+ // Copyright (c) Microsoft Corporation.
7
+ // Licensed under the MIT license.
8
+ /**
9
+ * Error code to trace the error types.
10
+ */
11
+ var ErrorCode;
12
+ (function (ErrorCode) {
13
+ /**
14
+ * Invalid parameter error.
15
+ */
16
+ ErrorCode["InvalidParameter"] = "InvalidParameter";
17
+ /**
18
+ * Invalid configuration error.
19
+ */
20
+ ErrorCode["InvalidConfiguration"] = "InvalidConfiguration";
21
+ /**
22
+ * Invalid certificate error.
23
+ */
24
+ ErrorCode["InvalidCertificate"] = "InvalidCertificate";
25
+ /**
26
+ * Internal error.
27
+ */
28
+ ErrorCode["InternalError"] = "InternalError";
29
+ /**
30
+ * Channel is not supported error.
31
+ */
32
+ ErrorCode["ChannelNotSupported"] = "ChannelNotSupported";
33
+ /**
34
+ * Failed to retrieve sso token
35
+ */
36
+ ErrorCode["FailedToRetrieveSsoToken"] = "FailedToRetrieveSsoToken";
37
+ /**
38
+ * Failed to process sso handler
39
+ */
40
+ ErrorCode["FailedToProcessSsoHandler"] = "FailedToProcessSsoHandler";
41
+ /**
42
+ * Cannot find command
43
+ */
44
+ ErrorCode["CannotFindCommand"] = "CannotFindCommand";
45
+ /**
46
+ * Failed to run sso step
47
+ */
48
+ ErrorCode["FailedToRunSsoStep"] = "FailedToRunSsoStep";
49
+ /**
50
+ * Failed to run dedup step
51
+ */
52
+ ErrorCode["FailedToRunDedupStep"] = "FailedToRunDedupStep";
53
+ /**
54
+ * Sso activity handler is undefined
55
+ */
56
+ ErrorCode["SsoActivityHandlerIsUndefined"] = "SsoActivityHandlerIsUndefined";
57
+ /**
58
+ * Runtime is not supported error.
59
+ */
60
+ ErrorCode["RuntimeNotSupported"] = "RuntimeNotSupported";
61
+ /**
62
+ * User failed to finish the AAD consent flow failed.
63
+ */
64
+ ErrorCode["ConsentFailed"] = "ConsentFailed";
65
+ /**
66
+ * The user or administrator has not consented to use the application error.
67
+ */
68
+ ErrorCode["UiRequiredError"] = "UiRequiredError";
69
+ /**
70
+ * Token is not within its valid time range error.
71
+ */
72
+ ErrorCode["TokenExpiredError"] = "TokenExpiredError";
73
+ /**
74
+ * Call service (AAD or simple authentication server) failed.
75
+ */
76
+ ErrorCode["ServiceError"] = "ServiceError";
77
+ /**
78
+ * Operation failed.
79
+ */
80
+ ErrorCode["FailedOperation"] = "FailedOperation";
81
+ /**
82
+ * Invalid response error.
83
+ */
84
+ ErrorCode["InvalidResponse"] = "InvalidResponse";
85
+ /**
86
+ * Authentication info already exists error.
87
+ */
88
+ ErrorCode["AuthorizationInfoAlreadyExists"] = "AuthorizationInfoAlreadyExists";
89
+ })(ErrorCode || (ErrorCode = {}));
90
+ /**
91
+ * @internal
92
+ */
93
+ class ErrorMessage {
154
94
  }
155
-
156
- // Copyright (c) Microsoft Corporation.
157
- // Licensed under the MIT license.
158
- /**
159
- * Log level.
160
- */
161
- var LogLevel;
162
- (function (LogLevel) {
163
- /**
164
- * Show verbose, information, warning and error message.
165
- */
166
- LogLevel[LogLevel["Verbose"] = 0] = "Verbose";
167
- /**
168
- * Show information, warning and error message.
169
- */
170
- LogLevel[LogLevel["Info"] = 1] = "Info";
171
- /**
172
- * Show warning and error message.
173
- */
174
- LogLevel[LogLevel["Warn"] = 2] = "Warn";
175
- /**
176
- * Show error message.
177
- */
178
- LogLevel[LogLevel["Error"] = 3] = "Error";
179
- })(LogLevel || (LogLevel = {}));
180
- /**
181
- * Update log level helper.
182
- *
183
- * @param { LogLevel } level - log level in configuration
184
- */
185
- function setLogLevel(level) {
186
- internalLogger.level = level;
187
- }
188
- /**
189
- * Get log level.
190
- *
191
- * @returns Log level
192
- */
193
- function getLogLevel() {
194
- return internalLogger.level;
195
- }
196
- class InternalLogger {
197
- constructor(name, logLevel) {
198
- this.level = undefined;
199
- this.defaultLogger = {
200
- verbose: console.debug,
201
- info: console.info,
202
- warn: console.warn,
203
- error: console.error,
204
- };
205
- this.name = name;
206
- this.level = logLevel;
207
- }
208
- error(message) {
209
- this.log(LogLevel.Error, (x) => x.error, message);
210
- }
211
- warn(message) {
212
- this.log(LogLevel.Warn, (x) => x.warn, message);
213
- }
214
- info(message) {
215
- this.log(LogLevel.Info, (x) => x.info, message);
216
- }
217
- verbose(message) {
218
- this.log(LogLevel.Verbose, (x) => x.verbose, message);
219
- }
220
- log(logLevel, logFunction, message) {
221
- if (message.trim() === "") {
222
- return;
223
- }
224
- const timestamp = new Date().toUTCString();
225
- let logHeader;
226
- if (this.name) {
227
- logHeader = `[${timestamp}] : @microsoft/teamsfx - ${this.name} : ${LogLevel[logLevel]} - `;
228
- }
229
- else {
230
- logHeader = `[${timestamp}] : @microsoft/teamsfx : ${LogLevel[logLevel]} - `;
231
- }
232
- const logMessage = `${logHeader}${message}`;
233
- if (this.level !== undefined && this.level <= logLevel) {
234
- if (this.customLogger) {
235
- logFunction(this.customLogger)(logMessage);
236
- }
237
- else if (this.customLogFunction) {
238
- this.customLogFunction(logLevel, logMessage);
239
- }
240
- else {
241
- logFunction(this.defaultLogger)(logMessage);
242
- }
243
- }
244
- }
245
- }
246
- /**
247
- * Logger instance used internally
248
- *
249
- * @internal
250
- */
251
- const internalLogger = new InternalLogger();
252
- /**
253
- * Set custom logger. Use the output functions if it's set. Priority is higher than setLogFunction.
254
- *
255
- * @param {Logger} logger - custom logger. If it's undefined, custom logger will be cleared.
256
- *
257
- * @example
258
- * ```typescript
259
- * setLogger({
260
- * verbose: console.debug,
261
- * info: console.info,
262
- * warn: console.warn,
263
- * error: console.error,
264
- * });
265
- * ```
266
- */
267
- function setLogger(logger) {
268
- internalLogger.customLogger = logger;
269
- }
270
- /**
271
- * Set custom log function. Use the function if it's set. Priority is lower than setLogger.
272
- *
273
- * @param {LogFunction} logFunction - custom log function. If it's undefined, custom log function will be cleared.
274
- *
275
- * @example
276
- * ```typescript
277
- * setLogFunction((level: LogLevel, message: string) => {
278
- * if (level === LogLevel.Error) {
279
- * console.log(message);
280
- * }
281
- * });
282
- * ```
283
- */
284
- function setLogFunction(logFunction) {
285
- internalLogger.customLogFunction = logFunction;
95
+ // InvalidConfiguration Error
96
+ ErrorMessage.InvalidConfiguration = "{0} in configuration is invalid: {1}.";
97
+ ErrorMessage.ConfigurationNotExists = "Configuration does not exist. {0}";
98
+ ErrorMessage.ResourceConfigurationNotExists = "{0} resource configuration does not exist.";
99
+ ErrorMessage.MissingResourceConfiguration = "Missing resource configuration with type: {0}, name: {1}.";
100
+ ErrorMessage.AuthenticationConfigurationNotExists = "Authentication configuration does not exist.";
101
+ // RuntimeNotSupported Error
102
+ ErrorMessage.BrowserRuntimeNotSupported = "{0} is not supported in browser.";
103
+ ErrorMessage.NodejsRuntimeNotSupported = "{0} is not supported in Node.";
104
+ // Internal Error
105
+ ErrorMessage.FailToAcquireTokenOnBehalfOfUser = "Failed to acquire access token on behalf of user: {0}";
106
+ // ChannelNotSupported Error
107
+ ErrorMessage.OnlyMSTeamsChannelSupported = "{0} is only supported in MS Teams Channel";
108
+ ErrorMessage.FailedToProcessSsoHandler = "Failed to process sso handler: {0}";
109
+ // FailedToRetrieveSsoToken Error
110
+ ErrorMessage.FailedToRetrieveSsoToken = "Failed to retrieve sso token, user failed to finish the AAD consent flow.";
111
+ // CannotFindCommand Error
112
+ ErrorMessage.CannotFindCommand = "Cannot find command: {0}";
113
+ ErrorMessage.FailedToRunSsoStep = "Failed to run dialog to retrieve sso token: {0}";
114
+ ErrorMessage.FailedToRunDedupStep = "Failed to run dialog to remove duplicated messages: {0}";
115
+ // SsoActivityHandlerIsUndefined Error
116
+ ErrorMessage.SsoActivityHandlerIsNull = "Sso command can only be used or added when sso activity handler is not undefined";
117
+ // AuthorizationInfoError
118
+ ErrorMessage.AuthorizationHeaderAlreadyExists = "Authorization header already exists!";
119
+ ErrorMessage.BasicCredentialAlreadyExists = "Basic credential already exists!";
120
+ // InvalidParameter Error
121
+ ErrorMessage.EmptyParameter = "Parameter {0} is empty";
122
+ ErrorMessage.DuplicateHttpsOptionProperty = "Axios HTTPS agent already defined value for property {0}";
123
+ ErrorMessage.DuplicateApiKeyInHeader = "The request already defined api key in request header with name {0}.";
124
+ ErrorMessage.DuplicateApiKeyInQueryParam = "The request already defined api key in query parameter with name {0}.";
125
+ ErrorMessage.OnlySupportInQueryActivity = "The handleMessageExtensionQueryWithToken only support in handleTeamsMessagingExtensionQuery with composeExtension/query type.";
126
+ ErrorMessage.OnlySupportInLinkQueryActivity = "The handleMessageExtensionLinkQueryWithSSO only support in handleTeamsAppBasedLinkQuery with composeExtension/queryLink type.";
127
+ /**
128
+ * Error class with code and message thrown by the SDK.
129
+ */
130
+ class ErrorWithCode extends Error {
131
+ /**
132
+ * Constructor of ErrorWithCode.
133
+ *
134
+ * @param {string} message - error message.
135
+ * @param {ErrorCode} code - error code.
136
+ */
137
+ constructor(message, code) {
138
+ if (!code) {
139
+ super(message);
140
+ return this;
141
+ }
142
+ super(message);
143
+ Object.setPrototypeOf(this, ErrorWithCode.prototype);
144
+ this.name = `${new.target.name}.${code}`;
145
+ this.code = code;
146
+ }
286
147
  }
287
148
 
288
- // Copyright (c) Microsoft Corporation.
289
- /**
290
- * Parse jwt token payload
291
- *
292
- * @param token
293
- *
294
- * @returns Payload object
295
- *
296
- * @internal
297
- */
298
- function parseJwt(token) {
299
- try {
300
- const tokenObj = jwt_decode(token);
301
- if (!tokenObj || !tokenObj.exp) {
302
- throw new ErrorWithCode("Decoded token is null or exp claim does not exists.", ErrorCode.InternalError);
303
- }
304
- return tokenObj;
305
- }
306
- catch (err) {
307
- const errorMsg = "Parse jwt token failed in node env with error: " + err.message;
308
- internalLogger.error(errorMsg);
309
- throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
310
- }
311
- }
312
- /**
313
- * @internal
314
- */
315
- function getUserInfoFromSsoToken(ssoToken) {
316
- if (!ssoToken) {
317
- const errorMsg = "SSO token is undefined.";
318
- internalLogger.error(errorMsg);
319
- throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);
320
- }
321
- const tokenObject = parseJwt(ssoToken);
322
- const userInfo = {
323
- displayName: tokenObject.name,
324
- objectId: tokenObject.oid,
325
- tenantId: tokenObject.tid,
326
- preferredUserName: "",
327
- };
328
- if (tokenObject.ver === "2.0") {
329
- userInfo.preferredUserName = tokenObject.preferred_username;
330
- }
331
- else if (tokenObject.ver === "1.0") {
332
- userInfo.preferredUserName = tokenObject.upn;
333
- }
334
- return userInfo;
335
- }
336
- /**
337
- * @internal
338
- */
339
- function getTenantIdAndLoginHintFromSsoToken(ssoToken) {
340
- if (!ssoToken) {
341
- const errorMsg = "SSO token is undefined.";
342
- internalLogger.error(errorMsg);
343
- throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);
344
- }
345
- const tokenObject = parseJwt(ssoToken);
346
- const userInfo = {
347
- tid: tokenObject.tid,
348
- loginHint: tokenObject.ver === "2.0"
349
- ? tokenObject.preferred_username
350
- : tokenObject.upn,
351
- };
352
- return userInfo;
353
- }
354
- /**
355
- * @internal
356
- */
357
- function parseAccessTokenFromAuthCodeTokenResponse(tokenResponse) {
358
- try {
359
- const tokenResponseObject = typeof tokenResponse == "string"
360
- ? JSON.parse(tokenResponse)
361
- : tokenResponse;
362
- if (!tokenResponseObject || !tokenResponseObject.accessToken) {
363
- const errorMsg = "Get empty access token from Auth Code token response.";
364
- internalLogger.error(errorMsg);
365
- throw new Error(errorMsg);
366
- }
367
- const token = tokenResponseObject.accessToken;
368
- const tokenObject = parseJwt(token);
369
- if (tokenObject.ver !== "1.0" && tokenObject.ver !== "2.0") {
370
- const errorMsg = "SSO token is not valid with an unknown version: " + tokenObject.ver;
371
- internalLogger.error(errorMsg);
372
- throw new Error(errorMsg);
373
- }
374
- const accessToken = {
375
- token: token,
376
- expiresOnTimestamp: tokenObject.exp * 1000,
377
- };
378
- return accessToken;
379
- }
380
- catch (error) {
381
- const errorMsg = "Parse access token failed from Auth Code token response in node env with error: " +
382
- error.message;
383
- internalLogger.error(errorMsg);
384
- throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
385
- }
386
- }
387
- /**
388
- * Format string template with replacements
389
- *
390
- * ```typescript
391
- * const template = "{0} and {1} are fruit. {0} is my favorite one."
392
- * const formattedStr = formatString(template, "apple", "pear"); // formattedStr: "apple and pear are fruit. apple is my favorite one."
393
- * ```
394
- *
395
- * @param str string template
396
- * @param replacements replacement string array
397
- * @returns Formatted string
398
- *
399
- * @internal
400
- */
401
- function formatString(str, ...replacements) {
402
- const args = replacements;
403
- return str.replace(/{(\d+)}/g, function (match, number) {
404
- return typeof args[number] != "undefined" ? args[number] : match;
405
- });
406
- }
407
- /**
408
- * @internal
409
- */
410
- function validateScopesType(value) {
411
- // string
412
- if (typeof value === "string" || value instanceof String) {
413
- return;
414
- }
415
- // empty array
416
- if (Array.isArray(value) && value.length === 0) {
417
- return;
418
- }
419
- // string array
420
- if (Array.isArray(value) && value.length > 0 && value.every((item) => typeof item === "string")) {
421
- return;
422
- }
423
- const errorMsg = "The type of scopes is not valid, it must be string or string array";
424
- internalLogger.error(errorMsg);
425
- throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);
149
+ // Copyright (c) Microsoft Corporation.
150
+ // Licensed under the MIT license.
151
+ /**
152
+ * Log level.
153
+ */
154
+ var LogLevel;
155
+ (function (LogLevel) {
156
+ /**
157
+ * Show verbose, information, warning and error message.
158
+ */
159
+ LogLevel[LogLevel["Verbose"] = 0] = "Verbose";
160
+ /**
161
+ * Show information, warning and error message.
162
+ */
163
+ LogLevel[LogLevel["Info"] = 1] = "Info";
164
+ /**
165
+ * Show warning and error message.
166
+ */
167
+ LogLevel[LogLevel["Warn"] = 2] = "Warn";
168
+ /**
169
+ * Show error message.
170
+ */
171
+ LogLevel[LogLevel["Error"] = 3] = "Error";
172
+ })(LogLevel || (LogLevel = {}));
173
+ /**
174
+ * Update log level helper.
175
+ *
176
+ * @param { LogLevel } level - log level in configuration
177
+ */
178
+ function setLogLevel(level) {
179
+ internalLogger.level = level;
426
180
  }
427
-
428
- // Copyright (c) Microsoft Corporation.
429
- /**
430
- * Represent Microsoft 365 tenant identity, and it is usually used when user is not involved.
431
- *
432
- * @remarks
433
- * Only works in in server side.
434
- */
435
- class AppCredential {
436
- constructor(authConfig) {
437
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "AppCredential"), ErrorCode.RuntimeNotSupported);
438
- }
439
- /**
440
- * Get access token for credential.
441
- *
442
- * @remarks
443
- * Only works in in server side.
444
- */
445
- getToken(scopes, options) {
446
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "AppCredential"), ErrorCode.RuntimeNotSupported));
447
- }
181
+ /**
182
+ * Get log level.
183
+ *
184
+ * @returns Log level
185
+ */
186
+ function getLogLevel() {
187
+ return internalLogger.level;
448
188
  }
449
-
450
- // Copyright (c) Microsoft Corporation.
451
- /**
452
- * Represent on-behalf-of flow to get user identity, and it is designed to be used in Azure Function or Bot scenarios.
453
- *
454
- * @remarks
455
- * Can only be used in server side.
456
- */
457
- class OnBehalfOfUserCredential {
458
- constructor(ssoToken, config) {
459
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "OnBehalfOfUserCredential"), ErrorCode.RuntimeNotSupported);
460
- }
461
- /**
462
- * Get access token from credential.
463
- * @remarks
464
- * Can only be used in server side.
465
- */
466
- getToken(scopes, options) {
467
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "OnBehalfOfUserCredential"), ErrorCode.RuntimeNotSupported));
468
- }
469
- /**
470
- * Get basic user info from SSO token.
471
- * @remarks
472
- * Can only be used in server side.
473
- */
474
- getUserInfo() {
475
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "OnBehalfOfUserCredential"), ErrorCode.RuntimeNotSupported));
476
- }
189
+ class InternalLogger {
190
+ constructor(name, logLevel) {
191
+ this.level = undefined;
192
+ this.defaultLogger = {
193
+ verbose: console.debug,
194
+ info: console.info,
195
+ warn: console.warn,
196
+ error: console.error,
197
+ };
198
+ this.name = name;
199
+ this.level = logLevel;
200
+ }
201
+ error(message) {
202
+ this.log(LogLevel.Error, (x) => x.error, message);
203
+ }
204
+ warn(message) {
205
+ this.log(LogLevel.Warn, (x) => x.warn, message);
206
+ }
207
+ info(message) {
208
+ this.log(LogLevel.Info, (x) => x.info, message);
209
+ }
210
+ verbose(message) {
211
+ this.log(LogLevel.Verbose, (x) => x.verbose, message);
212
+ }
213
+ log(logLevel, logFunction, message) {
214
+ if (message.trim() === "") {
215
+ return;
216
+ }
217
+ const timestamp = new Date().toUTCString();
218
+ let logHeader;
219
+ if (this.name) {
220
+ logHeader = `[${timestamp}] : @microsoft/teamsfx - ${this.name} : ${LogLevel[logLevel]} - `;
221
+ }
222
+ else {
223
+ logHeader = `[${timestamp}] : @microsoft/teamsfx : ${LogLevel[logLevel]} - `;
224
+ }
225
+ const logMessage = `${logHeader}${message}`;
226
+ if (this.level !== undefined && this.level <= logLevel) {
227
+ if (this.customLogger) {
228
+ logFunction(this.customLogger)(logMessage);
229
+ }
230
+ else if (this.customLogFunction) {
231
+ this.customLogFunction(logLevel, logMessage);
232
+ }
233
+ else {
234
+ logFunction(this.defaultLogger)(logMessage);
235
+ }
236
+ }
237
+ }
477
238
  }
478
-
479
- // Copyright (c) Microsoft Corporation.
480
- const tokenRefreshTimeSpanInMillisecond = 5 * 60 * 1000;
481
- const loginPageWidth = 600;
482
- const loginPageHeight = 535;
483
- /**
484
- * Represent Teams current user's identity, and it is used within Teams tab application.
485
- *
486
- * @remarks
487
- * Can only be used within Teams.
488
- */
489
- class TeamsUserCredential {
490
- constructor(authConfig) {
491
- internalLogger.info("Create teams user credential");
492
- this.config = this.loadAndValidateConfig(authConfig);
493
- this.ssoToken = null;
494
- this.initialized = false;
495
- }
496
- /**
497
- * Popup login page to get user's access token with specific scopes.
498
- *
499
- * @remarks
500
- * Only works in Teams client APP. User will be redirected to the authorization page to login and consent.
501
- *
502
- * @example
503
- * ```typescript
504
- * await credential.login(["https://graph.microsoft.com/User.Read"]); // single scope using string array
505
- * await credential.login("https://graph.microsoft.com/User.Read"); // single scopes using string
506
- * await credential.login(["https://graph.microsoft.com/User.Read", "Calendars.Read"]); // multiple scopes using string array
507
- * await credential.login("https://graph.microsoft.com/User.Read Calendars.Read"); // multiple scopes using string
508
- * ```
509
- * @param scopes - The list of scopes for which the token will have access, before that, we will request user to consent.
510
- * @param { string[] } resources - The optional list of resources for full trust Teams apps.
511
- *
512
- * @throws {@link ErrorCode|InternalError} when failed to login with unknown error.
513
- * @throws {@link ErrorCode|ConsentFailed} when user canceled or failed to consent.
514
- * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.
515
- * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.
516
- */
517
- async login(scopes, resources) {
518
- validateScopesType(scopes);
519
- const scopesStr = typeof scopes === "string" ? scopes : scopes.join(" ");
520
- internalLogger.info(`Popup login page to get user's access token with scopes: ${scopesStr}`);
521
- if (!this.initialized) {
522
- await this.init(resources);
523
- }
524
- await app.initialize();
525
- let result;
526
- try {
527
- const params = {
528
- url: `${this.config.initiateLoginEndpoint ? this.config.initiateLoginEndpoint : ""}?clientId=${this.config.clientId ? this.config.clientId : ""}&scope=${encodeURI(scopesStr)}&loginHint=${this.loginHint ? this.loginHint : ""}`,
529
- width: loginPageWidth,
530
- height: loginPageHeight,
531
- };
532
- result = await authentication.authenticate(params);
533
- if (!result) {
534
- const errorMsg = "Get empty authentication result from MSAL";
535
- internalLogger.error(errorMsg);
536
- throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
537
- }
538
- }
539
- catch (err) {
540
- const errorMsg = `Consent failed for the scope ${scopesStr} with error: ${err.message}`;
541
- internalLogger.error(errorMsg);
542
- throw new ErrorWithCode(errorMsg, ErrorCode.ConsentFailed);
543
- }
544
- let resultJson = {};
545
- try {
546
- resultJson = typeof result == "string" ? JSON.parse(result) : result;
547
- }
548
- catch (error) {
549
- // If can not parse result as Json, will throw error.
550
- const failedToParseResult = "Failed to parse response to Json.";
551
- internalLogger.error(failedToParseResult);
552
- throw new ErrorWithCode(failedToParseResult, ErrorCode.InvalidResponse);
553
- }
554
- // If code exists in result, user may using previous auth-start and auth-end page.
555
- if (resultJson.code) {
556
- const helpLink = "https://aka.ms/teamsfx-auth-code-flow";
557
- const usingPreviousAuthPage = "Found auth code in response. Auth code is not support for current version of SDK. " +
558
- `Please refer to the help link for how to fix the issue: ${helpLink}.`;
559
- internalLogger.error(usingPreviousAuthPage);
560
- throw new ErrorWithCode(usingPreviousAuthPage, ErrorCode.InvalidResponse);
561
- }
562
- // If sessionStorage exists in result, set the values in current session storage.
563
- if (resultJson.sessionStorage) {
564
- this.setSessionStorage(resultJson.sessionStorage);
565
- }
566
- }
567
- /**
568
- * Get access token from credential.
569
- *
570
- * Important: Access tokens are stored in sessionStorage, read more here: https://aka.ms/teamsfx-session-storage-notice
571
- * Important: Full trust applications do not read the resource information from the webApplicationInfo section of the app
572
- * manifest. Instead, this resource (along with any additional resources from which to request tokens) must be provided
573
- * as a list of resources to the getToken() method through a GetTeamsUserTokenOptions object.
574
- *
575
- * @example
576
- * ```typescript
577
- * await credential.getToken([]) // Get SSO token using empty string array
578
- * await credential.getToken("") // Get SSO token using empty string
579
- * await credential.getToken([".default"]) // Get Graph access token with default scope using string array
580
- * await credential.getToken(".default") // Get Graph access token with default scope using string
581
- * await credential.getToken(["User.Read"]) // Get Graph access token for single scope using string array
582
- * await credential.getToken("User.Read") // Get Graph access token for single scope using string
583
- * await credential.getToken(["User.Read", "Application.Read.All"]) // Get Graph access token for multiple scopes using string array
584
- * await credential.getToken("User.Read Application.Read.All") // Get Graph access token for multiple scopes using space-separated string
585
- * await credential.getToken("https://graph.microsoft.com/User.Read") // Get Graph access token with full resource URI
586
- * await credential.getToken(["https://outlook.office.com/Mail.Read"]) // Get Outlook access token
587
- *
588
- * const options: GetTeamsUserTokenOptions = { resources: ["https://domain.example.com"] }; // set up resources for full trust apps.
589
- * await credential.getToken([], options) // Get sso token from teams client - only use this approach for full trust apps.
590
- * ```
591
- *
592
- * @param {string | string[]} scopes - The list of scopes for which the token will have access.
593
- * @param {GetTokenOptions} options - The options used to configure any requests this TokenCredential implementation might make.
594
- *
595
- * @throws {@link ErrorCode|InternalError} when failed to get access token with unknown error.
596
- * @throws {@link ErrorCode|UiRequiredError} when need user consent to get access token.
597
- * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.
598
- * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.
599
- *
600
- * @returns User access token of defined scopes.
601
- * If scopes is empty string or array, it returns SSO token.
602
- * If scopes is non-empty, it returns access token for target scope.
603
- * Throw error if get access token failed.
604
- */
605
- async getToken(scopes, options) {
606
- var _a;
607
- validateScopesType(scopes);
608
- const resources = (_a = options) === null || _a === void 0 ? void 0 : _a.resources;
609
- const ssoToken = await this.getSSOToken(resources);
610
- const scopeStr = typeof scopes === "string" ? scopes : scopes.join(" ");
611
- if (scopeStr === "") {
612
- internalLogger.info("Get SSO token");
613
- return ssoToken;
614
- }
615
- else {
616
- internalLogger.info("Get access token with scopes: " + scopeStr);
617
- if (!this.initialized) {
618
- await this.init(resources);
619
- }
620
- let tokenResponse;
621
- const scopesArray = typeof scopes === "string" ? scopes.split(" ") : scopes;
622
- const domain = window.location.origin;
623
- // First try to get Access Token from cache.
624
- try {
625
- const account = this.msalInstance.getAccountByUsername(this.loginHint);
626
- const scopesRequestForAcquireTokenSilent = {
627
- scopes: scopesArray,
628
- account: account !== null && account !== void 0 ? account : undefined,
629
- redirectUri: `${domain}/blank-auth-end.html`,
630
- };
631
- tokenResponse = await this.msalInstance.acquireTokenSilent(scopesRequestForAcquireTokenSilent);
632
- }
633
- catch (error) {
634
- const acquireTokenSilentFailedMessage = `Failed to call acquireTokenSilent. Reason: ${error === null || error === void 0 ? void 0 : error.message}. `;
635
- internalLogger.verbose(acquireTokenSilentFailedMessage);
636
- }
637
- if (!tokenResponse) {
638
- // If fail to get Access Token from cache, try to get Access token by silent login.
639
- try {
640
- const scopesRequestForSsoSilent = {
641
- scopes: scopesArray,
642
- loginHint: this.loginHint,
643
- redirectUri: `${domain}/blank-auth-end.html`,
644
- };
645
- tokenResponse = await this.msalInstance.ssoSilent(scopesRequestForSsoSilent);
646
- }
647
- catch (error) {
648
- const ssoSilentFailedMessage = `Failed to call ssoSilent. Reason: ${error === null || error === void 0 ? void 0 : error.message}. `;
649
- internalLogger.verbose(ssoSilentFailedMessage);
650
- }
651
- }
652
- if (!tokenResponse) {
653
- const errorMsg = `Failed to get access token cache silently, please login first: you need login first before get access token.`;
654
- internalLogger.error(errorMsg);
655
- throw new ErrorWithCode(errorMsg, ErrorCode.UiRequiredError);
656
- }
657
- const accessToken = parseAccessTokenFromAuthCodeTokenResponse(tokenResponse);
658
- return accessToken;
659
- }
660
- }
661
- /**
662
- * Get basic user info from SSO token
663
- *
664
- * @param {string[]} resources - The optional list of resources for full trust Teams apps.
665
- *
666
- * @example
667
- * ```typescript
668
- * const currentUser = await credential.getUserInfo();
669
- * ```
670
- *
671
- * @throws {@link ErrorCode|InternalError} when SSO token from Teams client is not valid.
672
- * @throws {@link ErrorCode|InvalidParameter} when SSO token from Teams client is empty.
673
- * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.
674
- *
675
- * @returns Basic user info with user displayName, objectId and preferredUserName.
676
- */
677
- async getUserInfo(resources) {
678
- internalLogger.info("Get basic user info from SSO token");
679
- const ssoToken = await this.getSSOToken(resources);
680
- return getUserInfoFromSsoToken(ssoToken.token);
681
- }
682
- async init(resources) {
683
- const ssoToken = await this.getSSOToken(resources);
684
- const info = getTenantIdAndLoginHintFromSsoToken(ssoToken.token);
685
- this.loginHint = info.loginHint;
686
- this.tid = info.tid;
687
- const msalConfig = {
688
- auth: {
689
- clientId: this.config.clientId,
690
- authority: `https://login.microsoftonline.com/${this.tid}`,
691
- },
692
- cache: {
693
- cacheLocation: "sessionStorage",
694
- },
695
- };
696
- this.msalInstance = new PublicClientApplication(msalConfig);
697
- await this.msalInstance.initialize();
698
- this.initialized = true;
699
- }
700
- /**
701
- * Get SSO token using teams SDK
702
- * It will try to get SSO token from memory first, if SSO token doesn't exist or about to expired, then it will using teams SDK to get SSO token
703
- *
704
- * @param {string[]} resources - The optional list of resources for full trust Teams apps.
705
- *
706
- * @returns SSO token
707
- */
708
- async getSSOToken(resources) {
709
- if (this.ssoToken) {
710
- if (this.ssoToken.expiresOnTimestamp - Date.now() > tokenRefreshTimeSpanInMillisecond) {
711
- internalLogger.verbose("Get SSO token from memory cache");
712
- return this.ssoToken;
713
- }
714
- }
715
- const params = { resources: resources !== null && resources !== void 0 ? resources : [] };
716
- let token;
717
- try {
718
- await app.initialize();
719
- }
720
- catch (err) {
721
- const errorMsg = "Initialize teams sdk failed due to not running inside Teams environment";
722
- internalLogger.error(errorMsg);
723
- throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
724
- }
725
- try {
726
- token = await authentication.getAuthToken(params);
727
- }
728
- catch (err) {
729
- const errorMsg = "Get SSO token failed with error: " + err.message;
730
- internalLogger.error(errorMsg);
731
- throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
732
- }
733
- if (!token) {
734
- const errorMsg = "Get empty SSO token from Teams";
735
- internalLogger.error(errorMsg);
736
- throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
737
- }
738
- const tokenObject = parseJwt(token);
739
- if (tokenObject.ver !== "1.0" && tokenObject.ver !== "2.0") {
740
- const errorMsg = "SSO token is not valid with an unknown version: " + tokenObject.ver;
741
- internalLogger.error(errorMsg);
742
- throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
743
- }
744
- const ssoToken = {
745
- token,
746
- expiresOnTimestamp: tokenObject.exp * 1000,
747
- };
748
- this.ssoToken = ssoToken;
749
- return ssoToken;
750
- }
751
- /**
752
- * Load and validate authentication configuration
753
- *
754
- * @param {AuthenticationConfiguration?} config - The authentication configuration. Use environment variables if not provided.
755
- *
756
- * @returns Authentication configuration
757
- */
758
- loadAndValidateConfig(config) {
759
- internalLogger.verbose("Validate authentication configuration");
760
- if (config.initiateLoginEndpoint && config.clientId) {
761
- return config;
762
- }
763
- const missingValues = [];
764
- if (!config.initiateLoginEndpoint) {
765
- missingValues.push("initiateLoginEndpoint");
766
- }
767
- if (!config.clientId) {
768
- missingValues.push("clientId");
769
- }
770
- const errorMsg = formatString(ErrorMessage.InvalidConfiguration, missingValues.join(", "), "undefined");
771
- internalLogger.error(errorMsg);
772
- throw new ErrorWithCode(errorMsg, ErrorCode.InvalidConfiguration);
773
- }
774
- setSessionStorage(sessionStorageValues) {
775
- try {
776
- const sessionStorageKeys = Object.keys(sessionStorageValues);
777
- sessionStorageKeys.forEach((key) => {
778
- sessionStorage.setItem(key, sessionStorageValues[key]);
779
- });
780
- }
781
- catch (error) {
782
- // Values in result.sessionStorage can not be set into session storage.
783
- // Throw error since this may block user.
784
- const errorMessage = `Failed to set values in session storage. Error: ${error.message}`;
785
- internalLogger.error(errorMessage);
786
- throw new ErrorWithCode(errorMessage, ErrorCode.InternalError);
787
- }
788
- }
239
+ /**
240
+ * Logger instance used internally
241
+ *
242
+ * @internal
243
+ */
244
+ const internalLogger = new InternalLogger();
245
+ /**
246
+ * Set custom logger. Use the output functions if it's set. Priority is higher than setLogFunction.
247
+ *
248
+ * @param {Logger} logger - custom logger. If it's undefined, custom logger will be cleared.
249
+ *
250
+ * @example
251
+ * ```typescript
252
+ * setLogger({
253
+ * verbose: console.debug,
254
+ * info: console.info,
255
+ * warn: console.warn,
256
+ * error: console.error,
257
+ * });
258
+ * ```
259
+ */
260
+ function setLogger(logger) {
261
+ internalLogger.customLogger = logger;
789
262
  }
790
-
791
- // Copyright (c) Microsoft Corporation.
792
- const defaultScope = "https://graph.microsoft.com/.default";
793
- // eslint-disable-next-line no-secrets/no-secrets
794
- /**
795
- * Microsoft Graph auth provider for Teams Framework
796
- * @deprecated Use `TokenCredentialAuthenticationProvider` from `@microsoft/microsoft-graph-client/authProviders/azureTokenCredentials` instead.
797
- */
798
- class MsGraphAuthProvider {
799
- constructor(credentialOrTeamsFx, scopes) {
800
- this.credentialOrTeamsFx = credentialOrTeamsFx;
801
- let scopesStr = defaultScope;
802
- if (scopes) {
803
- validateScopesType(scopes);
804
- scopesStr = typeof scopes === "string" ? scopes : scopes.join(" ");
805
- if (scopesStr === "") {
806
- scopesStr = defaultScope;
807
- }
808
- }
809
- internalLogger.info(`Create Microsoft Graph Authentication Provider with scopes: '${scopesStr}'`);
810
- this.scopes = scopesStr;
811
- }
812
- /**
813
- * Get access token for Microsoft Graph API requests.
814
- *
815
- * @throws {@link ErrorCode|InternalError} when get access token failed due to empty token or unknown other problems.
816
- * @throws {@link ErrorCode|TokenExpiredError} when SSO token has already expired.
817
- * @throws {@link ErrorCode|UiRequiredError} when need user consent to get access token.
818
- * @throws {@link ErrorCode|ServiceError} when failed to get access token from simple auth or AAD server.
819
- * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.
820
- *
821
- * @returns Access token from the credential.
822
- *
823
- */
824
- async getAccessToken() {
825
- internalLogger.info(`Get Graph Access token with scopes: '${this.scopes.toString()}'`);
826
- let accessToken;
827
- if (this.credentialOrTeamsFx.getCredential) {
828
- accessToken = await this.credentialOrTeamsFx
829
- .getCredential()
830
- .getToken(this.scopes);
831
- }
832
- else {
833
- accessToken = await this.credentialOrTeamsFx.getToken(this.scopes);
834
- }
835
- return new Promise((resolve, reject) => {
836
- if (accessToken) {
837
- resolve(accessToken.token);
838
- }
839
- else {
840
- const errorMsg = "Graph access token is undefined or empty";
841
- internalLogger.error(errorMsg);
842
- reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));
843
- }
844
- });
845
- }
263
+ /**
264
+ * Set custom log function. Use the function if it's set. Priority is lower than setLogger.
265
+ *
266
+ * @param {LogFunction} logFunction - custom log function. If it's undefined, custom log function will be cleared.
267
+ *
268
+ * @example
269
+ * ```typescript
270
+ * setLogFunction((level: LogLevel, message: string) => {
271
+ * if (level === LogLevel.Error) {
272
+ * console.log(message);
273
+ * }
274
+ * });
275
+ * ```
276
+ */
277
+ function setLogFunction(logFunction) {
278
+ internalLogger.customLogFunction = logFunction;
846
279
  }
847
280
 
848
- // Copyright (c) Microsoft Corporation.
849
- /**
850
- * Get Microsoft graph client.
851
- * @deprecated Use `TokenCredentialAuthenticationProvider` and `Client.initWithMiddleware` instead.
852
- * ```typescript
853
- * const authProvider = new TokenCredentialAuthenticationProvider(credential, { scopes: scope });
854
- * const graph = Client.initWithMiddleware({
855
- * authProvider: authProvider,
856
- * });
857
- * ```
858
- *
859
- * @example
860
- * Get Microsoft graph client by TokenCredential
861
- * ```typescript
862
- * // Sso token example (Azure Function)
863
- * const ssoToken = "YOUR_TOKEN_STRING";
864
- * const options = {"AAD_APP_ID", "AAD_APP_SECRET"};
865
- * const credential = new OnBehalfOfAADUserCredential(ssoToken, options);
866
- * const graphClient = await createMicrosoftGraphClient(credential);
867
- * const profile = await graphClient.api("/me").get();
868
- *
869
- * // TeamsBotSsoPrompt example (Bot Application)
870
- * const requiredScopes = ["User.Read"];
871
- * const config: Configuration = {
872
- * loginUrl: loginUrl,
873
- * clientId: clientId,
874
- * clientSecret: clientSecret,
875
- * tenantId: tenantId
876
- * };
877
- * const prompt = new TeamsBotSsoPrompt(dialogId, {
878
- * config: config
879
- * scopes: ["User.Read"],
880
- * });
881
- * this.addDialog(prompt);
882
- *
883
- * const oboCredential = new OnBehalfOfAADUserCredential(
884
- * getUserId(dialogContext),
885
- * {
886
- * clientId: "AAD_APP_ID",
887
- * clientSecret: "AAD_APP_SECRET"
888
- * });
889
- * try {
890
- * const graphClient = await createMicrosoftGraphClient(credential);
891
- * const profile = await graphClient.api("/me").get();
892
- * } catch (e) {
893
- * dialogContext.beginDialog(dialogId);
894
- * return Dialog.endOfTurn();
895
- * }
896
- * ```
897
- *
898
- * @param {TeamsFx} teamsfx - Used to provide configuration and auth.
899
- * @param scopes - The array of Microsoft Token scope of access. Default value is `[.default]`.
900
- *
901
- * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.
902
- *
903
- * @returns Graph client with specified scopes.
904
- */
905
- function createMicrosoftGraphClient(teamsfx, scopes) {
906
- internalLogger.info("Create Microsoft Graph Client");
907
- const authProvider = new MsGraphAuthProvider(teamsfx, scopes);
908
- const graphClient = Client.initWithMiddleware({
909
- authProvider,
910
- });
911
- return graphClient;
912
- }
913
- // eslint-disable-next-line no-secrets/no-secrets
914
- /**
915
- * Get Microsoft graph client.
916
- * @deprecated Use `TokenCredentialAuthenticationProvider` and `Client.initWithMiddleware` instead.
917
- * ```typescript
918
- * const authProvider = new TokenCredentialAuthenticationProvider(credential, { scopes: scope });
919
- * const graph = Client.initWithMiddleware({
920
- * authProvider: authProvider,
921
- * });
922
- * ```
923
- *
924
- * @example
925
- * Get Microsoft graph client by TokenCredential
926
- * ```typescript
927
- * // In browser: TeamsUserCredential
928
- * const authConfig: TeamsUserCredentialAuthConfig = {
929
- * clientId: "xxx",
930
- initiateLoginEndpoint: "https://xxx/auth-start.html",
931
- * };
932
-
933
- * const credential = new TeamsUserCredential(authConfig);
934
-
935
- * const scope = "User.Read";
936
- * await credential.login(scope);
937
-
938
- * const client = createMicrosoftGraphClientWithCredential(credential, scope);
939
-
940
- * // In node: OnBehalfOfUserCredential
941
- * const oboAuthConfig: OnBehalfOfCredentialAuthConfig = {
942
- * authorityHost: "xxx",
943
- * clientId: "xxx",
944
- * tenantId: "xxx",
945
- * clientSecret: "xxx",
946
- * };
281
+ // Copyright (c) Microsoft Corporation.
282
+ /**
283
+ * Parse jwt token payload
284
+ *
285
+ * @param token
286
+ *
287
+ * @returns Payload object
288
+ *
289
+ * @internal
290
+ */
291
+ function parseJwt(token) {
292
+ try {
293
+ const tokenObj = jwtDecode(token);
294
+ if (!tokenObj || !tokenObj.exp) {
295
+ throw new ErrorWithCode("Decoded token is null or exp claim does not exists.", ErrorCode.InternalError);
296
+ }
297
+ return tokenObj;
298
+ }
299
+ catch (err) {
300
+ const errorMsg = "Parse jwt token failed in node env with error: " + err.message;
301
+ internalLogger.error(errorMsg);
302
+ throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
303
+ }
304
+ }
305
+ /**
306
+ * @internal
307
+ */
308
+ function getUserInfoFromSsoToken(ssoToken) {
309
+ if (!ssoToken) {
310
+ const errorMsg = "SSO token is undefined.";
311
+ internalLogger.error(errorMsg);
312
+ throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);
313
+ }
314
+ const tokenObject = parseJwt(ssoToken);
315
+ const userInfo = {
316
+ displayName: tokenObject.name,
317
+ objectId: tokenObject.oid,
318
+ tenantId: tokenObject.tid,
319
+ preferredUserName: "",
320
+ };
321
+ if (tokenObject.ver === "2.0") {
322
+ userInfo.preferredUserName = tokenObject.preferred_username;
323
+ }
324
+ else if (tokenObject.ver === "1.0") {
325
+ userInfo.preferredUserName = tokenObject.upn;
326
+ }
327
+ return userInfo;
328
+ }
329
+ /**
330
+ * @internal
331
+ */
332
+ function getTenantIdAndLoginHintFromSsoToken(ssoToken) {
333
+ if (!ssoToken) {
334
+ const errorMsg = "SSO token is undefined.";
335
+ internalLogger.error(errorMsg);
336
+ throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);
337
+ }
338
+ const tokenObject = parseJwt(ssoToken);
339
+ const userInfo = {
340
+ tid: tokenObject.tid,
341
+ loginHint: tokenObject.ver === "2.0"
342
+ ? tokenObject.preferred_username
343
+ : tokenObject.upn,
344
+ };
345
+ return userInfo;
346
+ }
347
+ /**
348
+ * @internal
349
+ */
350
+ function parseAccessTokenFromAuthCodeTokenResponse(tokenResponse) {
351
+ try {
352
+ const tokenResponseObject = typeof tokenResponse == "string"
353
+ ? JSON.parse(tokenResponse)
354
+ : tokenResponse;
355
+ if (!tokenResponseObject || !tokenResponseObject.accessToken) {
356
+ const errorMsg = "Get empty access token from Auth Code token response.";
357
+ internalLogger.error(errorMsg);
358
+ throw new Error(errorMsg);
359
+ }
360
+ const token = tokenResponseObject.accessToken;
361
+ const tokenObject = parseJwt(token);
362
+ if (tokenObject.ver !== "1.0" && tokenObject.ver !== "2.0") {
363
+ const errorMsg = "SSO token is not valid with an unknown version: " + tokenObject.ver;
364
+ internalLogger.error(errorMsg);
365
+ throw new Error(errorMsg);
366
+ }
367
+ const accessToken = {
368
+ token: token,
369
+ expiresOnTimestamp: tokenObject.exp * 1000,
370
+ };
371
+ return accessToken;
372
+ }
373
+ catch (error) {
374
+ const errorMsg = "Parse access token failed from Auth Code token response in node env with error: " +
375
+ error.message;
376
+ internalLogger.error(errorMsg);
377
+ throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
378
+ }
379
+ }
380
+ /**
381
+ * Format string template with replacements
382
+ *
383
+ * ```typescript
384
+ * const template = "{0} and {1} are fruit. {0} is my favorite one."
385
+ * const formattedStr = formatString(template, "apple", "pear"); // formattedStr: "apple and pear are fruit. apple is my favorite one."
386
+ * ```
387
+ *
388
+ * @param str string template
389
+ * @param replacements replacement string array
390
+ * @returns Formatted string
391
+ *
392
+ * @internal
393
+ */
394
+ function formatString(str, ...replacements) {
395
+ const args = replacements;
396
+ return str.replace(/{(\d+)}/g, function (match, number) {
397
+ return typeof args[number] != "undefined" ? args[number] : match;
398
+ });
399
+ }
400
+ /**
401
+ * @internal
402
+ */
403
+ function validateScopesType(value) {
404
+ // string
405
+ if (typeof value === "string" || value instanceof String) {
406
+ return;
407
+ }
408
+ // empty array
409
+ if (Array.isArray(value) && value.length === 0) {
410
+ return;
411
+ }
412
+ // string array
413
+ if (Array.isArray(value) && value.length > 0 && value.every((item) => typeof item === "string")) {
414
+ return;
415
+ }
416
+ const errorMsg = "The type of scopes is not valid, it must be string or string array";
417
+ internalLogger.error(errorMsg);
418
+ throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);
419
+ }
947
420
 
948
- * const oboCredential = new OnBehalfOfUserCredential(ssoToken, oboAuthConfig);
949
- * const scope = "User.Read";
950
- * const client = createMicrosoftGraphClientWithCredential(oboCredential, scope);
421
+ // Copyright (c) Microsoft Corporation.
422
+ /**
423
+ * Represent Microsoft 365 tenant identity, and it is usually used when user is not involved.
424
+ *
425
+ * @remarks
426
+ * Only works in in server side.
427
+ */
428
+ class AppCredential {
429
+ /**
430
+ * Constructor of AppCredential.
431
+ *
432
+ * @remarks
433
+ * Only works in in server side.
434
+ */
435
+ constructor(authConfig) {
436
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "AppCredential"), ErrorCode.RuntimeNotSupported);
437
+ }
438
+ /**
439
+ * Get access token for credential.
440
+ *
441
+ * @remarks
442
+ * Only works in in server side.
443
+ */
444
+ getToken(scopes, options) {
445
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "AppCredential"), ErrorCode.RuntimeNotSupported));
446
+ }
447
+ }
951
448
 
952
- * // In node: AppCredential
953
- * const appAuthConfig: AppCredentialAuthConfig = {
954
- * authorityHost: "xxx",
955
- * clientId: "xxx",
956
- * tenantId: "xxx",
957
- * clientSecret: "xxx",
958
- * };
959
- * const appCredential = new AppCredential(appAuthConfig);
960
- * const scope = "User.Read";
961
- * const client = createMicrosoftGraphClientWithCredential(appCredential, scope);
962
- *
963
- * const profile = await client.api("/me").get();
964
- * ```
965
- *
966
- * @param {TokenCredential} credential - Used to provide configuration and auth.
967
- * @param scopes - The array of Microsoft Token scope of access. Default value is `[.default]`.
968
- *
969
- * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.
970
- *
971
- * @returns Graph client with specified scopes.
972
- */
973
- function createMicrosoftGraphClientWithCredential(credential, scopes) {
974
- internalLogger.info("Create Microsoft Graph Client");
975
- const authProvider = new MsGraphAuthProvider(credential, scopes);
976
- const graphClient = Client.initWithMiddleware({
977
- authProvider,
978
- });
979
- return graphClient;
449
+ // Copyright (c) Microsoft Corporation.
450
+ /**
451
+ * Represent on-behalf-of flow to get user identity, and it is designed to be used in Azure Function or Bot scenarios.
452
+ *
453
+ * @remarks
454
+ * Can only be used in server side.
455
+ */
456
+ class OnBehalfOfUserCredential {
457
+ /**
458
+ * Constructor of OnBehalfOfUserCredential
459
+ *
460
+ * @remarks
461
+ * Can Only works in in server side.
462
+ */
463
+ constructor(ssoToken, config) {
464
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "OnBehalfOfUserCredential"), ErrorCode.RuntimeNotSupported);
465
+ }
466
+ /**
467
+ * Get access token from credential.
468
+ * @remarks
469
+ * Can only be used in server side.
470
+ */
471
+ getToken(scopes, options) {
472
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "OnBehalfOfUserCredential"), ErrorCode.RuntimeNotSupported));
473
+ }
474
+ /**
475
+ * Get basic user info from SSO token.
476
+ * @remarks
477
+ * Can only be used in server side.
478
+ */
479
+ getUserInfo() {
480
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "OnBehalfOfUserCredential"), ErrorCode.RuntimeNotSupported));
481
+ }
980
482
  }
981
483
 
982
- // Copyright (c) Microsoft Corporation.
983
- /**
984
- * Generate connection configuration consumed by tedious.
985
- *
986
- * @deprecated we recommend you compose your own Tedious configuration for better flexibility.
987
- *
988
- * @remarks
989
- * Only works in in server side.
990
- */
991
- function getTediousConnectionConfig(teamsfx, databaseName) {
992
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "DefaultTediousConnectionConfiguration"), ErrorCode.RuntimeNotSupported));
484
+ // Copyright (c) Microsoft Corporation.
485
+ const tokenRefreshTimeSpanInMillisecond = 5 * 60 * 1000;
486
+ const loginPageWidth = 600;
487
+ const loginPageHeight = 535;
488
+ /**
489
+ * Represent Teams current user's identity, and it is used within Teams tab application.
490
+ *
491
+ * @remarks
492
+ * Can only be used within Teams.
493
+ */
494
+ class TeamsUserCredential {
495
+ // eslint-disable-next-line no-secrets/no-secrets
496
+ /**
497
+ * Constructor of TeamsUserCredential.
498
+ *
499
+ * @example
500
+ * ```typescript
501
+ * const config: TeamsUserCredentialAuthConfig = {
502
+ * initiateLoginEndpoint: "https://localhost:3000/auth-start.html",
503
+ * clientId: "xxx"
504
+ * }
505
+ * const credential = new TeamsUserCredential(config);
506
+ * ```
507
+ *
508
+ * @param {TeamsUserCredentialAuthConfig} authConfig - The authentication configuration.
509
+ *
510
+ * @throws {@link ErrorCode|InvalidConfiguration} when client id, initiate login endpoint or simple auth endpoint is not found in config.
511
+ * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.
512
+ */
513
+ constructor(authConfig) {
514
+ internalLogger.info("Create teams user credential");
515
+ this.config = this.loadAndValidateConfig(authConfig);
516
+ this.ssoToken = null;
517
+ this.initialized = false;
518
+ }
519
+ /**
520
+ * Popup login page to get user's access token with specific scopes.
521
+ *
522
+ * @remarks
523
+ * Only works in Teams client APP. User will be redirected to the authorization page to login and consent.
524
+ *
525
+ * @example
526
+ * ```typescript
527
+ * await credential.login(["https://graph.microsoft.com/User.Read"]); // single scope using string array
528
+ * await credential.login("https://graph.microsoft.com/User.Read"); // single scopes using string
529
+ * await credential.login(["https://graph.microsoft.com/User.Read", "Calendars.Read"]); // multiple scopes using string array
530
+ * await credential.login("https://graph.microsoft.com/User.Read Calendars.Read"); // multiple scopes using string
531
+ * ```
532
+ * @param scopes - The list of scopes for which the token will have access, before that, we will request user to consent.
533
+ * @param { string[] } resources - The optional list of resources for full trust Teams apps.
534
+ *
535
+ * @throws {@link ErrorCode|InternalError} when failed to login with unknown error.
536
+ * @throws {@link ErrorCode|ConsentFailed} when user canceled or failed to consent.
537
+ * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.
538
+ * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.
539
+ */
540
+ async login(scopes, resources) {
541
+ validateScopesType(scopes);
542
+ const scopesStr = typeof scopes === "string" ? scopes : scopes.join(" ");
543
+ internalLogger.info(`Popup login page to get user's access token with scopes: ${scopesStr}`);
544
+ if (!this.initialized) {
545
+ await this.init(resources);
546
+ }
547
+ await app.initialize();
548
+ let result;
549
+ try {
550
+ const params = {
551
+ url: `${this.config.initiateLoginEndpoint ? this.config.initiateLoginEndpoint : ""}?clientId=${this.config.clientId ? this.config.clientId : ""}&scope=${encodeURI(scopesStr)}&loginHint=${this.loginHint ? this.loginHint : ""}`,
552
+ width: loginPageWidth,
553
+ height: loginPageHeight,
554
+ };
555
+ result = await authentication.authenticate(params);
556
+ if (!result) {
557
+ const errorMsg = "Get empty authentication result from MSAL";
558
+ internalLogger.error(errorMsg);
559
+ throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
560
+ }
561
+ }
562
+ catch (err) {
563
+ const errorMsg = `Consent failed for the scope ${scopesStr} with error: ${err.message}`;
564
+ internalLogger.error(errorMsg);
565
+ throw new ErrorWithCode(errorMsg, ErrorCode.ConsentFailed);
566
+ }
567
+ let resultJson = {};
568
+ try {
569
+ resultJson = typeof result == "string" ? JSON.parse(result) : result;
570
+ }
571
+ catch (error) {
572
+ // If can not parse result as Json, will throw error.
573
+ const failedToParseResult = "Failed to parse response to Json.";
574
+ internalLogger.error(failedToParseResult);
575
+ throw new ErrorWithCode(failedToParseResult, ErrorCode.InvalidResponse);
576
+ }
577
+ // If code exists in result, user may using previous auth-start and auth-end page.
578
+ if (resultJson.code) {
579
+ const helpLink = "https://aka.ms/teamsfx-auth-code-flow";
580
+ const usingPreviousAuthPage = "Found auth code in response. Auth code is not support for current version of SDK. " +
581
+ `Please refer to the help link for how to fix the issue: ${helpLink}.`;
582
+ internalLogger.error(usingPreviousAuthPage);
583
+ throw new ErrorWithCode(usingPreviousAuthPage, ErrorCode.InvalidResponse);
584
+ }
585
+ // If sessionStorage exists in result, set the values in current session storage.
586
+ if (resultJson.sessionStorage) {
587
+ this.setSessionStorage(resultJson.sessionStorage);
588
+ }
589
+ }
590
+ /**
591
+ * Get access token from credential.
592
+ *
593
+ * Important: Access tokens are stored in sessionStorage, read more here: https://aka.ms/teamsfx-session-storage-notice
594
+ * Important: Full trust applications do not read the resource information from the webApplicationInfo section of the app
595
+ * manifest. Instead, this resource (along with any additional resources from which to request tokens) must be provided
596
+ * as a list of resources to the getToken() method through a GetTeamsUserTokenOptions object.
597
+ *
598
+ * @example
599
+ * ```typescript
600
+ * await credential.getToken([]) // Get SSO token using empty string array
601
+ * await credential.getToken("") // Get SSO token using empty string
602
+ * await credential.getToken([".default"]) // Get Graph access token with default scope using string array
603
+ * await credential.getToken(".default") // Get Graph access token with default scope using string
604
+ * await credential.getToken(["User.Read"]) // Get Graph access token for single scope using string array
605
+ * await credential.getToken("User.Read") // Get Graph access token for single scope using string
606
+ * await credential.getToken(["User.Read", "Application.Read.All"]) // Get Graph access token for multiple scopes using string array
607
+ * await credential.getToken("User.Read Application.Read.All") // Get Graph access token for multiple scopes using space-separated string
608
+ * await credential.getToken("https://graph.microsoft.com/User.Read") // Get Graph access token with full resource URI
609
+ * await credential.getToken(["https://outlook.office.com/Mail.Read"]) // Get Outlook access token
610
+ *
611
+ * const options: GetTeamsUserTokenOptions = { resources: ["https://domain.example.com"] }; // set up resources for full trust apps.
612
+ * await credential.getToken([], options) // Get sso token from teams client - only use this approach for full trust apps.
613
+ * ```
614
+ *
615
+ * @param {string | string[]} scopes - The list of scopes for which the token will have access.
616
+ * @param {GetTokenOptions} options - The options used to configure any requests this TokenCredential implementation might make.
617
+ *
618
+ * @throws {@link ErrorCode|InternalError} when failed to get access token with unknown error.
619
+ * @throws {@link ErrorCode|UiRequiredError} when need user consent to get access token.
620
+ * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.
621
+ * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.
622
+ *
623
+ * @returns User access token of defined scopes.
624
+ * If scopes is empty string or array, it returns SSO token.
625
+ * If scopes is non-empty, it returns access token for target scope.
626
+ * Throw error if get access token failed.
627
+ */
628
+ async getToken(scopes, options) {
629
+ validateScopesType(scopes);
630
+ const resources = options === null || options === void 0 ? void 0 : options.resources;
631
+ const ssoToken = await this.getSSOToken(resources);
632
+ const scopeStr = typeof scopes === "string" ? scopes : scopes.join(" ");
633
+ if (scopeStr === "") {
634
+ internalLogger.info("Get SSO token");
635
+ return ssoToken;
636
+ }
637
+ else {
638
+ internalLogger.info("Get access token with scopes: " + scopeStr);
639
+ if (!this.initialized) {
640
+ await this.init(resources);
641
+ }
642
+ let tokenResponse;
643
+ const scopesArray = typeof scopes === "string" ? scopes.split(" ") : scopes;
644
+ const domain = window.location.origin;
645
+ // First try to get Access Token from cache.
646
+ try {
647
+ const account = this.msalInstance.getAccountByUsername(this.loginHint);
648
+ const scopesRequestForAcquireTokenSilent = {
649
+ scopes: scopesArray,
650
+ account: account !== null && account !== void 0 ? account : undefined,
651
+ redirectUri: `${domain}/blank-auth-end.html`,
652
+ };
653
+ tokenResponse = await this.msalInstance.acquireTokenSilent(scopesRequestForAcquireTokenSilent);
654
+ }
655
+ catch (error) {
656
+ const acquireTokenSilentFailedMessage = `Failed to call acquireTokenSilent. Reason: ${error === null || error === void 0 ? void 0 : error.message}. `;
657
+ internalLogger.verbose(acquireTokenSilentFailedMessage);
658
+ }
659
+ if (!tokenResponse) {
660
+ // If fail to get Access Token from cache, try to get Access token by silent login.
661
+ try {
662
+ const scopesRequestForSsoSilent = {
663
+ scopes: scopesArray,
664
+ loginHint: this.loginHint,
665
+ redirectUri: `${domain}/blank-auth-end.html`,
666
+ };
667
+ tokenResponse = await this.msalInstance.ssoSilent(scopesRequestForSsoSilent);
668
+ }
669
+ catch (error) {
670
+ const ssoSilentFailedMessage = `Failed to call ssoSilent. Reason: ${error === null || error === void 0 ? void 0 : error.message}. `;
671
+ internalLogger.verbose(ssoSilentFailedMessage);
672
+ }
673
+ }
674
+ if (!tokenResponse) {
675
+ const errorMsg = `Failed to get access token cache silently, please login first: you need login first before get access token.`;
676
+ internalLogger.error(errorMsg);
677
+ throw new ErrorWithCode(errorMsg, ErrorCode.UiRequiredError);
678
+ }
679
+ const accessToken = parseAccessTokenFromAuthCodeTokenResponse(tokenResponse);
680
+ return accessToken;
681
+ }
682
+ }
683
+ /**
684
+ * Get basic user info from SSO token
685
+ *
686
+ * @param {string[]} resources - The optional list of resources for full trust Teams apps.
687
+ *
688
+ * @example
689
+ * ```typescript
690
+ * const currentUser = await credential.getUserInfo();
691
+ * ```
692
+ *
693
+ * @throws {@link ErrorCode|InternalError} when SSO token from Teams client is not valid.
694
+ * @throws {@link ErrorCode|InvalidParameter} when SSO token from Teams client is empty.
695
+ * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.
696
+ *
697
+ * @returns Basic user info with user displayName, objectId and preferredUserName.
698
+ */
699
+ async getUserInfo(resources) {
700
+ internalLogger.info("Get basic user info from SSO token");
701
+ const ssoToken = await this.getSSOToken(resources);
702
+ return getUserInfoFromSsoToken(ssoToken.token);
703
+ }
704
+ async init(resources) {
705
+ const ssoToken = await this.getSSOToken(resources);
706
+ const info = getTenantIdAndLoginHintFromSsoToken(ssoToken.token);
707
+ this.loginHint = info.loginHint;
708
+ this.tid = info.tid;
709
+ const msalConfig = {
710
+ auth: {
711
+ clientId: this.config.clientId,
712
+ authority: `https://login.microsoftonline.com/${this.tid}`,
713
+ },
714
+ cache: {
715
+ cacheLocation: "sessionStorage",
716
+ },
717
+ };
718
+ this.msalInstance = new PublicClientApplication(msalConfig);
719
+ await this.msalInstance.initialize();
720
+ this.initialized = true;
721
+ }
722
+ /**
723
+ * Get SSO token using teams SDK
724
+ * It will try to get SSO token from memory first, if SSO token doesn't exist or about to expired, then it will using teams SDK to get SSO token
725
+ *
726
+ * @param {string[]} resources - The optional list of resources for full trust Teams apps.
727
+ *
728
+ * @returns SSO token
729
+ */
730
+ async getSSOToken(resources) {
731
+ if (this.ssoToken) {
732
+ if (this.ssoToken.expiresOnTimestamp - Date.now() > tokenRefreshTimeSpanInMillisecond) {
733
+ internalLogger.verbose("Get SSO token from memory cache");
734
+ return this.ssoToken;
735
+ }
736
+ }
737
+ const params = { resources: resources !== null && resources !== void 0 ? resources : [] };
738
+ let token;
739
+ try {
740
+ await app.initialize();
741
+ }
742
+ catch (err) {
743
+ const errorMsg = "Initialize teams sdk failed due to not running inside Teams environment";
744
+ internalLogger.error(errorMsg);
745
+ throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
746
+ }
747
+ try {
748
+ token = await authentication.getAuthToken(params);
749
+ }
750
+ catch (err) {
751
+ const errorMsg = "Get SSO token failed with error: " + err.message;
752
+ internalLogger.error(errorMsg);
753
+ throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
754
+ }
755
+ if (!token) {
756
+ const errorMsg = "Get empty SSO token from Teams";
757
+ internalLogger.error(errorMsg);
758
+ throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
759
+ }
760
+ const tokenObject = parseJwt(token);
761
+ if (tokenObject.ver !== "1.0" && tokenObject.ver !== "2.0") {
762
+ const errorMsg = "SSO token is not valid with an unknown version: " + tokenObject.ver;
763
+ internalLogger.error(errorMsg);
764
+ throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
765
+ }
766
+ const ssoToken = {
767
+ token,
768
+ expiresOnTimestamp: tokenObject.exp * 1000,
769
+ };
770
+ this.ssoToken = ssoToken;
771
+ return ssoToken;
772
+ }
773
+ /**
774
+ * Load and validate authentication configuration
775
+ *
776
+ * @param {AuthenticationConfiguration?} config - The authentication configuration. Use environment variables if not provided.
777
+ *
778
+ * @returns Authentication configuration
779
+ */
780
+ loadAndValidateConfig(config) {
781
+ internalLogger.verbose("Validate authentication configuration");
782
+ if (config.initiateLoginEndpoint && config.clientId) {
783
+ return config;
784
+ }
785
+ const missingValues = [];
786
+ if (!config.initiateLoginEndpoint) {
787
+ missingValues.push("initiateLoginEndpoint");
788
+ }
789
+ if (!config.clientId) {
790
+ missingValues.push("clientId");
791
+ }
792
+ const errorMsg = formatString(ErrorMessage.InvalidConfiguration, missingValues.join(", "), "undefined");
793
+ internalLogger.error(errorMsg);
794
+ throw new ErrorWithCode(errorMsg, ErrorCode.InvalidConfiguration);
795
+ }
796
+ setSessionStorage(sessionStorageValues) {
797
+ try {
798
+ const sessionStorageKeys = Object.keys(sessionStorageValues);
799
+ sessionStorageKeys.forEach((key) => {
800
+ sessionStorage.setItem(key, sessionStorageValues[key]);
801
+ });
802
+ }
803
+ catch (error) {
804
+ // Values in result.sessionStorage can not be set into session storage.
805
+ // Throw error since this may block user.
806
+ const errorMessage = `Failed to set values in session storage. Error: ${error.message}`;
807
+ internalLogger.error(errorMessage);
808
+ throw new ErrorWithCode(errorMessage, ErrorCode.InternalError);
809
+ }
810
+ }
993
811
  }
994
812
 
995
- // Copyright (c) Microsoft Corporation.
996
- /**
997
- * Creates a new prompt that leverage Teams Single Sign On (SSO) support for bot to automatically sign in user and
998
- * help receive oauth token, asks the user to consent if needed.
999
- *
1000
- * @remarks
1001
- * The prompt will attempt to retrieve the users current token of the desired scopes and store it in
1002
- * the token store.
1003
- *
1004
- * User will be automatically signed in leveraging Teams support of Bot Single Sign On(SSO):
1005
- * https://docs.microsoft.com/en-us/microsoftteams/platform/bots/how-to/authentication/auth-aad-sso-bots
1006
- *
1007
- * @example
1008
- * When used with your bots `DialogSet` you can simply add a new instance of the prompt as a named
1009
- * dialog using `DialogSet.add()`. You can then start the prompt from a waterfall step using either
1010
- * `DialogContext.beginDialog()` or `DialogContext.prompt()`. The user will be prompted to sign in as
1011
- * needed and their access token will be passed as an argument to the callers next waterfall step:
1012
- *
1013
- * ```JavaScript
1014
- * const { ConversationState, MemoryStorage } = require('botbuilder');
1015
- * const { DialogSet, WaterfallDialog } = require('botbuilder-dialogs');
1016
- * const { TeamsBotSsoPrompt } = require('@microsoft/teamsfx');
1017
- *
1018
- * const convoState = new ConversationState(new MemoryStorage());
1019
- * const dialogState = convoState.createProperty('dialogState');
1020
- * const dialogs = new DialogSet(dialogState);
1021
- *
1022
- * dialogs.add(new TeamsBotSsoPrompt('TeamsBotSsoPrompt', {
1023
- * scopes: ["User.Read"],
1024
- * }));
1025
- *
1026
- * dialogs.add(new WaterfallDialog('taskNeedingLogin', [
1027
- * async (step) => {
1028
- * return await step.beginDialog('TeamsBotSsoPrompt');
1029
- * },
1030
- * async (step) => {
1031
- * const token = step.result;
1032
- * if (token) {
1033
- *
1034
- * // ... continue with task needing access token ...
1035
- *
1036
- * } else {
1037
- * await step.context.sendActivity(`Sorry... We couldn't log you in. Try again later.`);
1038
- * return await step.endDialog();
1039
- * }
1040
- * }
1041
- * ]));
1042
- * ```
1043
- */
1044
- class TeamsBotSsoPrompt {
1045
- /**
1046
- * Constructor of TeamsBotSsoPrompt.
1047
- *
1048
- * @param dialogId Unique ID of the dialog within its parent `DialogSet` or `ComponentDialog`.
1049
- * @param settings Settings used to configure the prompt.
1050
- *
1051
- * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.
1052
- * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
1053
- */
1054
- constructor(teamsfx, dialogId, settings) {
1055
- this.teamsfx = teamsfx;
1056
- this.settings = settings;
1057
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotSsoPrompt"), ErrorCode.RuntimeNotSupported);
1058
- }
1059
- /**
1060
- * Called when a prompt dialog is pushed onto the dialog stack and is being activated.
1061
- * @remarks
1062
- * If the task is successful, the result indicates whether the prompt is still
1063
- * active after the turn has been processed by the prompt.
1064
- *
1065
- * @param dc The DialogContext for the current turn of the conversation.
1066
- *
1067
- * @throws {@link ErrorCode|InvalidParameter} when timeout property in teams bot sso prompt settings is not number or is not positive.
1068
- * @throws {@link ErrorCode|ChannelNotSupported} when bot channel is not MS Teams.
1069
- * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
1070
- *
1071
- * @returns A `Promise` representing the asynchronous operation.
1072
- */
1073
- beginDialog(dc) {
1074
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotSsoPrompt"), ErrorCode.RuntimeNotSupported));
1075
- }
1076
- /**
1077
- * Called when a prompt dialog is the active dialog and the user replied with a new activity.
1078
- *
1079
- * @remarks
1080
- * If the task is successful, the result indicates whether the dialog is still
1081
- * active after the turn has been processed by the dialog.
1082
- * The prompt generally continues to receive the user's replies until it accepts the
1083
- * user's reply as valid input for the prompt.
1084
- *
1085
- * @param dc The DialogContext for the current turn of the conversation.
1086
- *
1087
- * @returns A `Promise` representing the asynchronous operation.
1088
- *
1089
- * @throws {@link ErrorCode|ChannelNotSupported} when bot channel is not MS Teams.
1090
- * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
1091
- */
1092
- continueDialog(dc) {
1093
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotSsoPrompt"), ErrorCode.RuntimeNotSupported));
1094
- }
813
+ // Copyright (c) Microsoft Corporation.
814
+ /**
815
+ * Creates a new prompt that leverage Teams Single Sign On (SSO) support for bot to automatically sign in user and
816
+ * help receive oauth token, asks the user to consent if needed.
817
+ *
818
+ * @remarks
819
+ * The prompt will attempt to retrieve the users current token of the desired scopes and store it in
820
+ * the token store.
821
+ *
822
+ * User will be automatically signed in leveraging Teams support of Bot Single Sign On(SSO):
823
+ * https://docs.microsoft.com/en-us/microsoftteams/platform/bots/how-to/authentication/auth-aad-sso-bots
824
+ *
825
+ * @example
826
+ * When used with your bots `DialogSet` you can simply add a new instance of the prompt as a named
827
+ * dialog using `DialogSet.add()`. You can then start the prompt from a waterfall step using either
828
+ * `DialogContext.beginDialog()` or `DialogContext.prompt()`. The user will be prompted to sign in as
829
+ * needed and their access token will be passed as an argument to the callers next waterfall step:
830
+ *
831
+ * ```JavaScript
832
+ * const { ConversationState, MemoryStorage } = require('botbuilder');
833
+ * const { DialogSet, WaterfallDialog } = require('botbuilder-dialogs');
834
+ * const { TeamsBotSsoPrompt } = require('@microsoft/teamsfx');
835
+ *
836
+ * const convoState = new ConversationState(new MemoryStorage());
837
+ * const dialogState = convoState.createProperty('dialogState');
838
+ * const dialogs = new DialogSet(dialogState);
839
+ *
840
+ * dialogs.add(new TeamsBotSsoPrompt('TeamsBotSsoPrompt', {
841
+ * scopes: ["User.Read"],
842
+ * }));
843
+ *
844
+ * dialogs.add(new WaterfallDialog('taskNeedingLogin', [
845
+ * async (step) => {
846
+ * return await step.beginDialog('TeamsBotSsoPrompt');
847
+ * },
848
+ * async (step) => {
849
+ * const token = step.result;
850
+ * if (token) {
851
+ *
852
+ * // ... continue with task needing access token ...
853
+ *
854
+ * } else {
855
+ * await step.context.sendActivity(`Sorry... We couldn't log you in. Try again later.`);
856
+ * return await step.endDialog();
857
+ * }
858
+ * }
859
+ * ]));
860
+ * ```
861
+ */
862
+ class TeamsBotSsoPrompt {
863
+ /**
864
+ * Constructor of TeamsBotSsoPrompt.
865
+ *
866
+ * @param dialogId Unique ID of the dialog within its parent `DialogSet` or `ComponentDialog`.
867
+ * @param settings Settings used to configure the prompt.
868
+ *
869
+ * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.
870
+ * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
871
+ */
872
+ constructor(authConfig, initiateLoginEndpoint, dialogId, settings) {
873
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotSsoPrompt"), ErrorCode.RuntimeNotSupported);
874
+ }
875
+ /**
876
+ * Called when a prompt dialog is pushed onto the dialog stack and is being activated.
877
+ * @remarks
878
+ * If the task is successful, the result indicates whether the prompt is still
879
+ * active after the turn has been processed by the prompt.
880
+ *
881
+ * @param dc The DialogContext for the current turn of the conversation.
882
+ *
883
+ * @throws {@link ErrorCode|InvalidParameter} when timeout property in teams bot sso prompt settings is not number or is not positive.
884
+ * @throws {@link ErrorCode|ChannelNotSupported} when bot channel is not MS Teams.
885
+ * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
886
+ *
887
+ * @returns A `Promise` representing the asynchronous operation.
888
+ */
889
+ beginDialog(dc) {
890
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotSsoPrompt"), ErrorCode.RuntimeNotSupported));
891
+ }
892
+ /**
893
+ * Called when a prompt dialog is the active dialog and the user replied with a new activity.
894
+ *
895
+ * @remarks
896
+ * If the task is successful, the result indicates whether the dialog is still
897
+ * active after the turn has been processed by the dialog.
898
+ * The prompt generally continues to receive the user's replies until it accepts the
899
+ * user's reply as valid input for the prompt.
900
+ *
901
+ * @param dc The DialogContext for the current turn of the conversation.
902
+ *
903
+ * @returns A `Promise` representing the asynchronous operation.
904
+ *
905
+ * @throws {@link ErrorCode|ChannelNotSupported} when bot channel is not MS Teams.
906
+ * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
907
+ */
908
+ continueDialog(dc) {
909
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotSsoPrompt"), ErrorCode.RuntimeNotSupported));
910
+ }
1095
911
  }
1096
912
 
1097
- // Copyright (c) Microsoft Corporation.
1098
- /**
1099
- * Initializes new Axios instance with specific auth provider
1100
- *
1101
- * @param apiEndpoint - Base url of the API
1102
- * @param authProvider - Auth provider that injects authentication info to each request
1103
- * @returns axios instance configured with specfic auth provider
1104
- *
1105
- * @example
1106
- * ```typescript
1107
- * const client = createApiClient("https://my-api-endpoint-base-url", new BasicAuthProvider("xxx","xxx"));
1108
- * ```
1109
- */
1110
- function createApiClient(apiEndpoint, authProvider) {
1111
- // Add a request interceptor
1112
- const instance = axios.create({
1113
- baseURL: apiEndpoint,
1114
- });
1115
- instance.interceptors.request.use(async function (config) {
1116
- return (await authProvider.AddAuthenticationInfo(config));
1117
- });
1118
- return instance;
913
+ // Copyright (c) Microsoft Corporation.
914
+ /**
915
+ * Initializes new Axios instance with specific auth provider
916
+ *
917
+ * @param apiEndpoint - Base url of the API
918
+ * @param authProvider - Auth provider that injects authentication info to each request
919
+ * @returns axios instance configured with specfic auth provider
920
+ *
921
+ * @example
922
+ * ```typescript
923
+ * const client = createApiClient("https://my-api-endpoint-base-url", new BasicAuthProvider("xxx","xxx"));
924
+ * ```
925
+ */
926
+ function createApiClient(apiEndpoint, authProvider) {
927
+ // Add a request interceptor
928
+ const instance = axios.create({
929
+ baseURL: apiEndpoint,
930
+ });
931
+ instance.interceptors.request.use(async function (config) {
932
+ return (await authProvider.AddAuthenticationInfo(config));
933
+ });
934
+ return instance;
1119
935
  }
1120
936
 
1121
- // Copyright (c) Microsoft Corporation.
1122
- /**
1123
- * Provider that handles Bearer Token authentication
1124
- */
1125
- class BearerTokenAuthProvider {
1126
- /**
1127
- * @param { () => Promise<string> } getToken - Function that returns the content of bearer token used in http request
1128
- */
1129
- constructor(getToken) {
1130
- this.getToken = getToken;
1131
- }
1132
- /**
1133
- * Adds authentication info to http requests
1134
- *
1135
- * @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.
1136
- * Refer https://axios-http.com/docs/req_config for detailed document.
1137
- *
1138
- * @returns Updated axios request config.
1139
- *
1140
- * @throws {@link ErrorCode|AuthorizationInfoAlreadyExists} - when Authorization header already exists in request configuration.
1141
- */
1142
- async AddAuthenticationInfo(config) {
1143
- const token = await this.getToken();
1144
- if (!config.headers) {
1145
- config.headers = {};
1146
- }
1147
- if (config.headers["Authorization"]) {
1148
- throw new ErrorWithCode(ErrorMessage.AuthorizationHeaderAlreadyExists, ErrorCode.AuthorizationInfoAlreadyExists);
1149
- }
1150
- config.headers["Authorization"] = `Bearer ${token}`;
1151
- return config;
1152
- }
937
+ // Copyright (c) Microsoft Corporation.
938
+ /**
939
+ * Provider that handles Bearer Token authentication
940
+ */
941
+ class BearerTokenAuthProvider {
942
+ /**
943
+ * @param { () => Promise<string> } getToken - Function that returns the content of bearer token used in http request
944
+ */
945
+ constructor(getToken) {
946
+ this.getToken = getToken;
947
+ }
948
+ /**
949
+ * Adds authentication info to http requests
950
+ *
951
+ * @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.
952
+ * Refer https://axios-http.com/docs/req_config for detailed document.
953
+ *
954
+ * @returns Updated axios request config.
955
+ *
956
+ * @throws {@link ErrorCode|AuthorizationInfoAlreadyExists} - when Authorization header already exists in request configuration.
957
+ */
958
+ async AddAuthenticationInfo(config) {
959
+ const token = await this.getToken();
960
+ if (!config.headers) {
961
+ config.headers = {};
962
+ }
963
+ if (config.headers["Authorization"]) {
964
+ throw new ErrorWithCode(ErrorMessage.AuthorizationHeaderAlreadyExists, ErrorCode.AuthorizationInfoAlreadyExists);
965
+ }
966
+ config.headers["Authorization"] = `Bearer ${token}`;
967
+ return config;
968
+ }
1153
969
  }
1154
970
 
1155
- // Copyright (c) Microsoft Corporation.
1156
- /**
1157
- * Provider that handles Basic authentication
1158
- */
1159
- class BasicAuthProvider {
1160
- /**
1161
- *
1162
- * @param { string } userName - Username used in basic auth
1163
- * @param { string } password - Password used in basic auth
1164
- *
1165
- * @throws {@link ErrorCode|InvalidParameter} - when username or password is empty.
1166
- * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
1167
- */
1168
- constructor(userName, password) {
1169
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "BasicAuthProvider"), ErrorCode.RuntimeNotSupported);
1170
- }
1171
- /**
1172
- * Adds authentication info to http requests
1173
- *
1174
- * @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.
1175
- * Refer https://axios-http.com/docs/req_config for detailed document.
1176
- *
1177
- * @returns Updated axios request config.
1178
- *
1179
- * @throws {@link ErrorCode|AuthorizationInfoAlreadyExists} - when Authorization header or auth property already exists in request configuration.
1180
- * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
1181
- */
1182
- AddAuthenticationInfo(config) {
1183
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "BasicAuthProvider"), ErrorCode.RuntimeNotSupported));
1184
- }
971
+ // Copyright (c) Microsoft Corporation.
972
+ /**
973
+ * Provider that handles Basic authentication
974
+ */
975
+ class BasicAuthProvider {
976
+ /**
977
+ *
978
+ * @param { string } userName - Username used in basic auth
979
+ * @param { string } password - Password used in basic auth
980
+ *
981
+ * @throws {@link ErrorCode|InvalidParameter} - when username or password is empty.
982
+ * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
983
+ */
984
+ constructor(userName, password) {
985
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "BasicAuthProvider"), ErrorCode.RuntimeNotSupported);
986
+ }
987
+ /**
988
+ * Adds authentication info to http requests
989
+ *
990
+ * @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.
991
+ * Refer https://axios-http.com/docs/req_config for detailed document.
992
+ *
993
+ * @returns Updated axios request config.
994
+ *
995
+ * @throws {@link ErrorCode|AuthorizationInfoAlreadyExists} - when Authorization header or auth property already exists in request configuration.
996
+ * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
997
+ */
998
+ AddAuthenticationInfo(config) {
999
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "BasicAuthProvider"), ErrorCode.RuntimeNotSupported));
1000
+ }
1185
1001
  }
1186
1002
 
1187
- // Copyright (c) Microsoft Corporation.
1188
- /**
1189
- * Provider that handles API Key authentication
1190
- */
1191
- class ApiKeyProvider {
1192
- /**
1193
- *
1194
- * @param { string } keyName - The name of request header or query parameter that specifies API Key
1195
- * @param { string } keyValue - The value of API Key
1196
- * @param { ApiKeyLocation } keyLocation - The location of API Key: request header or query parameter.
1197
- *
1198
- * @throws {@link ErrorCode|InvalidParameter} - when key name or key value is empty.
1199
- * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
1200
- */
1201
- constructor(keyName, keyValue, keyLocation) {
1202
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "ApiKeyProvider"), ErrorCode.RuntimeNotSupported);
1203
- }
1204
- /**
1205
- * Adds authentication info to http requests
1206
- *
1207
- * @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.
1208
- * Refer https://axios-http.com/docs/req_config for detailed document.
1209
- *
1210
- * @returns Updated axios request config.
1211
- *
1212
- * @throws {@link ErrorCode|AuthorizationInfoAlreadyExists} - when API key already exists in request header or url query parameter.
1213
- * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
1214
- */
1215
- AddAuthenticationInfo(config) {
1216
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "ApiKeyProvider"), ErrorCode.RuntimeNotSupported));
1217
- }
1218
- }
1219
- /**
1220
- * Define available location for API Key location
1221
- */
1222
- var ApiKeyLocation;
1223
- (function (ApiKeyLocation) {
1224
- /**
1225
- * The API Key is placed in request header
1226
- */
1227
- ApiKeyLocation[ApiKeyLocation["Header"] = 0] = "Header";
1228
- /**
1229
- * The API Key is placed in query parameter
1230
- */
1231
- ApiKeyLocation[ApiKeyLocation["QueryParams"] = 1] = "QueryParams";
1003
+ // Copyright (c) Microsoft Corporation.
1004
+ /**
1005
+ * Provider that handles API Key authentication
1006
+ */
1007
+ class ApiKeyProvider {
1008
+ /**
1009
+ *
1010
+ * @param { string } keyName - The name of request header or query parameter that specifies API Key
1011
+ * @param { string } keyValue - The value of API Key
1012
+ * @param { ApiKeyLocation } keyLocation - The location of API Key: request header or query parameter.
1013
+ *
1014
+ * @throws {@link ErrorCode|InvalidParameter} - when key name or key value is empty.
1015
+ * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
1016
+ */
1017
+ constructor(keyName, keyValue, keyLocation) {
1018
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "ApiKeyProvider"), ErrorCode.RuntimeNotSupported);
1019
+ }
1020
+ /**
1021
+ * Adds authentication info to http requests
1022
+ *
1023
+ * @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.
1024
+ * Refer https://axios-http.com/docs/req_config for detailed document.
1025
+ *
1026
+ * @returns Updated axios request config.
1027
+ *
1028
+ * @throws {@link ErrorCode|AuthorizationInfoAlreadyExists} - when API key already exists in request header or url query parameter.
1029
+ * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
1030
+ */
1031
+ AddAuthenticationInfo(config) {
1032
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "ApiKeyProvider"), ErrorCode.RuntimeNotSupported));
1033
+ }
1034
+ }
1035
+ /**
1036
+ * Define available location for API Key location
1037
+ */
1038
+ var ApiKeyLocation;
1039
+ (function (ApiKeyLocation) {
1040
+ /**
1041
+ * The API Key is placed in request header
1042
+ */
1043
+ ApiKeyLocation[ApiKeyLocation["Header"] = 0] = "Header";
1044
+ /**
1045
+ * The API Key is placed in query parameter
1046
+ */
1047
+ ApiKeyLocation[ApiKeyLocation["QueryParams"] = 1] = "QueryParams";
1232
1048
  })(ApiKeyLocation || (ApiKeyLocation = {}));
1233
1049
 
1234
- // Copyright (c) Microsoft Corporation.
1235
- /**
1236
- * Provider that handles Certificate authentication
1237
- */
1238
- class CertificateAuthProvider {
1239
- /**
1240
- *
1241
- * @param { SecureContextOptions } certOption - information about the cert used in http requests
1242
- */
1243
- constructor(certOption) {
1244
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CertificateAuthProvider"), ErrorCode.RuntimeNotSupported);
1245
- }
1246
- /**
1247
- * Adds authentication info to http requests.
1248
- *
1249
- * @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.
1250
- * Refer https://axios-http.com/docs/req_config for detailed document.
1251
- *
1252
- * @returns Updated axios request config.
1253
- *
1254
- * @throws {@link ErrorCode|InvalidParameter} - when custom httpsAgent in the request has duplicate properties with certOption provided in constructor.
1255
- * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
1256
- */
1257
- AddAuthenticationInfo(config) {
1258
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CertificateAuthProvider"), ErrorCode.RuntimeNotSupported));
1259
- }
1260
- }
1261
- /**
1262
- * Helper to create SecureContextOptions from PEM format cert
1263
- *
1264
- * @param { string | Buffer } cert - The cert chain in PEM format
1265
- * @param { string | Buffer } key - The private key for the cert chain
1266
- * @param { {passphrase?: string; ca?: string | Buffer} } options - Optional settings when create the cert options.
1267
- *
1268
- * @returns Instance of SecureContextOptions
1269
- *
1270
- * @throws {@link ErrorCode|InvalidParameter} - when any parameter is empty
1271
- * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
1272
- *
1273
- */
1274
- function createPemCertOption(cert, key, options) {
1275
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "createPemCertOption"), ErrorCode.RuntimeNotSupported);
1276
- }
1277
- /**
1278
- * Helper to create SecureContextOptions from PFX format cert
1279
- *
1280
- * @param { string | Buffer } pfx - The content of .pfx file
1281
- * @param { {passphrase?: string} } options - Optional settings when create the cert options.
1282
- *
1283
- * @returns Instance of SecureContextOptions
1284
- *
1285
- * @throws {@link ErrorCode|InvalidParameter} - when any parameter is empty
1286
- * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
1287
- *
1288
- */
1289
- function createPfxCertOption(pfx, options) {
1290
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "createPfxCertOption"), ErrorCode.RuntimeNotSupported);
1050
+ // Copyright (c) Microsoft Corporation.
1051
+ /**
1052
+ * Provider that handles Certificate authentication
1053
+ */
1054
+ class CertificateAuthProvider {
1055
+ /**
1056
+ *
1057
+ * @param { SecureContextOptions } certOption - information about the cert used in http requests
1058
+ */
1059
+ constructor(certOption) {
1060
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CertificateAuthProvider"), ErrorCode.RuntimeNotSupported);
1061
+ }
1062
+ /**
1063
+ * Adds authentication info to http requests.
1064
+ *
1065
+ * @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.
1066
+ * Refer https://axios-http.com/docs/req_config for detailed document.
1067
+ *
1068
+ * @returns Updated axios request config.
1069
+ *
1070
+ * @throws {@link ErrorCode|InvalidParameter} - when custom httpsAgent in the request has duplicate properties with certOption provided in constructor.
1071
+ * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
1072
+ */
1073
+ AddAuthenticationInfo(config) {
1074
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CertificateAuthProvider"), ErrorCode.RuntimeNotSupported));
1075
+ }
1291
1076
  }
1292
-
1293
- // Copyright (c) Microsoft Corporation.
1294
- // Licensed under the MIT license.
1295
- /**
1296
- * Identity type to use in authentication.
1297
- */
1298
- var IdentityType;
1299
- (function (IdentityType) {
1300
- /**
1301
- * Represents the current user of Teams.
1302
- */
1303
- IdentityType["User"] = "User";
1304
- /**
1305
- * Represents the application itself.
1306
- */
1307
- IdentityType["App"] = "Application";
1308
- })(IdentityType || (IdentityType = {}));
1309
-
1310
- // Copyright (c) Microsoft Corporation.
1311
- /**
1312
- * A class providing credential and configuration.
1313
- * @deprecated Please use {@link TeamsUserCredential}
1314
- * in browser environment and {@link OnBehalfOfUserCredential} or {@link AppCredential} in NodeJS.
1315
- */
1316
- class TeamsFx {
1317
- constructor(identityType, customConfig) {
1318
- this.identityType = identityType !== null && identityType !== void 0 ? identityType : IdentityType.User;
1319
- if (this.identityType !== IdentityType.User) {
1320
- const errorMsg = formatString(ErrorMessage.IdentityTypeNotSupported, this.identityType.toString(), "TeamsFx");
1321
- internalLogger.error(errorMsg);
1322
- throw new ErrorWithCode(errorMsg, ErrorCode.IdentityTypeNotSupported);
1323
- }
1324
- this.configuration = new Map();
1325
- this.loadFromEnv();
1326
- if (customConfig) {
1327
- const myConfig = Object.assign({}, customConfig);
1328
- for (const key of Object.keys(myConfig)) {
1329
- const value = myConfig[key];
1330
- if (value) {
1331
- this.configuration.set(key, value);
1332
- }
1333
- }
1334
- }
1335
- if (this.configuration.size === 0) {
1336
- internalLogger.warn("No configuration is loaded, please pass required configs to TeamsFx constructor");
1337
- }
1338
- }
1339
- loadFromEnv() {
1340
- if (window && window.__env__) {
1341
- // testing purpose
1342
- const env = window.__env__;
1343
- this.configuration.set("authorityHost", env.REACT_APP_AUTHORITY_HOST);
1344
- this.configuration.set("tenantId", env.REACT_APP_TENANT_ID);
1345
- this.configuration.set("clientId", env.REACT_APP_CLIENT_ID);
1346
- this.configuration.set("initiateLoginEndpoint", env.REACT_APP_START_LOGIN_PAGE_URL);
1347
- this.configuration.set("applicationIdUri", env.M365_APPLICATION_ID_URI);
1348
- this.configuration.set("apiEndpoint", env.REACT_APP_FUNC_ENDPOINT);
1349
- this.configuration.set("apiName", env.REACT_APP_FUNC_NAME);
1350
- }
1351
- else {
1352
- // TODO: support common environment variable name
1353
- try {
1354
- this.configuration.set("authorityHost", process.env.REACT_APP_AUTHORITY_HOST);
1355
- this.configuration.set("tenantId", process.env.REACT_APP_TENANT_ID);
1356
- this.configuration.set("clientId", process.env.REACT_APP_CLIENT_ID);
1357
- this.configuration.set("initiateLoginEndpoint", process.env.REACT_APP_START_LOGIN_PAGE_URL);
1358
- this.configuration.set("applicationIdUri", process.env.M365_APPLICATION_ID_URI);
1359
- this.configuration.set("apiEndpoint", process.env.REACT_APP_FUNC_ENDPOINT);
1360
- this.configuration.set("apiName", process.env.REACT_APP_FUNC_NAME);
1361
- }
1362
- catch (_) {
1363
- internalLogger.warn("Cannot read process.env, please use webpack if you want to use environment variables.");
1364
- return;
1365
- }
1366
- }
1367
- }
1368
- getIdentityType() {
1369
- return this.identityType;
1370
- }
1371
- getCredential() {
1372
- if (!this.teamsUserCredential) {
1373
- this.teamsUserCredential = new TeamsUserCredential(Object.fromEntries(this.configuration));
1374
- }
1375
- return this.teamsUserCredential;
1376
- }
1377
- async getUserInfo(resources) {
1378
- return await this.getCredential().getUserInfo(resources);
1379
- }
1380
- async login(scopes, resources) {
1381
- await this.getCredential().login(scopes, resources);
1382
- }
1383
- setSsoToken(ssoToken) {
1384
- return this;
1385
- }
1386
- getConfig(key) {
1387
- const value = this.configuration.get(key);
1388
- if (!value) {
1389
- throw new Error();
1390
- }
1391
- return value;
1392
- }
1393
- hasConfig(key) {
1394
- const value = this.configuration.get(key);
1395
- return !!value;
1396
- }
1397
- getConfigs() {
1398
- const config = {};
1399
- for (const key of this.configuration.keys()) {
1400
- const value = this.configuration.get(key);
1401
- if (value) {
1402
- config[key] = value;
1403
- }
1404
- }
1405
- return config;
1406
- }
1077
+ /**
1078
+ * Helper to create SecureContextOptions from PEM format cert
1079
+ *
1080
+ * @param { string | Buffer } cert - The cert chain in PEM format
1081
+ * @param { string | Buffer } key - The private key for the cert chain
1082
+ * @param { {passphrase?: string; ca?: string | Buffer} } options - Optional settings when create the cert options.
1083
+ *
1084
+ * @returns Instance of SecureContextOptions
1085
+ *
1086
+ * @throws {@link ErrorCode|InvalidParameter} - when any parameter is empty
1087
+ * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
1088
+ *
1089
+ */
1090
+ function createPemCertOption(cert, key, options) {
1091
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "createPemCertOption"), ErrorCode.RuntimeNotSupported);
1092
+ }
1093
+ /**
1094
+ * Helper to create SecureContextOptions from PFX format cert
1095
+ *
1096
+ * @param { string | Buffer } pfx - The content of .pfx file
1097
+ * @param { {passphrase?: string} } options - Optional settings when create the cert options.
1098
+ *
1099
+ * @returns Instance of SecureContextOptions
1100
+ *
1101
+ * @throws {@link ErrorCode|InvalidParameter} - when any parameter is empty
1102
+ * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
1103
+ *
1104
+ */
1105
+ function createPfxCertOption(pfx, options) {
1106
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "createPfxCertOption"), ErrorCode.RuntimeNotSupported);
1407
1107
  }
1408
1108
 
1409
- // Copyright (c) Microsoft Corporation.
1410
- // Licensed under the MIT license.
1411
- /**
1412
- * The target type where the notification will be sent to.
1413
- *
1414
- * @remarks
1415
- * - "Channel" means to a team channel. (By default, notification to a team will be sent to its "General" channel.)
1416
- * - "Group" means to a group chat.
1417
- * - "Person" means to a personal chat.
1418
- */
1419
- var NotificationTargetType;
1420
- (function (NotificationTargetType) {
1421
- /**
1422
- * The notification will be sent to a team channel.
1423
- * (By default, notification to a team will be sent to its "General" channel.)
1424
- */
1425
- NotificationTargetType["Channel"] = "Channel";
1426
- /**
1427
- * The notification will be sent to a group chat.
1428
- */
1429
- NotificationTargetType["Group"] = "Group";
1430
- /**
1431
- * The notification will be sent to a personal chat.
1432
- */
1433
- NotificationTargetType["Person"] = "Person";
1434
- })(NotificationTargetType || (NotificationTargetType = {}));
1435
- /**
1436
- * Options used to control how the response card will be sent to users.
1437
- */
1438
- var AdaptiveCardResponse;
1439
- (function (AdaptiveCardResponse) {
1440
- /**
1441
- * The response card will be replaced the current one for the interactor who trigger the action.
1442
- */
1443
- AdaptiveCardResponse[AdaptiveCardResponse["ReplaceForInteractor"] = 0] = "ReplaceForInteractor";
1444
- /**
1445
- * The response card will be replaced the current one for all users in the chat.
1446
- */
1447
- AdaptiveCardResponse[AdaptiveCardResponse["ReplaceForAll"] = 1] = "ReplaceForAll";
1448
- /**
1449
- * The response card will be sent as a new message for all users in the chat.
1450
- */
1451
- AdaptiveCardResponse[AdaptiveCardResponse["NewForAll"] = 2] = "NewForAll";
1452
- })(AdaptiveCardResponse || (AdaptiveCardResponse = {}));
1453
- /**
1454
- * Status code for an `application/vnd.microsoft.error` invoke response.
1455
- */
1456
- var InvokeResponseErrorCode;
1457
- (function (InvokeResponseErrorCode) {
1458
- /**
1459
- * Invalid request.
1460
- */
1461
- InvokeResponseErrorCode[InvokeResponseErrorCode["BadRequest"] = 400] = "BadRequest";
1462
- /**
1463
- * Internal server error.
1464
- */
1465
- InvokeResponseErrorCode[InvokeResponseErrorCode["InternalServerError"] = 500] = "InternalServerError";
1109
+ // Copyright (c) Microsoft Corporation.
1110
+ // Licensed under the MIT license.
1111
+ /**
1112
+ * The target type where the notification will be sent to.
1113
+ *
1114
+ * @remarks
1115
+ * - "Channel" means to a team channel. (By default, notification to a team will be sent to its "General" channel.)
1116
+ * - "Group" means to a group chat.
1117
+ * - "Person" means to a personal chat.
1118
+ */
1119
+ var NotificationTargetType;
1120
+ (function (NotificationTargetType) {
1121
+ /**
1122
+ * The notification will be sent to a team channel.
1123
+ * (By default, notification to a team will be sent to its "General" channel.)
1124
+ */
1125
+ NotificationTargetType["Channel"] = "Channel";
1126
+ /**
1127
+ * The notification will be sent to a group chat.
1128
+ */
1129
+ NotificationTargetType["Group"] = "Group";
1130
+ /**
1131
+ * The notification will be sent to a personal chat.
1132
+ */
1133
+ NotificationTargetType["Person"] = "Person";
1134
+ })(NotificationTargetType || (NotificationTargetType = {}));
1135
+ /**
1136
+ * Options used to control how the response card will be sent to users.
1137
+ */
1138
+ var AdaptiveCardResponse;
1139
+ (function (AdaptiveCardResponse) {
1140
+ /**
1141
+ * The response card will be replaced the current one for the interactor who trigger the action.
1142
+ */
1143
+ AdaptiveCardResponse[AdaptiveCardResponse["ReplaceForInteractor"] = 0] = "ReplaceForInteractor";
1144
+ /**
1145
+ * The response card will be replaced the current one for all users in the chat.
1146
+ */
1147
+ AdaptiveCardResponse[AdaptiveCardResponse["ReplaceForAll"] = 1] = "ReplaceForAll";
1148
+ /**
1149
+ * The response card will be sent as a new message for all users in the chat.
1150
+ */
1151
+ AdaptiveCardResponse[AdaptiveCardResponse["NewForAll"] = 2] = "NewForAll";
1152
+ })(AdaptiveCardResponse || (AdaptiveCardResponse = {}));
1153
+ /**
1154
+ * Status code for an `application/vnd.microsoft.error` invoke response.
1155
+ */
1156
+ var InvokeResponseErrorCode;
1157
+ (function (InvokeResponseErrorCode) {
1158
+ /**
1159
+ * Invalid request.
1160
+ */
1161
+ InvokeResponseErrorCode[InvokeResponseErrorCode["BadRequest"] = 400] = "BadRequest";
1162
+ /**
1163
+ * Internal server error.
1164
+ */
1165
+ InvokeResponseErrorCode[InvokeResponseErrorCode["InternalServerError"] = 500] = "InternalServerError";
1466
1166
  })(InvokeResponseErrorCode || (InvokeResponseErrorCode = {}));
1467
1167
 
1468
- // Copyright (c) Microsoft Corporation.
1469
- /**
1470
- * Provide utilities for bot conversation, including:
1471
- * - handle command and response.
1472
- * - send notification to varies targets (e.g., member, group, channel).
1473
- *
1474
- * @remarks
1475
- * Only work on server side.
1476
- */
1477
- /**
1478
- * @deprecated Use `BotBuilderCloudAdapter.ConversationBot` instead.
1479
- */
1480
- class ConversationBot$1 {
1481
- /**
1482
- * Creates new instance of the `ConversationBot`.
1483
- *
1484
- * @param options - initialize options
1485
- *
1486
- * @remarks
1487
- * Only work on server side.
1488
- */
1489
- constructor(options) {
1490
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "ConversationBot"), ErrorCode.RuntimeNotSupported);
1491
- }
1492
- /**
1493
- * The request handler to integrate with web request.
1494
- *
1495
- * @param req - an Express or Restify style request object.
1496
- * @param res - an Express or Restify style response object.
1497
- * @param logic - the additional function to handle bot context.
1498
- *
1499
- * @remarks
1500
- * Only work on server side.
1501
- */
1502
- requestHandler(req, res, logic) {
1503
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "ConversationBot"), ErrorCode.RuntimeNotSupported);
1504
- }
1168
+ // Copyright (c) Microsoft Corporation.
1169
+ /*
1170
+ * Sso execution dialog, use to handle sso command
1171
+ */
1172
+ class BotSsoExecutionDialog {
1173
+ constructor(dedupStorage, ssoPromptSettings, authConfig, ...args) {
1174
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "BotSsoExecutionDialog"), ErrorCode.RuntimeNotSupported);
1175
+ }
1176
+ // eslint-disable-next-line no-secrets/no-secrets
1177
+ /**
1178
+ * Add TeamsFxBotSsoCommandHandler instance
1179
+ * @param handler {@link BotSsoExecutionDialogHandler} callback function
1180
+ * @param triggerPatterns The trigger pattern
1181
+ */
1182
+ addCommand(handler, triggerPatterns) {
1183
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "BotSsoExecutionDialog"), ErrorCode.RuntimeNotSupported);
1184
+ }
1185
+ /**
1186
+ * The run method handles the incoming activity (in the form of a DialogContext) and passes it through the dialog system.
1187
+ *
1188
+ * @param context The context object for the current turn.
1189
+ * @param accessor The instance of StatePropertyAccessor for dialog system.
1190
+ */
1191
+ run(context, accessor) {
1192
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "BotSsoExecutionDialog"), ErrorCode.RuntimeNotSupported);
1193
+ }
1194
+ /**
1195
+ * Called when the component is ending.
1196
+ *
1197
+ * @param context Context for the current turn of conversation.
1198
+ */
1199
+ onEndDialog(context) {
1200
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "BotSsoExecutionDialog"), ErrorCode.RuntimeNotSupported);
1201
+ }
1505
1202
  }
1506
1203
 
1507
- // Copyright (c) Microsoft Corporation.
1508
- /*
1509
- * Sso execution dialog, use to handle sso command
1510
- */
1511
- class BotSsoExecutionDialog {
1512
- constructor(dedupStorage, ssoPromptSettings, authConfig, ...args) {
1513
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "BotSsoExecutionDialog"), ErrorCode.RuntimeNotSupported);
1514
- }
1515
- /**
1516
- * Add TeamsFxBotSsoCommandHandler instance
1517
- * @param handler {@link BotSsoExecutionDialogHandler} callback function
1518
- * @param triggerPatterns The trigger pattern
1519
- */
1520
- addCommand(handler, triggerPatterns) {
1521
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "BotSsoExecutionDialog"), ErrorCode.RuntimeNotSupported);
1522
- }
1523
- /**
1524
- * The run method handles the incoming activity (in the form of a DialogContext) and passes it through the dialog system.
1525
- *
1526
- * @param context The context object for the current turn.
1527
- * @param accessor The instance of StatePropertyAccessor for dialog system.
1528
- */
1529
- async run(context, accessor) {
1530
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "BotSsoExecutionDialog"), ErrorCode.RuntimeNotSupported);
1531
- }
1532
- /**
1533
- * Called when the component is ending.
1534
- *
1535
- * @param context Context for the current turn of conversation.
1536
- */
1537
- async onEndDialog(context) {
1538
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "BotSsoExecutionDialog"), ErrorCode.RuntimeNotSupported);
1539
- }
1204
+ /**
1205
+ * Users execute query with SSO or Access Token.
1206
+ * @remarks
1207
+ * Only works in in server side.
1208
+ */
1209
+ function handleMessageExtensionQueryWithSSO(context, config, initiateLoginEndpoint, scopes, logic) {
1210
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "queryWithToken in message extension"), ErrorCode.RuntimeNotSupported);
1540
1211
  }
1541
1212
 
1542
- // Copyright (c) Microsoft Corporation.
1543
- /**
1544
- * Send a plain text message to a notification target.
1545
- *
1546
- * @remarks
1547
- * Only work on server side.
1548
- *
1549
- * @param target - the notification target.
1550
- * @param text - the plain text message.
1551
- * @param onError - an optional error handler that can catch exceptions during message sending.
1552
- * @returns A `Promise` representing the asynchronous operation.
1553
- */
1554
- function sendMessage$1(target, text, onError) {
1555
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "sendMessage"), ErrorCode.RuntimeNotSupported);
1556
- }
1557
- /**
1558
- * Send an adaptive card message to a notification target.
1559
- *
1560
- * @remarks
1561
- * Only work on server side.
1562
- *
1563
- * @param target - the notification target.
1564
- * @param card - the adaptive card raw JSON.
1565
- * @param onError - an optional error handler that can catch exceptions during adaptive card sending.
1566
- * @returns A `Promise` representing the asynchronous operation.
1567
- */
1568
- function sendAdaptiveCard$1(target, card, onError) {
1569
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "sendAdaptiveCard"), ErrorCode.RuntimeNotSupported);
1570
- }
1571
- /**
1572
- * A {@link NotificationTarget} that represents a team channel.
1573
- *
1574
- * @remarks
1575
- * Only work on server side.
1576
- *
1577
- * It's recommended to get channels from {@link TeamsBotInstallation.channels()}.
1578
- */
1579
- class Channel$1 {
1580
- /**
1581
- * Constructor.
1582
- *
1583
- * @remarks
1584
- * Only work on server side.
1585
- *
1586
- * It's recommended to get channels from {@link TeamsBotInstallation.channels()}, instead of using this constructor.
1587
- *
1588
- * @param parent - The parent {@link TeamsBotInstallation} where this channel is created from.
1589
- * @param info - Detailed channel information.
1590
- */
1591
- constructor(parent, info) {
1592
- /**
1593
- * Notification target type. For channel it's always "Channel".
1594
- *
1595
- * @remarks
1596
- * Only work on server side.
1597
- */
1598
- this.type = NotificationTargetType.Channel;
1599
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Channel"), ErrorCode.RuntimeNotSupported);
1600
- }
1601
- /**
1602
- * Send a plain text message.
1603
- *
1604
- * @remarks
1605
- * Only work on server side.
1606
- *
1607
- * @param text - the plain text message.
1608
- * @param onError - an optional error handler that can catch exceptions during message sending.
1609
- * @returns the response of sending message.
1610
- */
1611
- sendMessage(text, onError) {
1612
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Channel"), ErrorCode.RuntimeNotSupported);
1613
- }
1614
- /**
1615
- * Send an adaptive card message.
1616
- *
1617
- * @remarks
1618
- * Only work on server side.
1619
- *
1620
- * @param card - the adaptive card raw JSON.
1621
- * @param onError - an optional error handler that can catch exceptions during adaptive card sending.
1622
- * @returns the response of sending adaptive card message.
1623
- */
1624
- sendAdaptiveCard(card, onError) {
1625
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Channel"), ErrorCode.RuntimeNotSupported);
1626
- }
1627
- }
1628
- /**
1629
- * A {@link NotificationTarget} that represents a team member.
1630
- *
1631
- * @remarks
1632
- * Only work on server side.
1633
- *
1634
- * It's recommended to get members from {@link TeamsBotInstallation.members()}.
1635
- */
1636
- class Member$1 {
1637
- /**
1638
- * Constructor.
1639
- *
1640
- * @remarks
1641
- * Only work on server side.
1642
- *
1643
- * It's recommended to get members from {@link TeamsBotInstallation.members()}, instead of using this constructor.
1644
- *
1645
- * @param parent - The parent {@link TeamsBotInstallation} where this member is created from.
1646
- * @param account - Detailed member account information.
1647
- */
1648
- constructor(parent, account) {
1649
- /**
1650
- * Notification target type. For member it's always "Person".
1651
- *
1652
- * @remarks
1653
- * Only work on server side.
1654
- */
1655
- this.type = NotificationTargetType.Person;
1656
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Member"), ErrorCode.RuntimeNotSupported);
1657
- }
1658
- /**
1659
- * Send a plain text message.
1660
- *
1661
- * @remarks
1662
- * Only work on server side.
1663
- *
1664
- * @param text - the plain text message.
1665
- * @param onError - an optional error handler that can catch exceptions during message sending.
1666
- * @returns the response of sending message.
1667
- */
1668
- sendMessage(text, onError) {
1669
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Member"), ErrorCode.RuntimeNotSupported);
1670
- }
1671
- /**
1672
- * Send an adaptive card message.
1673
- *
1674
- * @remarks
1675
- * Only work on server side.
1676
- *
1677
- * @param card - the adaptive card raw JSON.
1678
- * @param onError - an optional error handler that can catch exceptions during adaptive card sending.
1679
- * @returns the response of sending adaptive card message.
1680
- */
1681
- sendAdaptiveCard(card, onError) {
1682
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Member"), ErrorCode.RuntimeNotSupported);
1683
- }
1684
- }
1685
- /**
1686
- * A {@link NotificationTarget} that represents a bot installation. Teams Bot could be installed into
1687
- * - Personal chat
1688
- * - Group chat
1689
- * - Team (by default the `General` channel)
1690
- *
1691
- * @remarks
1692
- * Only work on server side.
1693
- *
1694
- * It's recommended to get bot installations from {@link ConversationBot.installations()}.
1695
- */
1696
- /**
1697
- * @deprecated Use `BotBuilderCloudAdapter.TeamsBotInstallation` instead.
1698
- */
1699
- class TeamsBotInstallation$1 {
1700
- /**
1701
- * Constructor
1702
- *
1703
- * @remarks
1704
- * Only work on server side.
1705
- *
1706
- * It's recommended to get bot installations from {@link ConversationBot.installations()}, instead of using this constructor.
1707
- *
1708
- * @param adapter - the bound `BotFrameworkAdapter`.
1709
- * @param conversationReference - the bound `ConversationReference`.
1710
- */
1711
- constructor(adapter, conversationReference) {
1712
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported);
1713
- }
1714
- /**
1715
- * Send a plain text message.
1716
- *
1717
- * @remarks
1718
- * Only work on server side.
1719
- *
1720
- * @param text - the plain text message.
1721
- * @param onError - an optional error handler that can catch exceptions during message sending.
1722
- * @returns the response of sending message.
1723
- */
1724
- sendMessage(text, onError) {
1725
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported);
1726
- }
1727
- /**
1728
- * Send an adaptive card message.
1729
- *
1730
- * @remarks
1731
- * Only work on server side.
1732
- *
1733
- * @param card - the adaptive card raw JSON.
1734
- * @param onError - an optional error handler that can catch exceptions during adaptive card sending.
1735
- * @returns the response of sending adaptive card message.
1736
- */
1737
- sendAdaptiveCard(card, onError) {
1738
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported);
1739
- }
1740
- /**
1741
- * Get channels from this bot installation.
1742
- *
1743
- * @remarks
1744
- * Only work on server side.
1745
- *
1746
- * @returns an array of channels if bot is installed into a team, otherwise returns an empty array.
1747
- */
1748
- channels() {
1749
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported);
1750
- }
1751
- /**
1752
- * Get members from this bot installation.
1753
- *
1754
- * @remarks
1755
- * Only work on server side.
1756
- *
1757
- * @returns an array of members from where the bot is installed.
1758
- */
1759
- members() {
1760
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported);
1761
- }
1762
- /**
1763
- * Get team details from this bot installation
1764
- *
1765
- * @returns the team details if bot is installed into a team, otherwise returns undefined.
1766
- */
1767
- getTeamDetails() {
1768
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported);
1769
- }
1770
- }
1771
- /**
1772
- * Provide static utilities for bot notification.
1773
- *
1774
- * @remarks
1775
- * Only work on server side.
1776
- *
1777
- * @example
1778
- * Here's an example on how to send notification via Teams Bot.
1779
- * ```typescript
1780
- * // initialize (it's recommended to be called before handling any bot message)
1781
- * const notificationBot = new NotificationBot(adapter);
1782
- *
1783
- * // get all bot installations and send message
1784
- * for (const target of await notificationBot.installations()) {
1785
- * await target.sendMessage("Hello Notification");
1786
- * }
1787
- *
1788
- * // alternative - send message to all members
1789
- * for (const target of await notificationBot.installations()) {
1790
- * for (const member of await target.members()) {
1791
- * await member.sendMessage("Hello Notification");
1792
- * }
1793
- * }
1794
- * ```
1795
- */
1796
- /**
1797
- * @deprecated Use `BotBuilderCloudAdapter.NotificationBot` instead.
1798
- */
1799
- class NotificationBot$1 {
1800
- /**
1801
- * constructor of the notification bot.
1802
- *
1803
- * @remarks
1804
- * Only work on server side.
1805
- *
1806
- * To ensure accuracy, it's recommended to initialize before handling any message.
1807
- *
1808
- * @param adapter - the bound `BotFrameworkAdapter`
1809
- * @param options - initialize options
1810
- */
1811
- constructor(adapter, options) {
1812
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported);
1813
- }
1814
- /**
1815
- * Get all targets where the bot is installed.
1816
- *
1817
- * @remarks
1818
- * Only work on server side.
1819
- *
1820
- * The result is retrieving from the persisted storage.
1821
- *
1822
- * @returns - an array of {@link TeamsBotInstallation}.
1823
- */
1824
- static installations() {
1825
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported);
1826
- }
1827
- /**
1828
- * Returns the first {@link Member} where predicate is true, and undefined otherwise.
1829
- *
1830
- * @remarks
1831
- * Only work on server side.
1832
- *
1833
- * @param predicate find calls predicate once for each member of the installation,
1834
- * until it finds one where predicate returns true. If such a member is found, find
1835
- * immediately returns that member. Otherwise, find returns undefined.
1836
- * @param scope the scope to find members from the installations
1837
- * (personal chat, group chat, Teams channel).
1838
- * @returns the first {@link Member} where predicate is true, and undefined otherwise.
1839
- */
1840
- findMember(predicate, scope) {
1841
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported);
1842
- }
1843
- /**
1844
- * Returns the first {@link Channel} where predicate is true, and undefined otherwise.
1845
- * (Ensure the bot app is installed into the `General` channel, otherwise undefined will be returned.)
1846
- *
1847
- * @remarks
1848
- * Only work on server side.
1849
- *
1850
- * @param predicate find calls predicate once for each channel of the installation,
1851
- * until it finds one where predicate returns true. If such a channel is found, find
1852
- * immediately returns that channel. Otherwise, find returns undefined.
1853
- * @returns the first {@link Channel} where predicate is true, and undefined otherwise.
1854
- */
1855
- findChannel(predicate) {
1856
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported);
1857
- }
1858
- /**
1859
- * Returns all {@link Member} where predicate is true, and empty array otherwise.
1860
- *
1861
- * @remarks
1862
- * Only work on server side.
1863
- *
1864
- * @param predicate find calls predicate for each member of the installation.
1865
- * @param scope the scope to find members from the installations
1866
- * (personal chat, group chat, Teams channel).
1867
- * @returns an array of {@link Member} where predicate is true, and empty array otherwise.
1868
- */
1869
- findAllMembers(predicate, scope) {
1870
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported);
1871
- }
1872
- /**
1873
- * Returns all {@link Channel} where predicate is true, and empty array otherwise.
1874
- * (Ensure the bot app is installed into the `General` channel, otherwise empty array will be returned.)
1875
- *
1876
- * @remarks
1877
- * Only work on server side.
1878
- *
1879
- * @param predicate find calls predicate for each channel of the installation.
1880
- * @returns an array of {@link Channel} where predicate is true, and empty array otherwise.
1881
- */
1882
- findAllChannels(predicate) {
1883
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported);
1884
- }
1885
- }
1886
- /**
1887
- * The search scope when calling {@link NotificationBot.findMember} and {@link NotificationBot.findAllMembers}.
1888
- * The search scope is a flagged enum and it can be combined with `|`.
1889
- * For example, to search from personal chat and group chat, use `SearchScope.Person | SearchScope.Group`.
1890
- */
1891
- var SearchScope$1;
1892
- (function (SearchScope) {
1893
- /**
1894
- * Search members from the installations in personal chat only.
1895
- */
1896
- SearchScope[SearchScope["Person"] = 1] = "Person";
1897
- /**
1898
- * Search members from the installations in group chat only.
1899
- */
1900
- SearchScope[SearchScope["Group"] = 2] = "Group";
1901
- /**
1902
- * Search members from the installations in Teams channel only.
1903
- */
1904
- SearchScope[SearchScope["Channel"] = 4] = "Channel";
1905
- /**
1906
- * Search members from all installations including personal chat, group chat and Teams channel.
1907
- */
1908
- SearchScope[SearchScope["All"] = 7] = "All";
1909
- })(SearchScope$1 || (SearchScope$1 = {}));
1910
-
1911
- // Copyright (c) Microsoft Corporation.
1912
- /**
1913
- * A command bot for receiving commands and sending responses in Teams.
1914
- *
1915
- * @remarks
1916
- * Only work on server side.
1917
- */
1918
- /**
1919
- * @deprecated Use `BotBuilderCloudAdapter.CommandBot` instead.
1920
- */
1921
- class CommandBot$1 {
1922
- /**
1923
- * Creates a new instance of the `CommandBot`.
1924
- *
1925
- * @param adapter The bound `BotFrameworkAdapter`.
1926
- * @param commands The commands to registered with the command bot. Each command should implement the interface {@link TeamsFxBotCommandHandler} so that it can be correctly handled by this command bot.
1927
- */
1928
- constructor(adapter, commands) {
1929
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CommandBot"), ErrorCode.RuntimeNotSupported);
1930
- }
1931
- /**
1932
- * Registers a command into the command bot.
1933
- *
1934
- * @param command The command to registered.
1935
- *
1936
- * @remarks
1937
- * Only work on server side.
1938
- */
1939
- registerCommand(command) {
1940
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CommandBot"), ErrorCode.RuntimeNotSupported);
1941
- }
1942
- /**
1943
- * Registers commands into the command bot.
1944
- *
1945
- * @param commands The command to registered.
1946
- *
1947
- * @remarks
1948
- * Only work on server side.
1949
- */
1950
- registerCommands(commands) {
1951
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CommandBot"), ErrorCode.RuntimeNotSupported);
1952
- }
1953
- /**
1954
- * Registers a sso command into the command bot.
1955
- *
1956
- * @param command The command to register.
1957
- */
1958
- registerSsoCommand(ssoCommand) {
1959
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CommandBot"), ErrorCode.RuntimeNotSupported);
1960
- }
1961
- /**
1962
- * Registers commands into the command bot.
1963
- *
1964
- * @param commands The commands to register.
1965
- */
1966
- registerSsoCommands(ssoCommands) {
1967
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CommandBot"), ErrorCode.RuntimeNotSupported);
1968
- }
1213
+ // Copyright (c) Microsoft Corporation.
1214
+ /**
1215
+ * Provide utilities for bot conversation, including:
1216
+ * - handle command and response.
1217
+ * - send notification to varies targets (e.g., member, group, channel).
1218
+ *
1219
+ * @remarks
1220
+ * Only work on server side.
1221
+ */
1222
+ class ConversationBot {
1223
+ /**
1224
+ * Create new instance of the `ConversationBot`.
1225
+ *
1226
+ * @param options - The initialize options.
1227
+ *
1228
+ * @remarks
1229
+ * Only work on server side.
1230
+ */
1231
+ constructor(options) {
1232
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "ConversationBot"), ErrorCode.RuntimeNotSupported);
1233
+ }
1234
+ /**
1235
+ * The request handler to integrate with web request.
1236
+ *
1237
+ * @param req - An incoming HTTP [Request](xref:botbuilder.Request).
1238
+ * @param res - The corresponding HTTP [Response](xref:botbuilder.Response).
1239
+ * @param logic - The additional function to handle bot context.
1240
+ *
1241
+ * @remarks
1242
+ * Only work on server side.
1243
+ */
1244
+ requestHandler(req, res, logic) {
1245
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "ConversationBot"), ErrorCode.RuntimeNotSupported));
1246
+ }
1969
1247
  }
1970
1248
 
1971
- /**
1972
- * A card action bot to respond to adaptive card universal actions.
1973
- *
1974
- * @remarks
1975
- * Only work on server side.
1976
- */
1977
- /**
1978
- * @deprecated Use `BotBuilderCloudAdapter.CardActionBot` instead.
1979
- */
1980
- class CardActionBot$1 {
1981
- /**
1982
- * Creates a new instance of the `CardActionBot`.
1983
- *
1984
- * @param adapter The bound `BotFrameworkAdapter`.
1985
- * @param options - initialize options
1986
- */
1987
- constructor(adapter, options) {
1988
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CardActionBot"), ErrorCode.RuntimeNotSupported);
1989
- }
1990
- /**
1991
- * Registers a card action handler to the bot.
1992
- * @param actionHandler A card action handler to be registered.
1993
- *
1994
- * @remarks
1995
- * Only work on server side.
1996
- */
1997
- registerHandler(actionHandler) {
1998
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CardActionBot"), ErrorCode.RuntimeNotSupported);
1999
- }
2000
- /**
2001
- * Registers card action handlers to the bot.
2002
- * @param actionHandlers A set of card action handlers to be registered.
2003
- *
2004
- * @remarks
2005
- * Only work on server side.
2006
- */
2007
- registerHandlers(actionHandlers) {
2008
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CardActionBot"), ErrorCode.RuntimeNotSupported);
2009
- }
1249
+ // Copyright (c) Microsoft Corporation.
1250
+ /**
1251
+ * Send a plain text message to a notification target.
1252
+ *
1253
+ * @remarks
1254
+ * Only work on server side.
1255
+ *
1256
+ * @param target - The notification target.
1257
+ * @param text - The plain text message.
1258
+ * @param onError - An optional error handler that can catch exceptions during message sending.
1259
+ *
1260
+ * @returns A `Promise` representing the asynchronous operation.
1261
+ */
1262
+ function sendMessage(target, text, onError) {
1263
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "sendMessage"), ErrorCode.RuntimeNotSupported));
2010
1264
  }
2011
-
2012
- // eslint-disable-next-line no-secrets/no-secrets
2013
- /**
2014
- * Users execute query with SSO or Access Token.
2015
- * @deprecated
2016
- * @remarks
2017
- * Only works in in server side.
2018
- */
2019
- function handleMessageExtensionQueryWithToken(context, config, scopes, logic) {
2020
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "queryWithToken in message extension"), ErrorCode.RuntimeNotSupported);
2021
- }
2022
- /**
2023
- * Users execute query with SSO or Access Token.
2024
- * @remarks
2025
- * Only works in in server side.
2026
- */
2027
- function handleMessageExtensionQueryWithSSO(context, config, initiateLoginEndpoint, scopes, logic) {
2028
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "queryWithToken in message extension"), ErrorCode.RuntimeNotSupported);
1265
+ /**
1266
+ * Send an adaptive card message to a notification target.
1267
+ *
1268
+ * @remarks
1269
+ * Only work on server side.
1270
+ *
1271
+ * @param target - The notification target.
1272
+ * @param card - The adaptive card raw JSON.
1273
+ * @param onError - An optional error handler that can catch exceptions during adaptive card sending.
1274
+ *
1275
+ * @returns A `Promise` representing the asynchronous operation.
1276
+ */
1277
+ function sendAdaptiveCard(target, card, onError) {
1278
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "sendAdaptiveCard"), ErrorCode.RuntimeNotSupported));
2029
1279
  }
2030
-
2031
- // Copyright (c) Microsoft Corporation.
2032
- /**
2033
- * Provide utilities for bot conversation, including:
2034
- * - handle command and response.
2035
- * - send notification to varies targets (e.g., member, group, channel).
2036
- *
2037
- * @remarks
2038
- * Only work on server side.
2039
- */
2040
- class ConversationBot {
2041
- /**
2042
- * Create new instance of the `ConversationBot`.
2043
- *
2044
- * @param options - The initialize options.
2045
- *
2046
- * @remarks
2047
- * Only work on server side.
2048
- */
2049
- constructor(options) {
2050
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "ConversationBot"), ErrorCode.RuntimeNotSupported);
2051
- }
2052
- /**
2053
- * The request handler to integrate with web request.
2054
- *
2055
- * @param req - An incoming HTTP [Request](xref:botbuilder.Request).
2056
- * @param res - The corresponding HTTP [Response](xref:botbuilder.Response).
2057
- * @param logic - The additional function to handle bot context.
2058
- *
2059
- * @remarks
2060
- * Only work on server side.
2061
- */
2062
- requestHandler(req, res, logic) {
2063
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "ConversationBot"), ErrorCode.RuntimeNotSupported));
2064
- }
1280
+ /**
1281
+ * A {@link NotificationTarget} that represents a team channel.
1282
+ *
1283
+ * @remarks
1284
+ * Only work on server side.
1285
+ *
1286
+ * It's recommended to get channels from {@link TeamsBotInstallation.channels()}.
1287
+ */
1288
+ class Channel {
1289
+ /**
1290
+ * Constructor.
1291
+ *
1292
+ * @remarks
1293
+ * Only work on server side.
1294
+ *
1295
+ * It's recommended to get channels from {@link TeamsBotInstallation.channels()}, instead of using this constructor.
1296
+ *
1297
+ * @param parent - The parent {@link TeamsBotInstallation} where this channel is created from.
1298
+ * @param info - Detailed channel information.
1299
+ */
1300
+ constructor(parent, info) {
1301
+ /**
1302
+ * Notification target type. For channel it's always "Channel".
1303
+ *
1304
+ * @remarks
1305
+ * Only work on server side.
1306
+ */
1307
+ this.type = NotificationTargetType.Channel;
1308
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Channel"), ErrorCode.RuntimeNotSupported);
1309
+ }
1310
+ /**
1311
+ * Send a plain text message.
1312
+ *
1313
+ * @remarks
1314
+ * Only work on server side.
1315
+ *
1316
+ * @param text - The plain text message.
1317
+ * @param onError - An optional error handler that can catch exceptions during message sending.
1318
+ *
1319
+ * @returns The response of sending message.
1320
+ */
1321
+ sendMessage(text, onError) {
1322
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Channel"), ErrorCode.RuntimeNotSupported));
1323
+ }
1324
+ /**
1325
+ * Send an adaptive card message.
1326
+ *
1327
+ * @remarks
1328
+ * Only work on server side.
1329
+ *
1330
+ * @param card - The adaptive card raw JSON.
1331
+ * @param onError - An optional error handler that can catch exceptions during adaptive card sending.
1332
+ *
1333
+ * @returns The response of sending adaptive card message.
1334
+ */
1335
+ sendAdaptiveCard(card, onError) {
1336
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Channel"), ErrorCode.RuntimeNotSupported));
1337
+ }
2065
1338
  }
2066
-
2067
- // Copyright (c) Microsoft Corporation.
2068
- /**
2069
- * Send a plain text message to a notification target.
2070
- *
2071
- * @remarks
2072
- * Only work on server side.
2073
- *
2074
- * @param target - The notification target.
2075
- * @param text - The plain text message.
2076
- * @param onError - An optional error handler that can catch exceptions during message sending.
2077
- *
2078
- * @returns A `Promise` representing the asynchronous operation.
2079
- */
2080
- function sendMessage(target, text, onError) {
2081
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "sendMessage"), ErrorCode.RuntimeNotSupported));
2082
- }
2083
- /**
2084
- * Send an adaptive card message to a notification target.
2085
- *
2086
- * @remarks
2087
- * Only work on server side.
2088
- *
2089
- * @param target - The notification target.
2090
- * @param card - The adaptive card raw JSON.
2091
- * @param onError - An optional error handler that can catch exceptions during adaptive card sending.
2092
- *
2093
- * @returns A `Promise` representing the asynchronous operation.
2094
- */
2095
- function sendAdaptiveCard(target, card, onError) {
2096
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "sendAdaptiveCard"), ErrorCode.RuntimeNotSupported));
2097
- }
2098
- /**
2099
- * A {@link NotificationTarget} that represents a team channel.
2100
- *
2101
- * @remarks
2102
- * Only work on server side.
2103
- *
2104
- * It's recommended to get channels from {@link TeamsBotInstallation.channels()}.
2105
- */
2106
- class Channel {
2107
- /**
2108
- * Constructor.
2109
- *
2110
- * @remarks
2111
- * Only work on server side.
2112
- *
2113
- * It's recommended to get channels from {@link TeamsBotInstallation.channels()}, instead of using this constructor.
2114
- *
2115
- * @param parent - The parent {@link TeamsBotInstallation} where this channel is created from.
2116
- * @param info - Detailed channel information.
2117
- */
2118
- constructor(parent, info) {
2119
- /**
2120
- * Notification target type. For channel it's always "Channel".
2121
- *
2122
- * @remarks
2123
- * Only work on server side.
2124
- */
2125
- this.type = NotificationTargetType.Channel;
2126
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Channel"), ErrorCode.RuntimeNotSupported);
2127
- }
2128
- /**
2129
- * Send a plain text message.
2130
- *
2131
- * @remarks
2132
- * Only work on server side.
2133
- *
2134
- * @param text - The plain text message.
2135
- * @param onError - An optional error handler that can catch exceptions during message sending.
2136
- *
2137
- * @returns The response of sending message.
2138
- */
2139
- sendMessage(text, onError) {
2140
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Channel"), ErrorCode.RuntimeNotSupported));
2141
- }
2142
- /**
2143
- * Send an adaptive card message.
2144
- *
2145
- * @remarks
2146
- * Only work on server side.
2147
- *
2148
- * @param card - The adaptive card raw JSON.
2149
- * @param onError - An optional error handler that can catch exceptions during adaptive card sending.
2150
- *
2151
- * @returns The response of sending adaptive card message.
2152
- */
2153
- sendAdaptiveCard(card, onError) {
2154
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Channel"), ErrorCode.RuntimeNotSupported));
2155
- }
2156
- }
2157
- /**
2158
- * A {@link NotificationTarget} that represents a team member.
2159
- *
2160
- * @remarks
2161
- * Only work on server side.
2162
- *
2163
- * It's recommended to get members from {@link TeamsBotInstallation.members()}.
2164
- */
2165
- class Member {
2166
- /**
2167
- * Constructor.
2168
- *
2169
- * @remarks
2170
- * Only work on server side.
2171
- *
2172
- * It's recommended to get members from {@link TeamsBotInstallation.members()}, instead of using this constructor.
2173
- *
2174
- * @param parent - The parent {@link TeamsBotInstallation} where this member is created from.
2175
- * @param account - Detailed member account information.
2176
- */
2177
- constructor(parent, account) {
2178
- /**
2179
- * Notification target type. For member it's always "Person".
2180
- *
2181
- * @remarks
2182
- * Only work on server side.
2183
- */
2184
- this.type = NotificationTargetType.Person;
2185
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Member"), ErrorCode.RuntimeNotSupported);
2186
- }
2187
- /**
2188
- * Send a plain text message.
2189
- *
2190
- * @remarks
2191
- * Only work on server side.
2192
- *
2193
- * @param text - The plain text message.
2194
- * @param onError - An optional error handler that can catch exceptions during message sending.
2195
- *
2196
- * @returns The response of sending message.
2197
- */
2198
- sendMessage(text, onError) {
2199
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Member"), ErrorCode.RuntimeNotSupported));
2200
- }
2201
- /**
2202
- * Send an adaptive card message.
2203
- *
2204
- * @remarks
2205
- * Only work on server side.
2206
- *
2207
- * @param card - The adaptive card raw JSON.
2208
- * @param onError - An optional error handler that can catch exceptions during adaptive card sending.
2209
- *
2210
- * @returns The response of sending adaptive card message.
2211
- */
2212
- sendAdaptiveCard(card, onError) {
2213
- return Promise.reject(Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Member"), ErrorCode.RuntimeNotSupported)));
2214
- }
2215
- }
2216
- /**
2217
- * A {@link NotificationTarget} that represents a bot installation. Teams Bot could be installed into
2218
- * - Personal chat
2219
- * - Group chat
2220
- * - Team (by default the `General` channel)
2221
- *
2222
- * @remarks
2223
- * Only work on server side.
2224
- *
2225
- * It's recommended to get bot installations from {@link ConversationBot.installations()}.
2226
- */
2227
- class TeamsBotInstallation {
2228
- /**
2229
- * Constructor
2230
- *
2231
- * @remarks
2232
- * Only work on server side.
2233
- *
2234
- * It's recommended to get bot installations from {@link ConversationBot.installations()}, instead of using this constructor.
2235
- *
2236
- * @param adapter - The bound `CloudAdapter`.
2237
- * @param conversationReference - The bound `ConversationReference`.
2238
- */
2239
- constructor(adapter, conversationReference) {
2240
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported);
2241
- }
2242
- /**
2243
- * Send a plain text message.
2244
- *
2245
- * @remarks
2246
- * Only work on server side.
2247
- *
2248
- * @param text - The plain text message.
2249
- * @param onError - An optional error handler that can catch exceptions during message sending.
2250
- *
2251
- * @returns The response of sending message.
2252
- */
2253
- sendMessage(text, onError) {
2254
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported));
2255
- }
2256
- /**
2257
- * Send an adaptive card message.
2258
- *
2259
- * @remarks
2260
- * Only work on server side.
2261
- *
2262
- * @param card - The adaptive card raw JSON.
2263
- * @param onError - An optional error handler that can catch exceptions during adaptive card sending.
2264
- *
2265
- * @returns The response of sending adaptive card message.
2266
- */
2267
- sendAdaptiveCard(card, onError) {
2268
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported));
2269
- }
2270
- /**
2271
- * Get channels from this bot installation.
2272
- *
2273
- * @remarks
2274
- * Only work on server side.
2275
- *
2276
- * @returns An array of channels if bot is installed into a team, otherwise returns an empty array.
2277
- */
2278
- channels() {
2279
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported));
2280
- }
2281
- /**
2282
- * Get members from this bot installation.
2283
- *
2284
- * @remarks
2285
- * Only work on server side.
2286
- *
2287
- * @returns An array of members from where the bot is installed.
2288
- */
2289
- members() {
2290
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported));
2291
- }
2292
- /**
2293
- * Get team details from this bot installation
2294
- *
2295
- * @returns The team details if bot is installed into a team, otherwise returns undefined.
2296
- */
2297
- getTeamDetails() {
2298
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported));
2299
- }
2300
- }
2301
- /**
2302
- * Provide static utilities for bot notification.
2303
- *
2304
- * @remarks
2305
- * Only work on server side.
2306
- *
2307
- * @example
2308
- * Here's an example on how to send notification via Teams Bot.
2309
- * ```typescript
2310
- * // initialize (it's recommended to be called before handling any bot message)
2311
- * const notificationBot = new NotificationBot(adapter);
2312
- *
2313
- * // get all bot installations and send message
2314
- * for (const target of await notificationBot.installations()) {
2315
- * await target.sendMessage("Hello Notification");
2316
- * }
2317
- *
2318
- * // alternative - send message to all members
2319
- * for (const target of await notificationBot.installations()) {
2320
- * for (const member of await target.members()) {
2321
- * await member.sendMessage("Hello Notification");
2322
- * }
2323
- * }
2324
- * ```
2325
- */
2326
- class NotificationBot {
2327
- /**
2328
- * Constructor of the notification bot.
2329
- *
2330
- * @remarks
2331
- * Only work on server side.
2332
- *
2333
- * To ensure accuracy, it's recommended to initialize before handling any message.
2334
- *
2335
- * @param adapter - The bound `CloudAdapter`
2336
- * @param options - The initialize options
2337
- */
2338
- constructor(adapter, options) {
2339
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported);
2340
- }
2341
- /**
2342
- * Get all targets where the bot is installed.
2343
- *
2344
- * @remarks
2345
- * Only work on server side.
2346
- *
2347
- * The result is retrieving from the persisted storage.
2348
- *
2349
- * @returns An array of {@link TeamsBotInstallation}.
2350
- */
2351
- static installations() {
2352
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported));
2353
- }
2354
- /**
2355
- * Return the first {@link Member} where predicate is true, and undefined otherwise.
2356
- *
2357
- * @remarks
2358
- * Only work on server side.
2359
- *
2360
- * @param predicate find calls predicate once for each member of the installation,
2361
- * until it finds one where predicate returns true. If such a member is found,
2362
- * find immediately returns that member. Otherwise, find returns undefined.
2363
- * @param scope the scope to find members from the installations (personal chat, group chat, Teams channel).
2364
- *
2365
- * @returns The first {@link Member} where predicate is true, and undefined otherwise.
2366
- */
2367
- findMember(predicate, scope) {
2368
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported));
2369
- }
2370
- /**
2371
- * Return the first {@link Channel} where predicate is true, and undefined otherwise.
2372
- * (Ensure the bot app is installed into the `General` channel, otherwise undefined will be returned.)
2373
- *
2374
- * @remarks
2375
- * Only work on server side.
2376
- *
2377
- * @param predicate - Find calls predicate once for each channel of the installation,
2378
- * until it finds one where predicate returns true. If such a channel is found, find
2379
- * immediately returns that channel. Otherwise, find returns undefined.
2380
- *
2381
- * @returns The first {@link Channel} where predicate is true, and `undefined` otherwise.
2382
- */
2383
- findChannel(predicate) {
2384
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported));
2385
- }
2386
- /**
2387
- * Return all {@link Member} where predicate is true, and empty array otherwise.
2388
- *
2389
- * @remarks
2390
- * Only work on server side.
2391
- *
2392
- * @param predicate - Find calls predicate for each member of the installation.
2393
- * @param scope - The scope to find members from the installations.
2394
- * (personal chat, group chat, Teams channel).
2395
- *
2396
- * @returns An array of {@link Member} where predicate is true, and empty array otherwise.
2397
- */
2398
- findAllMembers(predicate, scope) {
2399
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported));
2400
- }
2401
- /**
2402
- * Return all {@link Channel} where predicate is true, and empty array otherwise.
2403
- * (Ensure the bot app is installed into the `General` channel, otherwise empty array will be returned.)
2404
- *
2405
- * @remarks
2406
- * Only work on server side.
2407
- *
2408
- * @param predicate - Find calls predicate for each channel of the installation.
2409
- *
2410
- * @returns An array of {@link Channel} where predicate is true, and empty array otherwise.
2411
- */
2412
- findAllChannels(predicate) {
2413
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported));
2414
- }
2415
- }
2416
- /**
2417
- * The search scope when calling {@link NotificationBot.findMember} and {@link NotificationBot.findAllMembers}.
2418
- * The search scope is a flagged enum and it can be combined with `|`.
2419
- * For example, to search from personal chat and group chat, use `SearchScope.Person | SearchScope.Group`.
2420
- */
2421
- var SearchScope;
2422
- (function (SearchScope) {
2423
- /**
2424
- * Search members from the installations in personal chat only.
2425
- */
2426
- SearchScope[SearchScope["Person"] = 1] = "Person";
2427
- /**
2428
- * Search members from the installations in group chat only.
2429
- */
2430
- SearchScope[SearchScope["Group"] = 2] = "Group";
2431
- /**
2432
- * Search members from the installations in Teams channel only.
2433
- */
2434
- SearchScope[SearchScope["Channel"] = 4] = "Channel";
2435
- /**
2436
- * Search members from all installations including personal chat, group chat and Teams channel.
2437
- */
2438
- SearchScope[SearchScope["All"] = 7] = "All";
1339
+ /**
1340
+ * A {@link NotificationTarget} that represents a team member.
1341
+ *
1342
+ * @remarks
1343
+ * Only work on server side.
1344
+ *
1345
+ * It's recommended to get members from {@link TeamsBotInstallation.members()}.
1346
+ */
1347
+ class Member {
1348
+ /**
1349
+ * Constructor.
1350
+ *
1351
+ * @remarks
1352
+ * Only work on server side.
1353
+ *
1354
+ * It's recommended to get members from {@link TeamsBotInstallation.members()}, instead of using this constructor.
1355
+ *
1356
+ * @param parent - The parent {@link TeamsBotInstallation} where this member is created from.
1357
+ * @param account - Detailed member account information.
1358
+ */
1359
+ constructor(parent, account) {
1360
+ /**
1361
+ * Notification target type. For member it's always "Person".
1362
+ *
1363
+ * @remarks
1364
+ * Only work on server side.
1365
+ */
1366
+ this.type = NotificationTargetType.Person;
1367
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Member"), ErrorCode.RuntimeNotSupported);
1368
+ }
1369
+ /**
1370
+ * Send a plain text message.
1371
+ *
1372
+ * @remarks
1373
+ * Only work on server side.
1374
+ *
1375
+ * @param text - The plain text message.
1376
+ * @param onError - An optional error handler that can catch exceptions during message sending.
1377
+ *
1378
+ * @returns The response of sending message.
1379
+ */
1380
+ sendMessage(text, onError) {
1381
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Member"), ErrorCode.RuntimeNotSupported));
1382
+ }
1383
+ /**
1384
+ * Send an adaptive card message.
1385
+ *
1386
+ * @remarks
1387
+ * Only work on server side.
1388
+ *
1389
+ * @param card - The adaptive card raw JSON.
1390
+ * @param onError - An optional error handler that can catch exceptions during adaptive card sending.
1391
+ *
1392
+ * @returns The response of sending adaptive card message.
1393
+ */
1394
+ sendAdaptiveCard(card, onError) {
1395
+ return Promise.reject(Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Member"), ErrorCode.RuntimeNotSupported)));
1396
+ }
1397
+ }
1398
+ /**
1399
+ * A {@link NotificationTarget} that represents a bot installation. Teams Bot could be installed into
1400
+ * - Personal chat
1401
+ * - Group chat
1402
+ * - Team (by default the `General` channel)
1403
+ *
1404
+ * @remarks
1405
+ * Only work on server side.
1406
+ *
1407
+ * It's recommended to get bot installations from {@link ConversationBot.installations()}.
1408
+ */
1409
+ class TeamsBotInstallation {
1410
+ /**
1411
+ * Constructor
1412
+ *
1413
+ * @remarks
1414
+ * Only work on server side.
1415
+ *
1416
+ * It's recommended to get bot installations from {@link ConversationBot.installations()}, instead of using this constructor.
1417
+ *
1418
+ * @param adapter - The bound `CloudAdapter`.
1419
+ * @param conversationReference - The bound `ConversationReference`.
1420
+ */
1421
+ constructor(adapter, conversationReference) {
1422
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported);
1423
+ }
1424
+ /**
1425
+ * Send a plain text message.
1426
+ *
1427
+ * @remarks
1428
+ * Only work on server side.
1429
+ *
1430
+ * @param text - The plain text message.
1431
+ * @param onError - An optional error handler that can catch exceptions during message sending.
1432
+ *
1433
+ * @returns The response of sending message.
1434
+ */
1435
+ sendMessage(text, onError) {
1436
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported));
1437
+ }
1438
+ /**
1439
+ * Send an adaptive card message.
1440
+ *
1441
+ * @remarks
1442
+ * Only work on server side.
1443
+ *
1444
+ * @param card - The adaptive card raw JSON.
1445
+ * @param onError - An optional error handler that can catch exceptions during adaptive card sending.
1446
+ *
1447
+ * @returns The response of sending adaptive card message.
1448
+ */
1449
+ sendAdaptiveCard(card, onError) {
1450
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported));
1451
+ }
1452
+ /**
1453
+ * Get channels from this bot installation.
1454
+ *
1455
+ * @remarks
1456
+ * Only work on server side.
1457
+ *
1458
+ * @returns An array of channels if bot is installed into a team, otherwise returns an empty array.
1459
+ */
1460
+ channels() {
1461
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported));
1462
+ }
1463
+ /**
1464
+ * Get members from this bot installation.
1465
+ *
1466
+ * @remarks
1467
+ * Only work on server side.
1468
+ *
1469
+ * @returns An array of members from where the bot is installed.
1470
+ */
1471
+ members() {
1472
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported));
1473
+ }
1474
+ /**
1475
+ * Get team details from this bot installation
1476
+ *
1477
+ * @returns The team details if bot is installed into a team, otherwise returns undefined.
1478
+ */
1479
+ getTeamDetails() {
1480
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported));
1481
+ }
1482
+ }
1483
+ /**
1484
+ * Provide static utilities for bot notification.
1485
+ *
1486
+ * @remarks
1487
+ * Only work on server side.
1488
+ *
1489
+ * @example
1490
+ * Here's an example on how to send notification via Teams Bot.
1491
+ * ```typescript
1492
+ * // initialize (it's recommended to be called before handling any bot message)
1493
+ * const notificationBot = new NotificationBot(adapter);
1494
+ *
1495
+ * // get all bot installations and send message
1496
+ * for (const target of await notificationBot.installations()) {
1497
+ * await target.sendMessage("Hello Notification");
1498
+ * }
1499
+ *
1500
+ * // alternative - send message to all members
1501
+ * for (const target of await notificationBot.installations()) {
1502
+ * for (const member of await target.members()) {
1503
+ * await member.sendMessage("Hello Notification");
1504
+ * }
1505
+ * }
1506
+ * ```
1507
+ */
1508
+ class NotificationBot {
1509
+ /**
1510
+ * Constructor of the notification bot.
1511
+ *
1512
+ * @remarks
1513
+ * Only work on server side.
1514
+ *
1515
+ * To ensure accuracy, it's recommended to initialize before handling any message.
1516
+ *
1517
+ * @param adapter - The bound `CloudAdapter`
1518
+ * @param options - The initialize options
1519
+ */
1520
+ constructor(adapter, options) {
1521
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported);
1522
+ }
1523
+ /**
1524
+ * Get all targets where the bot is installed.
1525
+ *
1526
+ * @remarks
1527
+ * Only work on server side.
1528
+ *
1529
+ * The result is retrieving from the persisted storage.
1530
+ *
1531
+ * @returns An array of {@link TeamsBotInstallation}.
1532
+ */
1533
+ static installations() {
1534
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported));
1535
+ }
1536
+ /**
1537
+ * Return the first {@link Member} where predicate is true, and undefined otherwise.
1538
+ *
1539
+ * @remarks
1540
+ * Only work on server side.
1541
+ *
1542
+ * @param predicate find calls predicate once for each member of the installation,
1543
+ * until it finds one where predicate returns true. If such a member is found,
1544
+ * find immediately returns that member. Otherwise, find returns undefined.
1545
+ * @param scope the scope to find members from the installations (personal chat, group chat, Teams channel).
1546
+ *
1547
+ * @returns The first {@link Member} where predicate is true, and undefined otherwise.
1548
+ */
1549
+ findMember(predicate, scope) {
1550
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported));
1551
+ }
1552
+ /**
1553
+ * Return the first {@link Channel} where predicate is true, and undefined otherwise.
1554
+ * (Ensure the bot app is installed into the `General` channel, otherwise undefined will be returned.)
1555
+ *
1556
+ * @remarks
1557
+ * Only work on server side.
1558
+ *
1559
+ * @param predicate - Find calls predicate once for each channel of the installation,
1560
+ * until it finds one where predicate returns true. If such a channel is found, find
1561
+ * immediately returns that channel. Otherwise, find returns undefined.
1562
+ *
1563
+ * @returns The first {@link Channel} where predicate is true, and `undefined` otherwise.
1564
+ */
1565
+ findChannel(predicate) {
1566
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported));
1567
+ }
1568
+ /**
1569
+ * Return all {@link Member} where predicate is true, and empty array otherwise.
1570
+ *
1571
+ * @remarks
1572
+ * Only work on server side.
1573
+ *
1574
+ * @param predicate - Find calls predicate for each member of the installation.
1575
+ * @param scope - The scope to find members from the installations.
1576
+ * (personal chat, group chat, Teams channel).
1577
+ *
1578
+ * @returns An array of {@link Member} where predicate is true, and empty array otherwise.
1579
+ */
1580
+ findAllMembers(predicate, scope) {
1581
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported));
1582
+ }
1583
+ /**
1584
+ * Return all {@link Channel} where predicate is true, and empty array otherwise.
1585
+ * (Ensure the bot app is installed into the `General` channel, otherwise empty array will be returned.)
1586
+ *
1587
+ * @remarks
1588
+ * Only work on server side.
1589
+ *
1590
+ * @param predicate - Find calls predicate for each channel of the installation.
1591
+ *
1592
+ * @returns An array of {@link Channel} where predicate is true, and empty array otherwise.
1593
+ */
1594
+ findAllChannels(predicate) {
1595
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported));
1596
+ }
1597
+ }
1598
+ /**
1599
+ * The search scope when calling {@link NotificationBot.findMember} and {@link NotificationBot.findAllMembers}.
1600
+ * The search scope is a flagged enum and it can be combined with `|`.
1601
+ * For example, to search from personal chat and group chat, use `SearchScope.Person | SearchScope.Group`.
1602
+ */
1603
+ var SearchScope;
1604
+ (function (SearchScope) {
1605
+ /**
1606
+ * Search members from the installations in personal chat only.
1607
+ */
1608
+ SearchScope[SearchScope["Person"] = 1] = "Person";
1609
+ /**
1610
+ * Search members from the installations in group chat only.
1611
+ */
1612
+ SearchScope[SearchScope["Group"] = 2] = "Group";
1613
+ /**
1614
+ * Search members from the installations in Teams channel only.
1615
+ */
1616
+ SearchScope[SearchScope["Channel"] = 4] = "Channel";
1617
+ /**
1618
+ * Search members from all installations including personal chat, group chat and Teams channel.
1619
+ */
1620
+ SearchScope[SearchScope["All"] = 7] = "All";
2439
1621
  })(SearchScope || (SearchScope = {}));
2440
1622
 
2441
- // Copyright (c) Microsoft Corporation.
2442
- /**
2443
- * A command bot for receiving commands and sending responses in Teams.
2444
- *
2445
- * @remarks
2446
- * Only work on server side.
2447
- */
2448
- class CommandBot {
2449
- /**
2450
- * Create a new instance of the `CommandBot`.
2451
- *
2452
- * @param adapter - The bound `CloudAdapter`.
2453
- * @param commands - The commands to be registered with the command bot. Each command should implement the interface {@link TeamsFxBotCommandHandler} so that it can be correctly handled by this command bot.
2454
- */
2455
- constructor(adapter, commands) {
2456
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CommandBot"), ErrorCode.RuntimeNotSupported);
2457
- }
2458
- /**
2459
- * Register a command into the command bot.
2460
- *
2461
- * @param command - The command to be registered.
2462
- *
2463
- * @remarks
2464
- * Only work on server side.
2465
- */
2466
- registerCommand(command) {
2467
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CommandBot"), ErrorCode.RuntimeNotSupported);
2468
- }
2469
- /**
2470
- * Register commands into the command bot.
2471
- *
2472
- * @param commands - The commands to be registered.
2473
- *
2474
- * @remarks
2475
- * Only work on server side.
2476
- */
2477
- registerCommands(commands) {
2478
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CommandBot"), ErrorCode.RuntimeNotSupported);
2479
- }
2480
- /**
2481
- * Register a sso command into the command bot.
2482
- *
2483
- * @param ssoCommand - The sso command to be registered.
2484
- */
2485
- registerSsoCommand(ssoCommand) {
2486
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CommandBot"), ErrorCode.RuntimeNotSupported);
2487
- }
2488
- /**
2489
- * Register sso commands into the command bot.
2490
- *
2491
- * @param ssoCommands - The sso commands to be registered.
2492
- */
2493
- registerSsoCommands(ssoCommands) {
2494
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CommandBot"), ErrorCode.RuntimeNotSupported);
2495
- }
1623
+ // Copyright (c) Microsoft Corporation.
1624
+ /**
1625
+ * A command bot for receiving commands and sending responses in Teams.
1626
+ *
1627
+ * @remarks
1628
+ * Only work on server side.
1629
+ */
1630
+ class CommandBot {
1631
+ /**
1632
+ * Create a new instance of the `CommandBot`.
1633
+ *
1634
+ * @param adapter - The bound `CloudAdapter`.
1635
+ * @param commands - The commands to be registered with the command bot. Each command should implement the interface {@link TeamsFxBotCommandHandler} so that it can be correctly handled by this command bot.
1636
+ */
1637
+ constructor(adapter, commands) {
1638
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CommandBot"), ErrorCode.RuntimeNotSupported);
1639
+ }
1640
+ /**
1641
+ * Register a command into the command bot.
1642
+ *
1643
+ * @param command - The command to be registered.
1644
+ *
1645
+ * @remarks
1646
+ * Only work on server side.
1647
+ */
1648
+ registerCommand(command) {
1649
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CommandBot"), ErrorCode.RuntimeNotSupported);
1650
+ }
1651
+ /**
1652
+ * Register commands into the command bot.
1653
+ *
1654
+ * @param commands - The commands to be registered.
1655
+ *
1656
+ * @remarks
1657
+ * Only work on server side.
1658
+ */
1659
+ registerCommands(commands) {
1660
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CommandBot"), ErrorCode.RuntimeNotSupported);
1661
+ }
1662
+ /**
1663
+ * Register a sso command into the command bot.
1664
+ *
1665
+ * @param ssoCommand - The sso command to be registered.
1666
+ */
1667
+ registerSsoCommand(ssoCommand) {
1668
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CommandBot"), ErrorCode.RuntimeNotSupported);
1669
+ }
1670
+ /**
1671
+ * Register sso commands into the command bot.
1672
+ *
1673
+ * @param ssoCommands - The sso commands to be registered.
1674
+ */
1675
+ registerSsoCommands(ssoCommands) {
1676
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CommandBot"), ErrorCode.RuntimeNotSupported);
1677
+ }
2496
1678
  }
2497
1679
 
2498
- /**
2499
- * A card action bot to respond to adaptive card universal actions.
2500
- *
2501
- * @remarks
2502
- * Only work on server side.
2503
- */
2504
- class CardActionBot {
2505
- /**
2506
- * Create a new instance of the `CardActionBot`.
2507
- *
2508
- * @param adapter - The bound `CloudAdapter`.
2509
- * @param options - The initialize options.
2510
- */
2511
- constructor(adapter, options) {
2512
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CardActionBot"), ErrorCode.RuntimeNotSupported);
2513
- }
2514
- /**
2515
- * Register a card action handler to the bot.
2516
- *
2517
- * @param actionHandler - A card action handler to be registered.
2518
- *
2519
- * @remarks
2520
- * Only work on server side.
2521
- */
2522
- registerHandler(actionHandler) {
2523
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CardActionBot"), ErrorCode.RuntimeNotSupported));
2524
- }
2525
- /**
2526
- * Register card action handlers to the bot.
2527
- *
2528
- * @param actionHandlers - A set of card action handlers to be registered.
2529
- *
2530
- * @remarks
2531
- * Only work on server side.
2532
- */
2533
- registerHandlers(actionHandlers) {
2534
- return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CardActionBot"), ErrorCode.RuntimeNotSupported));
2535
- }
1680
+ /**
1681
+ * A card action bot to respond to adaptive card universal actions.
1682
+ *
1683
+ * @remarks
1684
+ * Only work on server side.
1685
+ */
1686
+ class CardActionBot {
1687
+ /**
1688
+ * Create a new instance of the `CardActionBot`.
1689
+ *
1690
+ * @param adapter - The bound `CloudAdapter`.
1691
+ * @param options - The initialize options.
1692
+ */
1693
+ constructor(adapter, options) {
1694
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CardActionBot"), ErrorCode.RuntimeNotSupported);
1695
+ }
1696
+ /**
1697
+ * Register a card action handler to the bot.
1698
+ *
1699
+ * @param actionHandler - A card action handler to be registered.
1700
+ *
1701
+ * @remarks
1702
+ * Only work on server side.
1703
+ */
1704
+ registerHandler(actionHandler) {
1705
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CardActionBot"), ErrorCode.RuntimeNotSupported));
1706
+ }
1707
+ /**
1708
+ * Register card action handlers to the bot.
1709
+ *
1710
+ * @param actionHandlers - A set of card action handlers to be registered.
1711
+ *
1712
+ * @remarks
1713
+ * Only work on server side.
1714
+ */
1715
+ registerHandlers(actionHandlers) {
1716
+ return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CardActionBot"), ErrorCode.RuntimeNotSupported));
1717
+ }
2536
1718
  }
2537
1719
 
2538
1720
  var conversationWithCloudAdapter_browser = /*#__PURE__*/Object.freeze({
@@ -2549,5 +1731,5 @@ var conversationWithCloudAdapter_browser = /*#__PURE__*/Object.freeze({
2549
1731
  CardActionBot: CardActionBot
2550
1732
  });
2551
1733
 
2552
- export { AdaptiveCardResponse, ApiKeyLocation, ApiKeyProvider, AppCredential, BasicAuthProvider, BearerTokenAuthProvider, conversationWithCloudAdapter_browser as BotBuilderCloudAdapter, BotSsoExecutionDialog, CardActionBot$1 as CardActionBot, CertificateAuthProvider, Channel$1 as Channel, CommandBot$1 as CommandBot, ConversationBot$1 as ConversationBot, ErrorCode, ErrorWithCode, IdentityType, InvokeResponseErrorCode, LogLevel, Member$1 as Member, MsGraphAuthProvider, NotificationBot$1 as NotificationBot, NotificationTargetType, OnBehalfOfUserCredential, TeamsBotInstallation$1 as TeamsBotInstallation, TeamsBotSsoPrompt, TeamsFx, TeamsUserCredential, createApiClient, createMicrosoftGraphClient, createMicrosoftGraphClientWithCredential, createPemCertOption, createPfxCertOption, getLogLevel, getTediousConnectionConfig, handleMessageExtensionQueryWithSSO, handleMessageExtensionQueryWithToken, sendAdaptiveCard$1 as sendAdaptiveCard, sendMessage$1 as sendMessage, setLogFunction, setLogLevel, setLogger };
1734
+ export { AdaptiveCardResponse, ApiKeyLocation, ApiKeyProvider, AppCredential, BasicAuthProvider, BearerTokenAuthProvider, conversationWithCloudAdapter_browser as BotBuilderCloudAdapter, BotSsoExecutionDialog, CertificateAuthProvider, ErrorCode, ErrorWithCode, InvokeResponseErrorCode, LogLevel, NotificationTargetType, OnBehalfOfUserCredential, TeamsBotSsoPrompt, TeamsUserCredential, createApiClient, createPemCertOption, createPfxCertOption, getLogLevel, handleMessageExtensionQueryWithSSO, setLogFunction, setLogLevel, setLogger };
2553
1735
  //# sourceMappingURL=index.esm2017.js.map