@microsoft/teamsfx 0.6.2-alpha.eb3c5cc12.0 → 0.6.3-alpha.266fa3b9f.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.
@@ -3,9 +3,13 @@ import { ConfidentialClientApplication } from '@azure/msal-node';
3
3
  import { createHash } from 'crypto';
4
4
  import { Client } from '@microsoft/microsoft-graph-client';
5
5
  import { ManagedIdentityCredential } from '@azure/identity';
6
- import { ActivityTypes, Channels, TeamsInfo, CardFactory, ActionTypes, MessageFactory, StatusCodes, verifyStateOperationName, tokenExchangeOperationName } from 'botbuilder';
6
+ import { ActivityTypes, Channels, TeamsInfo, CardFactory, ActionTypes, MessageFactory, StatusCodes, verifyStateOperationName, tokenExchangeOperationName, TurnContext, BotFrameworkAdapter } from 'botbuilder';
7
7
  import { Dialog } from 'botbuilder-dialogs';
8
8
  import { v4 } from 'uuid';
9
+ import axios from 'axios';
10
+ import { Agent } from 'https';
11
+ import * as path from 'path';
12
+ import * as fs from 'fs';
9
13
 
10
14
  // Copyright (c) Microsoft Corporation.
11
15
  // Licensed under the MIT license.
@@ -67,6 +71,10 @@ var ErrorCode;
67
71
  * Identity type error.
68
72
  */
69
73
  ErrorCode["IdentityTypeNotSupported"] = "IdentityTypeNotSupported";
74
+ /**
75
+ * Authentication info already exists error.
76
+ */
77
+ ErrorCode["AuthorizationInfoAlreadyExists"] = "AuthorizationInfoAlreadyExists";
70
78
  })(ErrorCode || (ErrorCode = {}));
71
79
  /**
72
80
  * @internal
@@ -88,6 +96,14 @@ ErrorMessage.FailToAcquireTokenOnBehalfOfUser = "Failed to acquire access token
88
96
  ErrorMessage.OnlyMSTeamsChannelSupported = "{0} is only supported in MS Teams Channel";
89
97
  // IdentityTypeNotSupported Error
90
98
  ErrorMessage.IdentityTypeNotSupported = "{0} identity is not supported in {1}";
99
+ // AuthorizationInfoError
100
+ ErrorMessage.AuthorizationHeaderAlreadyExists = "Authorization header already exists!";
101
+ ErrorMessage.BasicCredentialAlreadyExists = "Basic credential already exists!";
102
+ // InvalidParameter Error
103
+ ErrorMessage.EmptyParameter = "Parameter {0} is empty";
104
+ ErrorMessage.DuplicateHttpsOptionProperty = "Axios HTTPS agent already defined value for property {0}";
105
+ ErrorMessage.DuplicateApiKeyInHeader = "The request already defined api key in request header with name {0}.";
106
+ ErrorMessage.DuplicateApiKeyInQueryParam = "The request already defined api key in query parameter with name {0}.";
91
107
  /**
92
108
  * Error class with code and message thrown by the SDK.
93
109
  *
@@ -1386,6 +1402,322 @@ class TeamsBotSsoPrompt extends Dialog {
1386
1402
  }
1387
1403
 
1388
1404
  // Copyright (c) Microsoft Corporation.
1405
+ /**
1406
+ * Initializes new Axios instance with specific auth provider
1407
+ *
1408
+ * @param apiEndpoint - Base url of the API
1409
+ * @param authProvider - Auth provider that injects authentication info to each request
1410
+ * @returns axios instance configured with specfic auth provider
1411
+ *
1412
+ * @example
1413
+ * ```typescript
1414
+ * const client = createApiClient("https://my-api-endpoint-base-url", new BasicAuthProvider("xxx","xxx"));
1415
+ * ```
1416
+ *
1417
+ * @beta
1418
+ */
1419
+ function createApiClient(apiEndpoint, authProvider) {
1420
+ // Add a request interceptor
1421
+ const instance = axios.create({
1422
+ baseURL: apiEndpoint,
1423
+ });
1424
+ instance.interceptors.request.use(async function (config) {
1425
+ return await authProvider.AddAuthenticationInfo(config);
1426
+ });
1427
+ return instance;
1428
+ }
1429
+
1430
+ // Copyright (c) Microsoft Corporation.
1431
+ /**
1432
+ * Provider that handles Bearer Token authentication
1433
+ *
1434
+ * @beta
1435
+ */
1436
+ class BearerTokenAuthProvider {
1437
+ /**
1438
+ * @param { () => Promise<string> } getToken - Function that returns the content of bearer token used in http request
1439
+ *
1440
+ * @beta
1441
+ */
1442
+ constructor(getToken) {
1443
+ this.getToken = getToken;
1444
+ }
1445
+ /**
1446
+ * Adds authentication info to http requests
1447
+ *
1448
+ * @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.
1449
+ * Refer https://axios-http.com/docs/req_config for detailed document.
1450
+ *
1451
+ * @returns Updated axios request config.
1452
+ *
1453
+ * @throws {@link ErrorCode|AuthorizationInfoAlreadyExists} - when Authorization header already exists in request configuration.
1454
+ *
1455
+ * @beta
1456
+ */
1457
+ async AddAuthenticationInfo(config) {
1458
+ const token = await this.getToken();
1459
+ if (!config.headers) {
1460
+ config.headers = {};
1461
+ }
1462
+ if (config.headers["Authorization"]) {
1463
+ throw new ErrorWithCode(ErrorMessage.AuthorizationHeaderAlreadyExists, ErrorCode.AuthorizationInfoAlreadyExists);
1464
+ }
1465
+ config.headers["Authorization"] = `Bearer ${token}`;
1466
+ return config;
1467
+ }
1468
+ }
1469
+
1470
+ // Copyright (c) Microsoft Corporation.
1471
+ /**
1472
+ * Provider that handles Basic authentication
1473
+ *
1474
+ * @beta
1475
+ */
1476
+ class BasicAuthProvider {
1477
+ /**
1478
+ *
1479
+ * @param { string } userName - Username used in basic auth
1480
+ * @param { string } password - Password used in basic auth
1481
+ *
1482
+ * @throws {@link ErrorCode|InvalidParameter} - when username or password is empty.
1483
+ *
1484
+ * @beta
1485
+ */
1486
+ constructor(userName, password) {
1487
+ if (!userName) {
1488
+ throw new ErrorWithCode(formatString(ErrorMessage.EmptyParameter, "username"), ErrorCode.InvalidParameter);
1489
+ }
1490
+ if (!password) {
1491
+ throw new ErrorWithCode(formatString(ErrorMessage.EmptyParameter, "password"), ErrorCode.InvalidParameter);
1492
+ }
1493
+ this.userName = userName;
1494
+ this.password = password;
1495
+ }
1496
+ /**
1497
+ * Adds authentication info to http requests
1498
+ *
1499
+ * @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.
1500
+ * Refer https://axios-http.com/docs/req_config for detailed document.
1501
+ *
1502
+ * @returns Updated axios request config.
1503
+ *
1504
+ * @throws {@link ErrorCode|AuthorizationInfoAlreadyExists} - when Authorization header or auth property already exists in request configuration.
1505
+ *
1506
+ * @beta
1507
+ */
1508
+ async AddAuthenticationInfo(config) {
1509
+ if (config.headers && config.headers["Authorization"]) {
1510
+ throw new ErrorWithCode(ErrorMessage.AuthorizationHeaderAlreadyExists, ErrorCode.AuthorizationInfoAlreadyExists);
1511
+ }
1512
+ if (config.auth) {
1513
+ throw new ErrorWithCode(ErrorMessage.BasicCredentialAlreadyExists, ErrorCode.AuthorizationInfoAlreadyExists);
1514
+ }
1515
+ config.auth = {
1516
+ username: this.userName,
1517
+ password: this.password,
1518
+ };
1519
+ return config;
1520
+ }
1521
+ }
1522
+
1523
+ // Copyright (c) Microsoft Corporation.
1524
+ /**
1525
+ * Provider that handles API Key authentication
1526
+ *
1527
+ * @beta
1528
+ */
1529
+ class ApiKeyProvider {
1530
+ /**
1531
+ *
1532
+ * @param { string } keyName - The name of request header or query parameter that specifies API Key
1533
+ * @param { string } keyValue - The value of API Key
1534
+ * @param { ApiKeyLocation } keyLocation - The location of API Key: request header or query parameter.
1535
+ *
1536
+ * @throws {@link ErrorCode|InvalidParameter} - when key name or key value is empty.
1537
+ *
1538
+ * @beta
1539
+ */
1540
+ constructor(keyName, keyValue, keyLocation) {
1541
+ if (!keyName) {
1542
+ throw new ErrorWithCode(formatString(ErrorMessage.EmptyParameter, "keyName"), ErrorCode.InvalidParameter);
1543
+ }
1544
+ if (!keyValue) {
1545
+ throw new ErrorWithCode(formatString(ErrorMessage.EmptyParameter, "keyVaule"), ErrorCode.InvalidParameter);
1546
+ }
1547
+ this.keyName = keyName;
1548
+ this.keyValue = keyValue;
1549
+ this.keyLocation = keyLocation;
1550
+ }
1551
+ /**
1552
+ * Adds authentication info to http requests
1553
+ *
1554
+ * @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.
1555
+ * Refer https://axios-http.com/docs/req_config for detailed document.
1556
+ *
1557
+ * @returns Updated axios request config.
1558
+ *
1559
+ * @throws {@link ErrorCode|AuthorizationInfoAlreadyExists} - when API key already exists in request header or url query parameter.
1560
+ *
1561
+ * @beta
1562
+ */
1563
+ async AddAuthenticationInfo(config) {
1564
+ switch (this.keyLocation) {
1565
+ case ApiKeyLocation.Header:
1566
+ if (!config.headers) {
1567
+ config.headers = {};
1568
+ }
1569
+ if (config.headers[this.keyName]) {
1570
+ throw new ErrorWithCode(formatString(ErrorMessage.DuplicateApiKeyInHeader, this.keyName), ErrorCode.AuthorizationInfoAlreadyExists);
1571
+ }
1572
+ config.headers[this.keyName] = this.keyValue;
1573
+ break;
1574
+ case ApiKeyLocation.QueryParams:
1575
+ if (!config.params) {
1576
+ config.params = {};
1577
+ }
1578
+ const url = new URL(config.url, config.baseURL);
1579
+ if (config.params[this.keyName] || url.searchParams.has(this.keyName)) {
1580
+ throw new ErrorWithCode(formatString(ErrorMessage.DuplicateApiKeyInQueryParam, this.keyName), ErrorCode.AuthorizationInfoAlreadyExists);
1581
+ }
1582
+ config.params[this.keyName] = this.keyValue;
1583
+ break;
1584
+ }
1585
+ return config;
1586
+ }
1587
+ }
1588
+ /**
1589
+ * Define available location for API Key location
1590
+ *
1591
+ * @beta
1592
+ */
1593
+ var ApiKeyLocation;
1594
+ (function (ApiKeyLocation) {
1595
+ /**
1596
+ * The API Key is placed in request header
1597
+ */
1598
+ ApiKeyLocation[ApiKeyLocation["Header"] = 0] = "Header";
1599
+ /**
1600
+ * The API Key is placed in query parameter
1601
+ */
1602
+ ApiKeyLocation[ApiKeyLocation["QueryParams"] = 1] = "QueryParams";
1603
+ })(ApiKeyLocation || (ApiKeyLocation = {}));
1604
+
1605
+ // Copyright (c) Microsoft Corporation.
1606
+ /**
1607
+ * Provider that handles Certificate authentication
1608
+ *
1609
+ * @beta
1610
+ */
1611
+ class CertificateAuthProvider {
1612
+ /**
1613
+ *
1614
+ * @param { SecureContextOptions } certOption - information about the cert used in http requests
1615
+ *
1616
+ * @throws {@link ErrorCode|InvalidParameter} - when cert option is empty.
1617
+ *
1618
+ * @beta
1619
+ */
1620
+ constructor(certOption) {
1621
+ if (certOption && Object.keys(certOption).length !== 0) {
1622
+ this.certOption = certOption;
1623
+ }
1624
+ else {
1625
+ throw new ErrorWithCode(formatString(ErrorMessage.EmptyParameter, "certOption"), ErrorCode.InvalidParameter);
1626
+ }
1627
+ }
1628
+ /**
1629
+ * Adds authentication info to http requests.
1630
+ *
1631
+ * @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.
1632
+ * Refer https://axios-http.com/docs/req_config for detailed document.
1633
+ *
1634
+ * @returns Updated axios request config.
1635
+ *
1636
+ * @throws {@link ErrorCode|InvalidParameter} - when custom httpsAgent in the request has duplicate properties with certOption provided in constructor.
1637
+ *
1638
+ * @beta
1639
+ */
1640
+ async AddAuthenticationInfo(config) {
1641
+ if (!config.httpsAgent) {
1642
+ config.httpsAgent = new Agent(this.certOption);
1643
+ }
1644
+ else {
1645
+ const existingProperties = new Set(Object.keys(config.httpsAgent.options));
1646
+ for (const property of Object.keys(this.certOption)) {
1647
+ if (existingProperties.has(property)) {
1648
+ throw new ErrorWithCode(formatString(ErrorMessage.DuplicateHttpsOptionProperty, property), ErrorCode.InvalidParameter);
1649
+ }
1650
+ }
1651
+ Object.assign(config.httpsAgent.options, this.certOption);
1652
+ }
1653
+ return config;
1654
+ }
1655
+ }
1656
+ /**
1657
+ * Helper to create SecureContextOptions from PEM format cert
1658
+ *
1659
+ * @param { string | Buffer } cert - The cert chain in PEM format
1660
+ * @param { string | Buffer } key - The private key for the cert chain
1661
+ * @param { string? } passphrase - The passphrase for private key
1662
+ * @param { string? | Buffer? } ca - Overrides the trusted CA certificates
1663
+ *
1664
+ * @returns Instance of SecureContextOptions
1665
+ *
1666
+ * @throws {@link ErrorCode|InvalidParameter} - when any parameter is empty
1667
+ *
1668
+ */
1669
+ function createPemCertOption(cert, key, passphrase, ca) {
1670
+ if (cert.length === 0) {
1671
+ throw new ErrorWithCode(formatString(ErrorMessage.EmptyParameter, "cert"), ErrorCode.InvalidParameter);
1672
+ }
1673
+ if (key.length === 0) {
1674
+ throw new ErrorWithCode(formatString(ErrorMessage.EmptyParameter, "key"), ErrorCode.InvalidParameter);
1675
+ }
1676
+ return {
1677
+ cert,
1678
+ key,
1679
+ passphrase,
1680
+ ca,
1681
+ };
1682
+ }
1683
+ /**
1684
+ * Helper to create SecureContextOptions from PFX format cert
1685
+ *
1686
+ * @param { string | Buffer } pfx - The content of .pfx file
1687
+ * @param { string? } passphrase - Optional. The passphrase of .pfx file
1688
+ *
1689
+ * @returns Instance of SecureContextOptions
1690
+ *
1691
+ * @throws {@link ErrorCode|InvalidParameter} - when any parameter is empty
1692
+ *
1693
+ */
1694
+ function createPfxCertOption(pfx, passphrase) {
1695
+ if (pfx.length === 0) {
1696
+ throw new ErrorWithCode(formatString(ErrorMessage.EmptyParameter, "pfx"), ErrorCode.InvalidParameter);
1697
+ }
1698
+ return {
1699
+ pfx,
1700
+ passphrase,
1701
+ };
1702
+ }
1703
+
1704
+ // Copyright (c) Microsoft Corporation.
1705
+ // Following keys are used by SDK internally
1706
+ const ReservedKey = new Set([
1707
+ "authorityHost",
1708
+ "tenantId",
1709
+ "clientId",
1710
+ "clientSecret",
1711
+ "initiateLoginEndpoint",
1712
+ "applicationIdUri",
1713
+ "apiEndpoint",
1714
+ "apiName",
1715
+ "sqlServerEndpoint",
1716
+ "sqlUsername",
1717
+ "sqlPassword",
1718
+ "sqlDatabaseName",
1719
+ "sqlIdentityId",
1720
+ ]);
1389
1721
  /**
1390
1722
  * A class providing credential and configuration.
1391
1723
  * @beta
@@ -1559,13 +1891,979 @@ class TeamsFx {
1559
1891
  this.configuration.set("sqlDatabaseName", env.SQL_DATABASE_NAME);
1560
1892
  this.configuration.set("sqlIdentityId", env.IDENTITY_ID);
1561
1893
  Object.keys(env).forEach((key) => {
1562
- const value = env[key];
1563
- if (key.startsWith("TEAMSFX_") && value) {
1564
- this.configuration.set(key.substring(8), value);
1894
+ if (ReservedKey.has(key)) {
1895
+ internalLogger.warn(`The name of environment variable ${key} is preserved. Will not load it as configuration.`);
1896
+ }
1897
+ this.configuration.set(key, env[key]);
1898
+ });
1899
+ }
1900
+ }
1901
+
1902
+ // Copyright (c) Microsoft Corporation.
1903
+ /**
1904
+ * @internal
1905
+ */
1906
+ var ActivityType;
1907
+ (function (ActivityType) {
1908
+ ActivityType[ActivityType["CurrentBotInstalled"] = 0] = "CurrentBotInstalled";
1909
+ ActivityType[ActivityType["CurrentBotMessaged"] = 1] = "CurrentBotMessaged";
1910
+ ActivityType[ActivityType["CurrentBotUninstalled"] = 2] = "CurrentBotUninstalled";
1911
+ ActivityType[ActivityType["TeamDeleted"] = 3] = "TeamDeleted";
1912
+ ActivityType[ActivityType["TeamRestored"] = 4] = "TeamRestored";
1913
+ ActivityType[ActivityType["Unknown"] = 5] = "Unknown";
1914
+ })(ActivityType || (ActivityType = {}));
1915
+ /**
1916
+ * @internal
1917
+ */
1918
+ class NotificationMiddleware {
1919
+ constructor(options) {
1920
+ this.conversationReferenceStore = options.conversationReferenceStore;
1921
+ }
1922
+ async onTurn(context, next) {
1923
+ const type = this.classifyActivity(context.activity);
1924
+ switch (type) {
1925
+ case ActivityType.CurrentBotInstalled:
1926
+ case ActivityType.TeamRestored: {
1927
+ const reference = TurnContext.getConversationReference(context.activity);
1928
+ await this.conversationReferenceStore.set(reference);
1929
+ break;
1930
+ }
1931
+ case ActivityType.CurrentBotUninstalled:
1932
+ case ActivityType.TeamDeleted: {
1933
+ const reference = TurnContext.getConversationReference(context.activity);
1934
+ await this.conversationReferenceStore.delete(reference);
1935
+ break;
1936
+ }
1937
+ }
1938
+ await next();
1939
+ }
1940
+ classifyActivity(activity) {
1941
+ var _a, _b;
1942
+ const activityType = activity.type;
1943
+ if (activityType === "installationUpdate") {
1944
+ const action = (_a = activity.action) === null || _a === void 0 ? void 0 : _a.toLowerCase();
1945
+ if (action === "add") {
1946
+ return ActivityType.CurrentBotInstalled;
1947
+ }
1948
+ else {
1949
+ return ActivityType.CurrentBotUninstalled;
1950
+ }
1951
+ }
1952
+ else if (activityType === "conversationUpdate") {
1953
+ const eventType = (_b = activity.channelData) === null || _b === void 0 ? void 0 : _b.eventType;
1954
+ if (eventType === "teamDeleted") {
1955
+ return ActivityType.TeamDeleted;
1956
+ }
1957
+ else if (eventType === "teamRestored") {
1958
+ return ActivityType.TeamRestored;
1959
+ }
1960
+ }
1961
+ return ActivityType.Unknown;
1962
+ }
1963
+ }
1964
+ class CommandResponseMiddleware {
1965
+ constructor(handlers) {
1966
+ this.commandHandlers = [];
1967
+ if (handlers && handlers.length > 0) {
1968
+ this.commandHandlers.push(...handlers);
1969
+ }
1970
+ }
1971
+ async onTurn(context, next) {
1972
+ const type = this.classifyActivity(context.activity);
1973
+ switch (type) {
1974
+ case ActivityType.CurrentBotMessaged:
1975
+ // Invoke corresponding command handler for the command response
1976
+ const commandText = this.getActivityText(context.activity);
1977
+ const message = {
1978
+ text: commandText,
1979
+ };
1980
+ for (const handler of this.commandHandlers) {
1981
+ const matchResult = this.shouldTrigger(handler.triggerPatterns, commandText);
1982
+ // It is important to note that the command bot will stop processing handlers
1983
+ // when the first command handler is matched.
1984
+ if (!!matchResult) {
1985
+ message.matches = Array.isArray(matchResult) ? matchResult : void 0;
1986
+ const response = await handler.handleCommandReceived(context, message);
1987
+ await context.sendActivity(response);
1988
+ break;
1989
+ }
1990
+ }
1991
+ break;
1992
+ }
1993
+ await next();
1994
+ }
1995
+ classifyActivity(activity) {
1996
+ if (activity.type === ActivityTypes.Message) {
1997
+ return ActivityType.CurrentBotMessaged;
1998
+ }
1999
+ return ActivityType.Unknown;
2000
+ }
2001
+ matchPattern(pattern, text) {
2002
+ if (text) {
2003
+ if (typeof pattern === "string") {
2004
+ const regExp = new RegExp(pattern, "i");
2005
+ return regExp.test(text);
2006
+ }
2007
+ if (pattern instanceof RegExp) {
2008
+ const matches = text.match(pattern);
2009
+ return matches !== null && matches !== void 0 ? matches : false;
2010
+ }
2011
+ }
2012
+ return false;
2013
+ }
2014
+ shouldTrigger(patterns, text) {
2015
+ const expressions = Array.isArray(patterns) ? patterns : [patterns];
2016
+ for (const ex of expressions) {
2017
+ const arg = this.matchPattern(ex, text);
2018
+ if (arg)
2019
+ return arg;
2020
+ }
2021
+ return false;
2022
+ }
2023
+ getActivityText(activity) {
2024
+ let text = activity.text;
2025
+ const removedMentionText = TurnContext.removeRecipientMention(activity);
2026
+ if (removedMentionText) {
2027
+ text = removedMentionText
2028
+ .toLowerCase()
2029
+ .replace(/\n|\r\n/g, "")
2030
+ .trim();
2031
+ }
2032
+ return text;
2033
+ }
2034
+ }
2035
+
2036
+ // Copyright (c) Microsoft Corporation.
2037
+ /**
2038
+ * A command bot for receiving commands and sending responses in Teams.
2039
+ *
2040
+ * @remarks
2041
+ * Ensure each command should ONLY be registered with the command once, otherwise it'll cause unexpected behavior if you register the same command more than once.
2042
+ *
2043
+ * @beta
2044
+ */
2045
+ class CommandBot {
2046
+ /**
2047
+ * Creates a new instance of the `CommandBot`.
2048
+ *
2049
+ * @param adapter The bound `BotFrameworkAdapter`.
2050
+ * @param options - initialize options
2051
+ *
2052
+ * @beta
2053
+ */
2054
+ constructor(adapter, options) {
2055
+ this.middleware = new CommandResponseMiddleware(options === null || options === void 0 ? void 0 : options.commands);
2056
+ this.adapter = adapter.use(this.middleware);
2057
+ }
2058
+ /**
2059
+ * Registers a command into the command bot.
2060
+ *
2061
+ * @param command The command to registered.
2062
+ *
2063
+ * @beta
2064
+ */
2065
+ registerCommand(command) {
2066
+ if (command) {
2067
+ this.middleware.commandHandlers.push(command);
2068
+ }
2069
+ }
2070
+ /**
2071
+ * Registers commands into the command bot.
2072
+ *
2073
+ * @param commands The command to registered.
2074
+ *
2075
+ * @beta
2076
+ */
2077
+ registerCommands(commands) {
2078
+ if (commands) {
2079
+ this.middleware.commandHandlers.push(...commands);
2080
+ }
2081
+ }
2082
+ }
2083
+
2084
+ // Copyright (c) Microsoft Corporation.
2085
+ /**
2086
+ * @internal
2087
+ */
2088
+ class LocalFileStorage {
2089
+ constructor(fileDir) {
2090
+ this.localFileName = ".notification.localstore.json";
2091
+ this.filePath = path.resolve(fileDir, this.localFileName);
2092
+ }
2093
+ async read(key) {
2094
+ if (!(await this.storeFileExists())) {
2095
+ return undefined;
2096
+ }
2097
+ const data = await this.readFromFile();
2098
+ return data[key];
2099
+ }
2100
+ async list() {
2101
+ if (!(await this.storeFileExists())) {
2102
+ return [];
2103
+ }
2104
+ const data = await this.readFromFile();
2105
+ return Object.entries(data).map((entry) => entry[1]);
2106
+ }
2107
+ async write(key, object) {
2108
+ if (!(await this.storeFileExists())) {
2109
+ await this.writeToFile({ [key]: object });
2110
+ return;
2111
+ }
2112
+ const data = await this.readFromFile();
2113
+ await this.writeToFile(Object.assign(data, { [key]: object }));
2114
+ }
2115
+ async delete(key) {
2116
+ if (await this.storeFileExists()) {
2117
+ const data = await this.readFromFile();
2118
+ if (data[key] !== undefined) {
2119
+ delete data[key];
2120
+ await this.writeToFile(data);
2121
+ }
2122
+ }
2123
+ }
2124
+ storeFileExists() {
2125
+ return new Promise((resolve) => {
2126
+ try {
2127
+ fs.access(this.filePath, (err) => {
2128
+ if (err) {
2129
+ resolve(false);
2130
+ }
2131
+ else {
2132
+ resolve(true);
2133
+ }
2134
+ });
2135
+ }
2136
+ catch (error) {
2137
+ resolve(false);
1565
2138
  }
1566
2139
  });
1567
2140
  }
2141
+ readFromFile() {
2142
+ return new Promise((resolve, reject) => {
2143
+ try {
2144
+ fs.readFile(this.filePath, { encoding: "utf-8" }, (err, rawData) => {
2145
+ if (err) {
2146
+ reject(err);
2147
+ }
2148
+ else {
2149
+ resolve(JSON.parse(rawData));
2150
+ }
2151
+ });
2152
+ }
2153
+ catch (error) {
2154
+ reject(error);
2155
+ }
2156
+ });
2157
+ }
2158
+ async writeToFile(data) {
2159
+ return new Promise((resolve, reject) => {
2160
+ try {
2161
+ const rawData = JSON.stringify(data, undefined, 2);
2162
+ fs.writeFile(this.filePath, rawData, { encoding: "utf-8" }, (err) => {
2163
+ if (err) {
2164
+ reject(err);
2165
+ }
2166
+ else {
2167
+ resolve();
2168
+ }
2169
+ });
2170
+ }
2171
+ catch (error) {
2172
+ reject(error);
2173
+ }
2174
+ });
2175
+ }
2176
+ }
2177
+ /**
2178
+ * @internal
2179
+ */
2180
+ class ConversationReferenceStore {
2181
+ constructor(storage) {
2182
+ this.storage = storage;
2183
+ }
2184
+ async check(reference) {
2185
+ const ref = await this.storage.read(this.getKey(reference));
2186
+ return ref !== undefined;
2187
+ }
2188
+ getAll() {
2189
+ return this.storage.list();
2190
+ }
2191
+ set(reference) {
2192
+ return this.storage.write(this.getKey(reference), reference);
2193
+ }
2194
+ delete(reference) {
2195
+ return this.storage.delete(this.getKey(reference));
2196
+ }
2197
+ getKey(reference) {
2198
+ var _a, _b;
2199
+ return `_${(_a = reference.conversation) === null || _a === void 0 ? void 0 : _a.tenantId}_${(_b = reference.conversation) === null || _b === void 0 ? void 0 : _b.id}`;
2200
+ }
2201
+ }
2202
+
2203
+ // Copyright (c) Microsoft Corporation.
2204
+ // Licensed under the MIT license.
2205
+ /**
2206
+ * @internal
2207
+ */
2208
+ function cloneConversation(conversation) {
2209
+ return Object.assign({}, conversation);
2210
+ }
2211
+ /**
2212
+ * @internal
2213
+ */
2214
+ function getTargetType(conversationReference) {
2215
+ var _a;
2216
+ const conversationType = (_a = conversationReference.conversation) === null || _a === void 0 ? void 0 : _a.conversationType;
2217
+ if (conversationType === "personal") {
2218
+ return "Person";
2219
+ }
2220
+ else if (conversationType === "groupChat") {
2221
+ return "Group";
2222
+ }
2223
+ else if (conversationType === "channel") {
2224
+ return "Channel";
2225
+ }
2226
+ else {
2227
+ return undefined;
2228
+ }
2229
+ }
2230
+ /**
2231
+ * @internal
2232
+ */
2233
+ function getTeamsBotInstallationId(context) {
2234
+ var _a, _b, _c, _d;
2235
+ return (_d = (_c = (_b = (_a = context.activity) === null || _a === void 0 ? void 0 : _a.channelData) === null || _b === void 0 ? void 0 : _b.team) === null || _c === void 0 ? void 0 : _c.id) !== null && _d !== void 0 ? _d : context.activity.conversation.id;
2236
+ }
2237
+
2238
+ // Copyright (c) Microsoft Corporation.
2239
+ /**
2240
+ * Send a plain text message to a notification target.
2241
+ *
2242
+ * @param target - the notification target.
2243
+ * @param text - the plain text message.
2244
+ * @returns A `Promise` representing the asynchronous operation.
2245
+ *
2246
+ * @beta
2247
+ */
2248
+ function sendMessage(target, text) {
2249
+ return target.sendMessage(text);
2250
+ }
2251
+ /**
2252
+ * Send an adaptive card message to a notification target.
2253
+ *
2254
+ * @param target - the notification target.
2255
+ * @param card - the adaptive card raw JSON.
2256
+ * @returns A `Promise` representing the asynchronous operation.
2257
+ *
2258
+ * @beta
2259
+ */
2260
+ function sendAdaptiveCard(target, card) {
2261
+ return target.sendAdaptiveCard(card);
2262
+ }
2263
+ /**
2264
+ * A {@link NotificationTarget} that represents a team channel.
2265
+ *
2266
+ * @remarks
2267
+ * It's recommended to get channels from {@link TeamsBotInstallation.channels()}.
2268
+ *
2269
+ * @beta
2270
+ */
2271
+ class Channel {
2272
+ /**
2273
+ * Constuctor.
2274
+ *
2275
+ * @remarks
2276
+ * It's recommended to get channels from {@link TeamsBotInstallation.channels()}, instead of using this constructor.
2277
+ *
2278
+ * @param parent - The parent {@link TeamsBotInstallation} where this channel is created from.
2279
+ * @param info - Detailed channel information.
2280
+ *
2281
+ * @beta
2282
+ */
2283
+ constructor(parent, info) {
2284
+ /**
2285
+ * Notification target type. For channel it's always "Channel".
2286
+ *
2287
+ * @beta
2288
+ */
2289
+ this.type = "Channel";
2290
+ this.parent = parent;
2291
+ this.info = info;
2292
+ }
2293
+ /**
2294
+ * Send a plain text message.
2295
+ *
2296
+ * @param text - the plain text message.
2297
+ * @returns A `Promise` representing the asynchronous operation.
2298
+ *
2299
+ * @beta
2300
+ */
2301
+ sendMessage(text) {
2302
+ return this.parent.adapter.continueConversation(this.parent.conversationReference, async (context) => {
2303
+ const conversation = await this.newConversation(context);
2304
+ await this.parent.adapter.continueConversation(conversation, async (ctx) => {
2305
+ await ctx.sendActivity(text);
2306
+ });
2307
+ });
2308
+ }
2309
+ /**
2310
+ * Send an adaptive card message.
2311
+ *
2312
+ * @param card - the adaptive card raw JSON.
2313
+ * @returns A `Promise` representing the asynchronous operation.
2314
+ *
2315
+ * @beta
2316
+ */
2317
+ async sendAdaptiveCard(card) {
2318
+ return this.parent.adapter.continueConversation(this.parent.conversationReference, async (context) => {
2319
+ const conversation = await this.newConversation(context);
2320
+ await this.parent.adapter.continueConversation(conversation, async (ctx) => {
2321
+ await ctx.sendActivity({
2322
+ attachments: [CardFactory.adaptiveCard(card)],
2323
+ });
2324
+ });
2325
+ });
2326
+ }
2327
+ /**
2328
+ * @internal
2329
+ */
2330
+ async newConversation(context) {
2331
+ const reference = TurnContext.getConversationReference(context.activity);
2332
+ const channelConversation = cloneConversation(reference);
2333
+ channelConversation.conversation.id = this.info.id || "";
2334
+ return channelConversation;
2335
+ }
2336
+ }
2337
+ /**
2338
+ * A {@link NotificationTarget} that represents a team member.
2339
+ *
2340
+ * @remarks
2341
+ * It's recommended to get members from {@link TeamsBotInstallation.members()}.
2342
+ *
2343
+ * @beta
2344
+ */
2345
+ class Member {
2346
+ /**
2347
+ * Constuctor.
2348
+ *
2349
+ * @remarks
2350
+ * It's recommended to get members from {@link TeamsBotInstallation.members()}, instead of using this constructor.
2351
+ *
2352
+ * @param parent - The parent {@link TeamsBotInstallation} where this member is created from.
2353
+ * @param account - Detailed member account information.
2354
+ *
2355
+ * @beta
2356
+ */
2357
+ constructor(parent, account) {
2358
+ /**
2359
+ * Notification target type. For member it's always "Person".
2360
+ *
2361
+ * @beta
2362
+ */
2363
+ this.type = "Person";
2364
+ this.parent = parent;
2365
+ this.account = account;
2366
+ }
2367
+ /**
2368
+ * Send a plain text message.
2369
+ *
2370
+ * @param text - the plain text message.
2371
+ * @returns A `Promise` representing the asynchronous operation.
2372
+ *
2373
+ * @beta
2374
+ */
2375
+ sendMessage(text) {
2376
+ return this.parent.adapter.continueConversation(this.parent.conversationReference, async (context) => {
2377
+ const conversation = await this.newConversation(context);
2378
+ await this.parent.adapter.continueConversation(conversation, async (ctx) => {
2379
+ await ctx.sendActivity(text);
2380
+ });
2381
+ });
2382
+ }
2383
+ /**
2384
+ * Send an adaptive card message.
2385
+ *
2386
+ * @param card - the adaptive card raw JSON.
2387
+ * @returns A `Promise` representing the asynchronous operation.
2388
+ *
2389
+ * @beta
2390
+ */
2391
+ async sendAdaptiveCard(card) {
2392
+ return this.parent.adapter.continueConversation(this.parent.conversationReference, async (context) => {
2393
+ const conversation = await this.newConversation(context);
2394
+ await this.parent.adapter.continueConversation(conversation, async (ctx) => {
2395
+ await ctx.sendActivity({
2396
+ attachments: [CardFactory.adaptiveCard(card)],
2397
+ });
2398
+ });
2399
+ });
2400
+ }
2401
+ /**
2402
+ * @internal
2403
+ */
2404
+ async newConversation(context) {
2405
+ const reference = TurnContext.getConversationReference(context.activity);
2406
+ const personalConversation = cloneConversation(reference);
2407
+ const connectorClient = context.turnState.get(this.parent.adapter.ConnectorClientKey);
2408
+ const conversation = await connectorClient.conversations.createConversation({
2409
+ isGroup: false,
2410
+ tenantId: context.activity.conversation.tenantId,
2411
+ bot: context.activity.recipient,
2412
+ members: [this.account],
2413
+ channelData: {},
2414
+ });
2415
+ personalConversation.conversation.id = conversation.id;
2416
+ return personalConversation;
2417
+ }
2418
+ }
2419
+ /**
2420
+ * A {@link NotificationTarget} that represents a bot installation. Teams Bot could be installed into
2421
+ * - Personal chat
2422
+ * - Group chat
2423
+ * - Team (by default the `General` channel)
2424
+ *
2425
+ * @remarks
2426
+ * It's recommended to get bot installations from {@link ConversationBot.installations()}.
2427
+ *
2428
+ * @beta
2429
+ */
2430
+ class TeamsBotInstallation {
2431
+ /**
2432
+ * Constructor
2433
+ *
2434
+ * @remarks
2435
+ * It's recommended to get bot installations from {@link ConversationBot.installations()}, instead of using this constructor.
2436
+ *
2437
+ * @param adapter - the bound `BotFrameworkAdapter`.
2438
+ * @param conversationReference - the bound `ConversationReference`.
2439
+ *
2440
+ * @beta
2441
+ */
2442
+ constructor(adapter, conversationReference) {
2443
+ this.adapter = adapter;
2444
+ this.conversationReference = conversationReference;
2445
+ this.type = getTargetType(conversationReference);
2446
+ }
2447
+ /**
2448
+ * Send a plain text message.
2449
+ *
2450
+ * @param text - the plain text message.
2451
+ * @returns A `Promise` representing the asynchronous operation.
2452
+ *
2453
+ * @beta
2454
+ */
2455
+ sendMessage(text) {
2456
+ return this.adapter.continueConversation(this.conversationReference, async (context) => {
2457
+ await context.sendActivity(text);
2458
+ });
2459
+ }
2460
+ /**
2461
+ * Send an adaptive card message.
2462
+ *
2463
+ * @param card - the adaptive card raw JSON.
2464
+ * @returns A `Promise` representing the asynchronous operation.
2465
+ *
2466
+ * @beta
2467
+ */
2468
+ sendAdaptiveCard(card) {
2469
+ return this.adapter.continueConversation(this.conversationReference, async (context) => {
2470
+ await context.sendActivity({
2471
+ attachments: [CardFactory.adaptiveCard(card)],
2472
+ });
2473
+ });
2474
+ }
2475
+ /**
2476
+ * Get channels from this bot installation.
2477
+ *
2478
+ * @returns an array of channels if bot is installed into a team, otherwise returns an empty array.
2479
+ *
2480
+ * @beta
2481
+ */
2482
+ async channels() {
2483
+ let teamsChannels = [];
2484
+ await this.adapter.continueConversation(this.conversationReference, async (context) => {
2485
+ const teamId = getTeamsBotInstallationId(context);
2486
+ if (teamId !== undefined) {
2487
+ teamsChannels = await TeamsInfo.getTeamChannels(context, teamId);
2488
+ }
2489
+ });
2490
+ const channels = [];
2491
+ for (const channel of teamsChannels) {
2492
+ channels.push(new Channel(this, channel));
2493
+ }
2494
+ return channels;
2495
+ }
2496
+ /**
2497
+ * Get members from this bot installation.
2498
+ *
2499
+ * @returns an array of members from where the bot is installed.
2500
+ *
2501
+ * @beta
2502
+ */
2503
+ async members() {
2504
+ const members = [];
2505
+ await this.adapter.continueConversation(this.conversationReference, async (context) => {
2506
+ let continuationToken;
2507
+ do {
2508
+ const pagedMembers = await TeamsInfo.getPagedMembers(context, undefined, continuationToken);
2509
+ continuationToken = pagedMembers.continuationToken;
2510
+ for (const member of pagedMembers.members) {
2511
+ members.push(new Member(this, member));
2512
+ }
2513
+ } while (continuationToken !== undefined);
2514
+ });
2515
+ return members;
2516
+ }
2517
+ }
2518
+ /**
2519
+ * Provide utilities to send notification to varies targets (e.g., member, group, channel).
2520
+ *
2521
+ * @beta
2522
+ */
2523
+ class NotificationBot {
2524
+ /**
2525
+ * constructor of the notification bot.
2526
+ *
2527
+ * @remarks
2528
+ * To ensure accuracy, it's recommended to initialize before handling any message.
2529
+ *
2530
+ * @param adapter - the bound `BotFrameworkAdapter`
2531
+ * @param options - initialize options
2532
+ *
2533
+ * @beta
2534
+ */
2535
+ constructor(adapter, options) {
2536
+ var _a, _b;
2537
+ const storage = (_a = options === null || options === void 0 ? void 0 : options.storage) !== null && _a !== void 0 ? _a : new LocalFileStorage(path.resolve(process.env.RUNNING_ON_AZURE === "1" ? (_b = process.env.TEMP) !== null && _b !== void 0 ? _b : "./" : "./"));
2538
+ this.conversationReferenceStore = new ConversationReferenceStore(storage);
2539
+ this.adapter = adapter.use(new NotificationMiddleware({
2540
+ conversationReferenceStore: this.conversationReferenceStore,
2541
+ }));
2542
+ }
2543
+ /**
2544
+ * Get all targets where the bot is installed.
2545
+ *
2546
+ * @remarks
2547
+ * The result is retrieving from the persisted storage.
2548
+ *
2549
+ * @returns - an array of {@link TeamsBotInstallation}.
2550
+ *
2551
+ * @beta
2552
+ */
2553
+ async installations() {
2554
+ if (this.conversationReferenceStore === undefined || this.adapter === undefined) {
2555
+ throw new Error("NotificationBot has not been initialized.");
2556
+ }
2557
+ const references = (await this.conversationReferenceStore.getAll()).values();
2558
+ const targets = [];
2559
+ for (const reference of references) {
2560
+ // validate connection
2561
+ let valid = true;
2562
+ this.adapter.continueConversation(reference, async (context) => {
2563
+ try {
2564
+ // try get member to see if the installation is still valid
2565
+ await TeamsInfo.getPagedMembers(context, 1);
2566
+ }
2567
+ catch (error) {
2568
+ if (error.code === "BotNotInConversationRoster") {
2569
+ valid = false;
2570
+ }
2571
+ }
2572
+ });
2573
+ if (valid) {
2574
+ targets.push(new TeamsBotInstallation(this.adapter, reference));
2575
+ }
2576
+ else {
2577
+ this.conversationReferenceStore.delete(reference);
2578
+ }
2579
+ }
2580
+ return targets;
2581
+ }
2582
+ }
2583
+
2584
+ // Copyright (c) Microsoft Corporation.
2585
+ /**
2586
+ * Provide utilities for bot conversation, including:
2587
+ * - handle command and response.
2588
+ * - send notification to varies targets (e.g., member, group, channel).
2589
+ *
2590
+ * @example
2591
+ * For command and response, you can register your commands through the constructor, or use the `registerCommand` and `registerCommands` API to add commands later.
2592
+ *
2593
+ * ```typescript
2594
+ * // register through constructor
2595
+ * const conversationBot = new ConversationBot({
2596
+ * command: {
2597
+ * enabled: true,
2598
+ * commands: [ new HelloWorldCommandHandler() ],
2599
+ * },
2600
+ * });
2601
+ *
2602
+ * // register through `register*` API
2603
+ * conversationBot.command.registerCommand(new HelpCommandHandler());
2604
+ * ```
2605
+ *
2606
+ * For notification, you can enable notification at initialization, then send notifications at any time.
2607
+ *
2608
+ * ```typescript
2609
+ * // enable through constructor
2610
+ * const conversationBot = new ConversationBot({
2611
+ * notification: {
2612
+ * enabled: true,
2613
+ * },
2614
+ * });
2615
+ *
2616
+ * // get all bot installations and send message
2617
+ * for (const target of await conversationBot.notification.installations()) {
2618
+ * await target.sendMessage("Hello Notification");
2619
+ * }
2620
+ *
2621
+ * // alternative - send message to all members
2622
+ * for (const target of await conversationBot.notification.installations()) {
2623
+ * for (const member of await target.members()) {
2624
+ * await member.sendMessage("Hello Notification");
2625
+ * }
2626
+ * }
2627
+ * ```
2628
+ *
2629
+ * @remarks
2630
+ * Set `adapter` in {@link ConversationOptions} to use your own bot adapter.
2631
+ *
2632
+ * For command and response, ensure each command should ONLY be registered with the command once, otherwise it'll cause unexpected behavior if you register the same command more than once.
2633
+ *
2634
+ * For notification, set `notification.storage` in {@link ConversationOptions} to use your own storage implementation.
2635
+ *
2636
+ * @beta
2637
+ */
2638
+ class ConversationBot {
2639
+ /**
2640
+ * Creates new instance of the `ConversationBot`.
2641
+ *
2642
+ * @remarks
2643
+ * It's recommended to create your own adapter and storage for production environment instead of the default one.
2644
+ *
2645
+ * @param options - initialize options
2646
+ *
2647
+ * @beta
2648
+ */
2649
+ constructor(options) {
2650
+ var _a, _b;
2651
+ if (options.adapter) {
2652
+ this.adapter = options.adapter;
2653
+ }
2654
+ else {
2655
+ this.adapter = this.createDefaultAdapter(options.adapterConfig);
2656
+ }
2657
+ if ((_a = options.command) === null || _a === void 0 ? void 0 : _a.enabled) {
2658
+ this.command = new CommandBot(this.adapter, options.command);
2659
+ }
2660
+ if ((_b = options.notification) === null || _b === void 0 ? void 0 : _b.enabled) {
2661
+ this.notification = new NotificationBot(this.adapter, options.notification);
2662
+ }
2663
+ }
2664
+ createDefaultAdapter(adapterConfig) {
2665
+ const adapter = adapterConfig === undefined
2666
+ ? new BotFrameworkAdapter({
2667
+ appId: process.env.BOT_ID,
2668
+ appPassword: process.env.BOT_PASSWORD,
2669
+ })
2670
+ : new BotFrameworkAdapter(adapterConfig);
2671
+ // the default error handler
2672
+ adapter.onTurnError = async (context, error) => {
2673
+ // This check writes out errors to console.
2674
+ console.error(`[onTurnError] unhandled error: ${error}`);
2675
+ // Send a trace activity, which will be displayed in Bot Framework Emulator
2676
+ await context.sendTraceActivity("OnTurnError Trace", `${error}`, "https://www.botframework.com/schemas/error", "TurnError");
2677
+ // Send a message to the user
2678
+ await context.sendActivity(`The bot encountered unhandled error: ${error.message}`);
2679
+ await context.sendActivity("To continue to run this bot, please fix the bot source code.");
2680
+ };
2681
+ return adapter;
2682
+ }
2683
+ /**
2684
+ * The request handler to integrate with web request.
2685
+ *
2686
+ * @param req - an Express or Restify style request object.
2687
+ * @param res - an Express or Restify style response object.
2688
+ * @param logic - the additional function to handle bot context.
2689
+ *
2690
+ * @example
2691
+ * For example, to use with Restify:
2692
+ * ``` typescript
2693
+ * // The default/empty behavior
2694
+ * server.post("api/messages", conversationBot.requestHandler);
2695
+ *
2696
+ * // Or, add your own logic
2697
+ * server.post("api/messages", async (req, res) => {
2698
+ * await conversationBot.requestHandler(req, res, async (context) => {
2699
+ * // your-own-context-logic
2700
+ * });
2701
+ * });
2702
+ * ```
2703
+ *
2704
+ * @beta
2705
+ */
2706
+ async requestHandler(req, res, logic) {
2707
+ if (logic === undefined) {
2708
+ // create empty logic
2709
+ logic = async () => { };
2710
+ }
2711
+ await this.adapter.processActivity(req, res, logic);
2712
+ }
2713
+ }
2714
+
2715
+ // Copyright (c) Microsoft Corporation.
2716
+ const { AdaptiveCards } = require("@microsoft/adaptivecards-tools");
2717
+ /**
2718
+ * Provides utility method to build bot message with cards that supported in Teams.
2719
+ */
2720
+ class MessageBuilder {
2721
+ /**
2722
+ * Build a bot message activity attached with adaptive card.
2723
+ *
2724
+ * @param cardTemplate The adaptive card template.
2725
+ * @param data card data used to render the template.
2726
+ * @returns A bot message activity attached with an adaptive card.
2727
+ *
2728
+ * @example
2729
+ * ```javascript
2730
+ * const cardTemplate = {
2731
+ * type: "AdaptiveCard",
2732
+ * body: [
2733
+ * {
2734
+ * "type": "TextBlock",
2735
+ * "text": "${title}",
2736
+ * "size": "Large"
2737
+ * },
2738
+ * {
2739
+ * "type": "TextBlock",
2740
+ * "text": "${description}"
2741
+ * }],
2742
+ * $schema: "http://adaptivecards.io/schemas/adaptive-card.json",
2743
+ * version: "1.4"
2744
+ * };
2745
+ *
2746
+ * type CardData = {
2747
+ * title: string,
2748
+ * description: string
2749
+ * };
2750
+ * const card = MessageBuilder.attachAdaptiveCard<CardData>(
2751
+ * cardTemplate, {
2752
+ * title: "sample card title",
2753
+ * description: "sample card description"
2754
+ * });
2755
+ * ```
2756
+ *
2757
+ * @beta
2758
+ */
2759
+ static attachAdaptiveCard(cardTemplate, data) {
2760
+ return {
2761
+ attachments: [CardFactory.adaptiveCard(AdaptiveCards.declare(cardTemplate).render(data))],
2762
+ };
2763
+ }
2764
+ /**
2765
+ * Build a bot message activity attached with an adaptive card.
2766
+ *
2767
+ * @param card The adaptive card content.
2768
+ * @returns A bot message activity attached with an adaptive card.
2769
+ *
2770
+ * @beta
2771
+ */
2772
+ static attachAdaptiveCardWithoutData(card) {
2773
+ return {
2774
+ attachments: [CardFactory.adaptiveCard(AdaptiveCards.declareWithoutData(card).render())],
2775
+ };
2776
+ }
2777
+ /**
2778
+ * Build a bot message activity attached with an hero card.
2779
+ *
2780
+ * @param title The card title.
2781
+ * @param images Optional. The array of images to include on the card.
2782
+ * @param buttons Optional. The array of buttons to include on the card. Each `string` in the array
2783
+ * is converted to an `imBack` button with a title and value set to the value of the string.
2784
+ * @param other Optional. Any additional properties to include on the card.
2785
+ *
2786
+ * @returns A bot message activity attached with a hero card.
2787
+ *
2788
+ * @example
2789
+ * ```javascript
2790
+ * const message = MessageBuilder.attachHeroCard(
2791
+ * 'sample title',
2792
+ * ['https://example.com/sample.jpg'],
2793
+ * ['action']
2794
+ * );
2795
+ * ```
2796
+ *
2797
+ * @beta
2798
+ */
2799
+ static attachHeroCard(title, images, buttons, other) {
2800
+ return MessageBuilder.attachContent(CardFactory.heroCard(title, images, buttons, other));
2801
+ }
2802
+ /**
2803
+ * Returns an attachment for a sign-in card.
2804
+ *
2805
+ * @param title The title for the card's sign-in button.
2806
+ * @param url The URL of the sign-in page to use.
2807
+ * @param text Optional. Additional text to include on the card.
2808
+ *
2809
+ * @returns A bot message activity attached with a sign-in card.
2810
+ *
2811
+ * @remarks
2812
+ * For channels that don't natively support sign-in cards, an alternative message is rendered.
2813
+ *
2814
+ * @beta
2815
+ */
2816
+ static attachSigninCard(title, url, text) {
2817
+ return MessageBuilder.attachContent(CardFactory.signinCard(title, url, text));
2818
+ }
2819
+ /**
2820
+ * Build a bot message activity attached with an Office 365 connector card.
2821
+ *
2822
+ * @param card A description of the Office 365 connector card.
2823
+ * @returns A bot message activity attached with an Office 365 connector card.
2824
+ *
2825
+ * @beta
2826
+ */
2827
+ static attachO365ConnectorCard(card) {
2828
+ return MessageBuilder.attachContent(CardFactory.o365ConnectorCard(card));
2829
+ }
2830
+ /**
2831
+ * Build a message activity attached with a receipt card.
2832
+ * @param card A description of the receipt card.
2833
+ * @returns A message activity attached with a receipt card.
2834
+ *
2835
+ * @beta
2836
+ */
2837
+ static AttachReceiptCard(card) {
2838
+ return MessageBuilder.attachContent(CardFactory.receiptCard(card));
2839
+ }
2840
+ /**
2841
+ *
2842
+ * @param title The card title.
2843
+ * @param images Optional. The array of images to include on the card.
2844
+ * @param buttons Optional. The array of buttons to include on the card. Each `string` in the array
2845
+ * is converted to an `imBack` button with a title and value set to the value of the string.
2846
+ * @param other Optional. Any additional properties to include on the card.
2847
+ * @returns A message activity attached with a thumbnail card
2848
+ *
2849
+ * @beta
2850
+ */
2851
+ static attachThumbnailCard(title, images, buttons, other) {
2852
+ return MessageBuilder.attachContent(CardFactory.thumbnailCard(title, images, buttons, other));
2853
+ }
2854
+ /**
2855
+ * Add an attachement to a bot activity.
2856
+ * @param attachement The attachment object to attach.
2857
+ * @returns A message activity with an attachment.
2858
+ *
2859
+ * @beta
2860
+ */
2861
+ static attachContent(attachement) {
2862
+ return {
2863
+ attachments: [attachement],
2864
+ };
2865
+ }
1568
2866
  }
1569
2867
 
1570
- export { AppCredential, ErrorCode, ErrorWithCode, IdentityType, LogLevel, MsGraphAuthProvider, OnBehalfOfUserCredential, TeamsBotSsoPrompt, TeamsFx, TeamsUserCredential, createMicrosoftGraphClient, getLogLevel, getTediousConnectionConfig, setLogFunction, setLogLevel, setLogger };
2868
+ export { ApiKeyLocation, ApiKeyProvider, AppCredential, BasicAuthProvider, BearerTokenAuthProvider, CertificateAuthProvider, Channel, CommandBot, ConversationBot, ErrorCode, ErrorWithCode, IdentityType, LogLevel, Member, MessageBuilder, MsGraphAuthProvider, NotificationBot, OnBehalfOfUserCredential, TeamsBotInstallation, TeamsBotSsoPrompt, TeamsFx, TeamsUserCredential, createApiClient, createMicrosoftGraphClient, createPemCertOption, createPfxCertOption, getLogLevel, getTediousConnectionConfig, sendAdaptiveCard, sendMessage, setLogFunction, setLogLevel, setLogger };
1571
2869
  //# sourceMappingURL=index.esm2017.mjs.map