@microsoft/teamsfx 0.6.2 → 0.6.3-alpha.26aa11b7c.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.
@@ -88,6 +92,9 @@ ErrorMessage.FailToAcquireTokenOnBehalfOfUser = "Failed to acquire access token
88
92
  ErrorMessage.OnlyMSTeamsChannelSupported = "{0} is only supported in MS Teams Channel";
89
93
  // IdentityTypeNotSupported Error
90
94
  ErrorMessage.IdentityTypeNotSupported = "{0} identity is not supported in {1}";
95
+ // InvalidParameter Error
96
+ ErrorMessage.EmptyParameter = "Parameter {0} is empty";
97
+ ErrorMessage.DuplicateHttpsOptionProperty = "Axios HTTPS agent already defined value for property {0}";
91
98
  /**
92
99
  * Error class with code and message thrown by the SDK.
93
100
  *
@@ -1385,6 +1392,166 @@ class TeamsBotSsoPrompt extends Dialog {
1385
1392
  }
1386
1393
  }
1387
1394
 
1395
+ // Copyright (c) Microsoft Corporation.
1396
+ /**
1397
+ * Initializes new Axios instance with specific auth provider
1398
+ *
1399
+ * @param apiEndpoint - Base url of the API
1400
+ * @param authProvider - Auth provider that injects authentication info to each request
1401
+ * @returns axios instance configured with specfic auth provider
1402
+ *
1403
+ * @example
1404
+ * ```typescript
1405
+ * const client = createApiClient("https://my-api-endpoint-base-url", new BasicAuthProvider("xxx","xxx"));
1406
+ * ```
1407
+ *
1408
+ * @beta
1409
+ */
1410
+ function createApiClient(apiEndpoint, authProvider) {
1411
+ // Add a request interceptor
1412
+ const instance = axios.create({
1413
+ baseURL: apiEndpoint,
1414
+ });
1415
+ instance.interceptors.request.use(async function (config) {
1416
+ return await authProvider.AddAuthenticationInfo(config);
1417
+ });
1418
+ return instance;
1419
+ }
1420
+
1421
+ // Copyright (c) Microsoft Corporation.
1422
+ // Licensed under the MIT license.
1423
+ /**
1424
+ * Provider that handles Bearer Token authentication
1425
+ *
1426
+ * @beta
1427
+ */
1428
+ class BearerTokenAuthProvider {
1429
+ /**
1430
+ * @param getToken Function that returns the content of bearer token used in http request
1431
+ *
1432
+ * @beta
1433
+ */
1434
+ constructor(getToken) {
1435
+ this.getToken = getToken;
1436
+ }
1437
+ /**
1438
+ * Adds authentication info to http requests
1439
+ *
1440
+ * @param config - Contains all the request information and can be updated to include extra authentication info.
1441
+ * Refer https://axios-http.com/docs/req_config for detailed document.
1442
+ *
1443
+ * @beta
1444
+ */
1445
+ async AddAuthenticationInfo(config) {
1446
+ const token = await this.getToken();
1447
+ if (!config.headers) {
1448
+ config.headers = {};
1449
+ }
1450
+ if (config.headers["Authorization"]) {
1451
+ throw new Error("Authorization header already exists!");
1452
+ }
1453
+ config.headers["Authorization"] = `Bearer ${token}`;
1454
+ return config;
1455
+ }
1456
+ }
1457
+
1458
+ // Copyright (c) Microsoft Corporation.
1459
+ /**
1460
+ * Provider that handles Certificate authentication
1461
+ *
1462
+ * @beta
1463
+ */
1464
+ class CertificateAuthProvider {
1465
+ /**
1466
+ *
1467
+ * @param { SecureContextOptions } certOption - information about the cert used in http requests
1468
+ *
1469
+ * @beta
1470
+ */
1471
+ constructor(certOption) {
1472
+ if (certOption && Object.keys(certOption).length !== 0) {
1473
+ this.certOption = certOption;
1474
+ }
1475
+ else {
1476
+ throw new ErrorWithCode(formatString(ErrorMessage.EmptyParameter, "certOption"), ErrorCode.InvalidParameter);
1477
+ }
1478
+ }
1479
+ /**
1480
+ * Adds authentication info to http requests.
1481
+ *
1482
+ * @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.
1483
+ * Refer https://axios-http.com/docs/req_config for detailed document.
1484
+ *
1485
+ * @returns Updated axios request config.
1486
+ *
1487
+ * @throws {@link ErrorCode|InvalidParameter} - when custom httpsAgent in the request has duplicate properties with certOption provided in constructor.
1488
+ *
1489
+ * @beta
1490
+ */
1491
+ async AddAuthenticationInfo(config) {
1492
+ if (!config.httpsAgent) {
1493
+ config.httpsAgent = new Agent(this.certOption);
1494
+ }
1495
+ else {
1496
+ const existingProperties = new Set(Object.keys(config.httpsAgent.options));
1497
+ for (const property of Object.keys(this.certOption)) {
1498
+ if (existingProperties.has(property)) {
1499
+ throw new ErrorWithCode(formatString(ErrorMessage.DuplicateHttpsOptionProperty, property), ErrorCode.InvalidParameter);
1500
+ }
1501
+ }
1502
+ Object.assign(config.httpsAgent.options, this.certOption);
1503
+ }
1504
+ return config;
1505
+ }
1506
+ }
1507
+ /**
1508
+ * Helper to create SecureContextOptions from PEM format cert
1509
+ *
1510
+ * @param { string | Buffer } cert - The cert chain in PEM format
1511
+ * @param { string | Buffer } key - The private key for the cert chain
1512
+ * @param { string? } passphrase - The passphrase for private key
1513
+ * @param { string? | Buffer? } ca - Overrides the trusted CA certificates
1514
+ *
1515
+ * @returns Instance of SecureContextOptions
1516
+ *
1517
+ * @throws {@link ErrorCode|InvalidParameter} - when any parameter is empty
1518
+ *
1519
+ */
1520
+ function createPemCertOption(cert, key, passphrase, ca) {
1521
+ if (cert.length === 0) {
1522
+ throw new ErrorWithCode(formatString(ErrorMessage.EmptyParameter, "cert"), ErrorCode.InvalidParameter);
1523
+ }
1524
+ if (key.length === 0) {
1525
+ throw new ErrorWithCode(formatString(ErrorMessage.EmptyParameter, "key"), ErrorCode.InvalidParameter);
1526
+ }
1527
+ return {
1528
+ cert,
1529
+ key,
1530
+ passphrase,
1531
+ ca,
1532
+ };
1533
+ }
1534
+ /**
1535
+ * Helper to create SecureContextOptions from PFX format cert
1536
+ *
1537
+ * @param { string | Buffer } pfx - The content of .pfx file
1538
+ * @param { string? } passphrase - Optional. The passphrase of .pfx file
1539
+ *
1540
+ * @returns Instance of SecureContextOptions
1541
+ *
1542
+ * @throws {@link ErrorCode|InvalidParameter} - when any parameter is empty
1543
+ *
1544
+ */
1545
+ function createPfxCertOption(pfx, passphrase) {
1546
+ if (pfx.length === 0) {
1547
+ throw new ErrorWithCode(formatString(ErrorMessage.EmptyParameter, "pfx"), ErrorCode.InvalidParameter);
1548
+ }
1549
+ return {
1550
+ pfx,
1551
+ passphrase,
1552
+ };
1553
+ }
1554
+
1388
1555
  // Copyright (c) Microsoft Corporation.
1389
1556
  /**
1390
1557
  * A class providing credential and configuration.
@@ -1567,5 +1734,982 @@ class TeamsFx {
1567
1734
  }
1568
1735
  }
1569
1736
 
1570
- export { AppCredential, ErrorCode, ErrorWithCode, IdentityType, LogLevel, MsGraphAuthProvider, OnBehalfOfUserCredential, TeamsBotSsoPrompt, TeamsFx, TeamsUserCredential, createMicrosoftGraphClient, getLogLevel, getTediousConnectionConfig, setLogFunction, setLogLevel, setLogger };
1737
+ // Copyright (c) Microsoft Corporation.
1738
+ /**
1739
+ * @internal
1740
+ */
1741
+ var ActivityType;
1742
+ (function (ActivityType) {
1743
+ ActivityType[ActivityType["CurrentBotInstalled"] = 0] = "CurrentBotInstalled";
1744
+ ActivityType[ActivityType["CurrentBotMessaged"] = 1] = "CurrentBotMessaged";
1745
+ ActivityType[ActivityType["CurrentBotUninstalled"] = 2] = "CurrentBotUninstalled";
1746
+ ActivityType[ActivityType["TeamDeleted"] = 3] = "TeamDeleted";
1747
+ ActivityType[ActivityType["TeamRestored"] = 4] = "TeamRestored";
1748
+ ActivityType[ActivityType["Unknown"] = 5] = "Unknown";
1749
+ })(ActivityType || (ActivityType = {}));
1750
+ /**
1751
+ * @internal
1752
+ */
1753
+ class NotificationMiddleware {
1754
+ constructor(options) {
1755
+ this.conversationReferenceStore = options.conversationReferenceStore;
1756
+ }
1757
+ async onTurn(context, next) {
1758
+ const type = this.classifyActivity(context.activity);
1759
+ switch (type) {
1760
+ case ActivityType.CurrentBotInstalled:
1761
+ case ActivityType.TeamRestored: {
1762
+ const reference = TurnContext.getConversationReference(context.activity);
1763
+ await this.conversationReferenceStore.set(reference);
1764
+ break;
1765
+ }
1766
+ case ActivityType.CurrentBotMessaged: {
1767
+ const reference = TurnContext.getConversationReference(context.activity);
1768
+ if (!(await this.conversationReferenceStore.check(reference))) {
1769
+ await this.conversationReferenceStore.set(reference);
1770
+ }
1771
+ break;
1772
+ }
1773
+ case ActivityType.CurrentBotUninstalled:
1774
+ case ActivityType.TeamDeleted: {
1775
+ const reference = TurnContext.getConversationReference(context.activity);
1776
+ await this.conversationReferenceStore.delete(reference);
1777
+ break;
1778
+ }
1779
+ }
1780
+ await next();
1781
+ }
1782
+ classifyActivity(activity) {
1783
+ var _a, _b;
1784
+ const activityType = activity.type;
1785
+ if (activityType === "installationUpdate") {
1786
+ const action = (_a = activity.action) === null || _a === void 0 ? void 0 : _a.toLowerCase();
1787
+ if (action === "add") {
1788
+ return ActivityType.CurrentBotInstalled;
1789
+ }
1790
+ else {
1791
+ return ActivityType.CurrentBotUninstalled;
1792
+ }
1793
+ }
1794
+ else if (activityType === "message") {
1795
+ return ActivityType.CurrentBotMessaged;
1796
+ }
1797
+ else if (activityType === "conversationUpdate") {
1798
+ const eventType = (_b = activity.channelData) === null || _b === void 0 ? void 0 : _b.eventType;
1799
+ if (eventType === "teamDeleted") {
1800
+ return ActivityType.TeamDeleted;
1801
+ }
1802
+ else if (eventType === "teamRestored") {
1803
+ return ActivityType.TeamRestored;
1804
+ }
1805
+ }
1806
+ return ActivityType.Unknown;
1807
+ }
1808
+ }
1809
+ class CommandResponseMiddleware {
1810
+ constructor(handlers) {
1811
+ this.commandHandlers = [];
1812
+ if (handlers && handlers.length > 0) {
1813
+ this.commandHandlers.push(...handlers);
1814
+ }
1815
+ }
1816
+ async onTurn(context, next) {
1817
+ const type = this.classifyActivity(context.activity);
1818
+ switch (type) {
1819
+ case ActivityType.CurrentBotMessaged:
1820
+ // Invoke corresponding command handler for the command response
1821
+ const commandText = this.getActivityText(context.activity);
1822
+ const message = {
1823
+ text: commandText,
1824
+ };
1825
+ for (const handler of this.commandHandlers) {
1826
+ const matchResult = this.shouldTrigger(handler.triggerPatterns, commandText);
1827
+ // It is important to note that the command bot will stop processing handlers
1828
+ // when the first command handler is matched.
1829
+ if (!!matchResult) {
1830
+ message.matches = Array.isArray(matchResult) ? matchResult : void 0;
1831
+ const response = await handler.handleCommandReceived(context, message);
1832
+ await context.sendActivity(response);
1833
+ break;
1834
+ }
1835
+ }
1836
+ break;
1837
+ }
1838
+ await next();
1839
+ }
1840
+ classifyActivity(activity) {
1841
+ if (activity.type === ActivityTypes.Message) {
1842
+ return ActivityType.CurrentBotMessaged;
1843
+ }
1844
+ return ActivityType.Unknown;
1845
+ }
1846
+ matchPattern(pattern, text) {
1847
+ if (text) {
1848
+ if (typeof pattern === "string") {
1849
+ const regExp = new RegExp(pattern, "i");
1850
+ return regExp.test(text);
1851
+ }
1852
+ if (pattern instanceof RegExp) {
1853
+ const matches = text.match(pattern);
1854
+ return matches !== null && matches !== void 0 ? matches : false;
1855
+ }
1856
+ }
1857
+ return false;
1858
+ }
1859
+ shouldTrigger(patterns, text) {
1860
+ const expressions = Array.isArray(patterns) ? patterns : [patterns];
1861
+ for (const ex of expressions) {
1862
+ const arg = this.matchPattern(ex, text);
1863
+ if (arg)
1864
+ return arg;
1865
+ }
1866
+ return false;
1867
+ }
1868
+ getActivityText(activity) {
1869
+ let text = activity.text;
1870
+ const removedMentionText = TurnContext.removeRecipientMention(activity);
1871
+ if (removedMentionText) {
1872
+ text = removedMentionText
1873
+ .toLowerCase()
1874
+ .replace(/\n|\r\n/g, "")
1875
+ .trim();
1876
+ }
1877
+ return text;
1878
+ }
1879
+ }
1880
+
1881
+ // Copyright (c) Microsoft Corporation.
1882
+ /**
1883
+ * A command bot for receiving commands and sending responses in Teams.
1884
+ *
1885
+ * @remarks
1886
+ * 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.
1887
+ *
1888
+ * @beta
1889
+ */
1890
+ class CommandBot {
1891
+ /**
1892
+ * Creates a new instance of the `CommandBot`.
1893
+ *
1894
+ * @param adapter The bound `BotFrameworkAdapter`.
1895
+ * @param options - initialize options
1896
+ *
1897
+ * @beta
1898
+ */
1899
+ constructor(adapter, options) {
1900
+ this.middleware = new CommandResponseMiddleware(options === null || options === void 0 ? void 0 : options.commands);
1901
+ this.adapter = adapter.use(this.middleware);
1902
+ }
1903
+ /**
1904
+ * Registers a command into the command bot.
1905
+ *
1906
+ * @param command The command to registered.
1907
+ *
1908
+ * @beta
1909
+ */
1910
+ registerCommand(command) {
1911
+ if (command) {
1912
+ this.middleware.commandHandlers.push(command);
1913
+ }
1914
+ }
1915
+ /**
1916
+ * Registers commands into the command bot.
1917
+ *
1918
+ * @param commands The command to registered.
1919
+ *
1920
+ * @beta
1921
+ */
1922
+ registerCommands(commands) {
1923
+ if (commands) {
1924
+ this.middleware.commandHandlers.push(...commands);
1925
+ }
1926
+ }
1927
+ }
1928
+
1929
+ // Copyright (c) Microsoft Corporation.
1930
+ /**
1931
+ * @internal
1932
+ */
1933
+ class LocalFileStorage {
1934
+ constructor(fileDir) {
1935
+ this.localFileName = ".notification.localstore.json";
1936
+ this.filePath = path.resolve(fileDir, this.localFileName);
1937
+ }
1938
+ async read(key) {
1939
+ if (!(await this.storeFileExists())) {
1940
+ return undefined;
1941
+ }
1942
+ const data = await this.readFromFile();
1943
+ return data[key];
1944
+ }
1945
+ async list() {
1946
+ if (!(await this.storeFileExists())) {
1947
+ return [];
1948
+ }
1949
+ const data = await this.readFromFile();
1950
+ return Object.entries(data).map((entry) => entry[1]);
1951
+ }
1952
+ async write(key, object) {
1953
+ if (!(await this.storeFileExists())) {
1954
+ await this.writeToFile({ [key]: object });
1955
+ return;
1956
+ }
1957
+ const data = await this.readFromFile();
1958
+ await this.writeToFile(Object.assign(data, { [key]: object }));
1959
+ }
1960
+ async delete(key) {
1961
+ if (await this.storeFileExists()) {
1962
+ const data = await this.readFromFile();
1963
+ if (data[key] !== undefined) {
1964
+ delete data[key];
1965
+ await this.writeToFile(data);
1966
+ }
1967
+ }
1968
+ }
1969
+ storeFileExists() {
1970
+ return new Promise((resolve) => {
1971
+ try {
1972
+ fs.access(this.filePath, (err) => {
1973
+ if (err) {
1974
+ resolve(false);
1975
+ }
1976
+ else {
1977
+ resolve(true);
1978
+ }
1979
+ });
1980
+ }
1981
+ catch (error) {
1982
+ resolve(false);
1983
+ }
1984
+ });
1985
+ }
1986
+ readFromFile() {
1987
+ return new Promise((resolve, reject) => {
1988
+ try {
1989
+ fs.readFile(this.filePath, { encoding: "utf-8" }, (err, rawData) => {
1990
+ if (err) {
1991
+ reject(err);
1992
+ }
1993
+ else {
1994
+ resolve(JSON.parse(rawData));
1995
+ }
1996
+ });
1997
+ }
1998
+ catch (error) {
1999
+ reject(error);
2000
+ }
2001
+ });
2002
+ }
2003
+ async writeToFile(data) {
2004
+ return new Promise((resolve, reject) => {
2005
+ try {
2006
+ const rawData = JSON.stringify(data, undefined, 2);
2007
+ fs.writeFile(this.filePath, rawData, { encoding: "utf-8" }, (err) => {
2008
+ if (err) {
2009
+ reject(err);
2010
+ }
2011
+ else {
2012
+ resolve();
2013
+ }
2014
+ });
2015
+ }
2016
+ catch (error) {
2017
+ reject(error);
2018
+ }
2019
+ });
2020
+ }
2021
+ }
2022
+ /**
2023
+ * @internal
2024
+ */
2025
+ class ConversationReferenceStore {
2026
+ constructor(storage) {
2027
+ this.storage = storage;
2028
+ }
2029
+ async check(reference) {
2030
+ const ref = await this.storage.read(this.getKey(reference));
2031
+ return ref !== undefined;
2032
+ }
2033
+ getAll() {
2034
+ return this.storage.list();
2035
+ }
2036
+ set(reference) {
2037
+ return this.storage.write(this.getKey(reference), reference);
2038
+ }
2039
+ delete(reference) {
2040
+ return this.storage.delete(this.getKey(reference));
2041
+ }
2042
+ getKey(reference) {
2043
+ var _a, _b;
2044
+ return `_${(_a = reference.conversation) === null || _a === void 0 ? void 0 : _a.tenantId}_${(_b = reference.conversation) === null || _b === void 0 ? void 0 : _b.id}`;
2045
+ }
2046
+ }
2047
+
2048
+ // Copyright (c) Microsoft Corporation.
2049
+ // Licensed under the MIT license.
2050
+ /**
2051
+ * @internal
2052
+ */
2053
+ function cloneConversation(conversation) {
2054
+ return Object.assign({}, conversation);
2055
+ }
2056
+ /**
2057
+ * @internal
2058
+ */
2059
+ function getTargetType(conversationReference) {
2060
+ var _a;
2061
+ const conversationType = (_a = conversationReference.conversation) === null || _a === void 0 ? void 0 : _a.conversationType;
2062
+ if (conversationType === "personal") {
2063
+ return "Person";
2064
+ }
2065
+ else if (conversationType === "groupChat") {
2066
+ return "Group";
2067
+ }
2068
+ else if (conversationType === "channel") {
2069
+ return "Channel";
2070
+ }
2071
+ else {
2072
+ return undefined;
2073
+ }
2074
+ }
2075
+ /**
2076
+ * @internal
2077
+ */
2078
+ function getTeamsBotInstallationId(context) {
2079
+ var _a, _b, _c, _d;
2080
+ 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;
2081
+ }
2082
+
2083
+ // Copyright (c) Microsoft Corporation.
2084
+ /**
2085
+ * Send a plain text message to a notification target.
2086
+ *
2087
+ * @param target - the notification target.
2088
+ * @param text - the plain text message.
2089
+ * @returns A `Promise` representing the asynchronous operation.
2090
+ *
2091
+ * @beta
2092
+ */
2093
+ function sendMessage(target, text) {
2094
+ return target.sendMessage(text);
2095
+ }
2096
+ /**
2097
+ * Send an adaptive card message to a notification target.
2098
+ *
2099
+ * @param target - the notification target.
2100
+ * @param card - the adaptive card raw JSON.
2101
+ * @returns A `Promise` representing the asynchronous operation.
2102
+ *
2103
+ * @beta
2104
+ */
2105
+ function sendAdaptiveCard(target, card) {
2106
+ return target.sendAdaptiveCard(card);
2107
+ }
2108
+ /**
2109
+ * A {@link NotificationTarget} that represents a team channel.
2110
+ *
2111
+ * @remarks
2112
+ * It's recommended to get channels from {@link TeamsBotInstallation.channels()}.
2113
+ *
2114
+ * @beta
2115
+ */
2116
+ class Channel {
2117
+ /**
2118
+ * Constuctor.
2119
+ *
2120
+ * @remarks
2121
+ * It's recommended to get channels from {@link TeamsBotInstallation.channels()}, instead of using this constructor.
2122
+ *
2123
+ * @param parent - The parent {@link TeamsBotInstallation} where this channel is created from.
2124
+ * @param info - Detailed channel information.
2125
+ *
2126
+ * @beta
2127
+ */
2128
+ constructor(parent, info) {
2129
+ /**
2130
+ * Notification target type. For channel it's always "Channel".
2131
+ *
2132
+ * @beta
2133
+ */
2134
+ this.type = "Channel";
2135
+ this.parent = parent;
2136
+ this.info = info;
2137
+ }
2138
+ /**
2139
+ * Send a plain text message.
2140
+ *
2141
+ * @param text - the plain text message.
2142
+ * @returns A `Promise` representing the asynchronous operation.
2143
+ *
2144
+ * @beta
2145
+ */
2146
+ sendMessage(text) {
2147
+ return this.parent.adapter.continueConversation(this.parent.conversationReference, async (context) => {
2148
+ const conversation = await this.newConversation(context);
2149
+ await this.parent.adapter.continueConversation(conversation, async (ctx) => {
2150
+ await ctx.sendActivity(text);
2151
+ });
2152
+ });
2153
+ }
2154
+ /**
2155
+ * Send an adaptive card message.
2156
+ *
2157
+ * @param card - the adaptive card raw JSON.
2158
+ * @returns A `Promise` representing the asynchronous operation.
2159
+ *
2160
+ * @beta
2161
+ */
2162
+ async sendAdaptiveCard(card) {
2163
+ return this.parent.adapter.continueConversation(this.parent.conversationReference, async (context) => {
2164
+ const conversation = await this.newConversation(context);
2165
+ await this.parent.adapter.continueConversation(conversation, async (ctx) => {
2166
+ await ctx.sendActivity({
2167
+ attachments: [CardFactory.adaptiveCard(card)],
2168
+ });
2169
+ });
2170
+ });
2171
+ }
2172
+ /**
2173
+ * @internal
2174
+ */
2175
+ async newConversation(context) {
2176
+ const reference = TurnContext.getConversationReference(context.activity);
2177
+ const channelConversation = cloneConversation(reference);
2178
+ channelConversation.conversation.id = this.info.id || "";
2179
+ return channelConversation;
2180
+ }
2181
+ }
2182
+ /**
2183
+ * A {@link NotificationTarget} that represents a team member.
2184
+ *
2185
+ * @remarks
2186
+ * It's recommended to get members from {@link TeamsBotInstallation.members()}.
2187
+ *
2188
+ * @beta
2189
+ */
2190
+ class Member {
2191
+ /**
2192
+ * Constuctor.
2193
+ *
2194
+ * @remarks
2195
+ * It's recommended to get members from {@link TeamsBotInstallation.members()}, instead of using this constructor.
2196
+ *
2197
+ * @param parent - The parent {@link TeamsBotInstallation} where this member is created from.
2198
+ * @param account - Detailed member account information.
2199
+ *
2200
+ * @beta
2201
+ */
2202
+ constructor(parent, account) {
2203
+ /**
2204
+ * Notification target type. For member it's always "Person".
2205
+ *
2206
+ * @beta
2207
+ */
2208
+ this.type = "Person";
2209
+ this.parent = parent;
2210
+ this.account = account;
2211
+ }
2212
+ /**
2213
+ * Send a plain text message.
2214
+ *
2215
+ * @param text - the plain text message.
2216
+ * @returns A `Promise` representing the asynchronous operation.
2217
+ *
2218
+ * @beta
2219
+ */
2220
+ sendMessage(text) {
2221
+ return this.parent.adapter.continueConversation(this.parent.conversationReference, async (context) => {
2222
+ const conversation = await this.newConversation(context);
2223
+ await this.parent.adapter.continueConversation(conversation, async (ctx) => {
2224
+ await ctx.sendActivity(text);
2225
+ });
2226
+ });
2227
+ }
2228
+ /**
2229
+ * Send an adaptive card message.
2230
+ *
2231
+ * @param card - the adaptive card raw JSON.
2232
+ * @returns A `Promise` representing the asynchronous operation.
2233
+ *
2234
+ * @beta
2235
+ */
2236
+ async sendAdaptiveCard(card) {
2237
+ return this.parent.adapter.continueConversation(this.parent.conversationReference, async (context) => {
2238
+ const conversation = await this.newConversation(context);
2239
+ await this.parent.adapter.continueConversation(conversation, async (ctx) => {
2240
+ await ctx.sendActivity({
2241
+ attachments: [CardFactory.adaptiveCard(card)],
2242
+ });
2243
+ });
2244
+ });
2245
+ }
2246
+ /**
2247
+ * @internal
2248
+ */
2249
+ async newConversation(context) {
2250
+ const reference = TurnContext.getConversationReference(context.activity);
2251
+ const personalConversation = cloneConversation(reference);
2252
+ const connectorClient = context.turnState.get(this.parent.adapter.ConnectorClientKey);
2253
+ const conversation = await connectorClient.conversations.createConversation({
2254
+ isGroup: false,
2255
+ tenantId: context.activity.conversation.tenantId,
2256
+ bot: context.activity.recipient,
2257
+ members: [this.account],
2258
+ channelData: {},
2259
+ });
2260
+ personalConversation.conversation.id = conversation.id;
2261
+ return personalConversation;
2262
+ }
2263
+ }
2264
+ /**
2265
+ * A {@link NotificationTarget} that represents a bot installation. Teams Bot could be installed into
2266
+ * - Personal chat
2267
+ * - Group chat
2268
+ * - Team (by default the `General` channel)
2269
+ *
2270
+ * @remarks
2271
+ * It's recommended to get bot installations from {@link ConversationBot.installations()}.
2272
+ *
2273
+ * @beta
2274
+ */
2275
+ class TeamsBotInstallation {
2276
+ /**
2277
+ * Constructor
2278
+ *
2279
+ * @remarks
2280
+ * It's recommended to get bot installations from {@link ConversationBot.installations()}, instead of using this constructor.
2281
+ *
2282
+ * @param adapter - the bound `BotFrameworkAdapter`.
2283
+ * @param conversationReference - the bound `ConversationReference`.
2284
+ *
2285
+ * @beta
2286
+ */
2287
+ constructor(adapter, conversationReference) {
2288
+ this.adapter = adapter;
2289
+ this.conversationReference = conversationReference;
2290
+ this.type = getTargetType(conversationReference);
2291
+ }
2292
+ /**
2293
+ * Send a plain text message.
2294
+ *
2295
+ * @param text - the plain text message.
2296
+ * @returns A `Promise` representing the asynchronous operation.
2297
+ *
2298
+ * @beta
2299
+ */
2300
+ sendMessage(text) {
2301
+ return this.adapter.continueConversation(this.conversationReference, async (context) => {
2302
+ await context.sendActivity(text);
2303
+ });
2304
+ }
2305
+ /**
2306
+ * Send an adaptive card message.
2307
+ *
2308
+ * @param card - the adaptive card raw JSON.
2309
+ * @returns A `Promise` representing the asynchronous operation.
2310
+ *
2311
+ * @beta
2312
+ */
2313
+ sendAdaptiveCard(card) {
2314
+ return this.adapter.continueConversation(this.conversationReference, async (context) => {
2315
+ await context.sendActivity({
2316
+ attachments: [CardFactory.adaptiveCard(card)],
2317
+ });
2318
+ });
2319
+ }
2320
+ /**
2321
+ * Get channels from this bot installation.
2322
+ *
2323
+ * @returns an array of channels if bot is installed into a team, otherwise returns an empty array.
2324
+ *
2325
+ * @beta
2326
+ */
2327
+ async channels() {
2328
+ let teamsChannels = [];
2329
+ await this.adapter.continueConversation(this.conversationReference, async (context) => {
2330
+ const teamId = getTeamsBotInstallationId(context);
2331
+ if (teamId !== undefined) {
2332
+ teamsChannels = await TeamsInfo.getTeamChannels(context, teamId);
2333
+ }
2334
+ });
2335
+ const channels = [];
2336
+ for (const channel of teamsChannels) {
2337
+ channels.push(new Channel(this, channel));
2338
+ }
2339
+ return channels;
2340
+ }
2341
+ /**
2342
+ * Get members from this bot installation.
2343
+ *
2344
+ * @returns an array of members from where the bot is installed.
2345
+ *
2346
+ * @beta
2347
+ */
2348
+ async members() {
2349
+ const members = [];
2350
+ await this.adapter.continueConversation(this.conversationReference, async (context) => {
2351
+ let continuationToken;
2352
+ do {
2353
+ const pagedMembers = await TeamsInfo.getPagedMembers(context, undefined, continuationToken);
2354
+ continuationToken = pagedMembers.continuationToken;
2355
+ for (const member of pagedMembers.members) {
2356
+ members.push(new Member(this, member));
2357
+ }
2358
+ } while (continuationToken !== undefined);
2359
+ });
2360
+ return members;
2361
+ }
2362
+ }
2363
+ /**
2364
+ * Provide utilities to send notification to varies targets (e.g., member, group, channel).
2365
+ *
2366
+ * @beta
2367
+ */
2368
+ class NotificationBot {
2369
+ /**
2370
+ * constructor of the notification bot.
2371
+ *
2372
+ * @remarks
2373
+ * To ensure accuracy, it's recommended to initialize before handling any message.
2374
+ *
2375
+ * @param adapter - the bound `BotFrameworkAdapter`
2376
+ * @param options - initialize options
2377
+ *
2378
+ * @beta
2379
+ */
2380
+ constructor(adapter, options) {
2381
+ var _a, _b;
2382
+ 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 : "./" : "./"));
2383
+ this.conversationReferenceStore = new ConversationReferenceStore(storage);
2384
+ this.adapter = adapter.use(new NotificationMiddleware({
2385
+ conversationReferenceStore: this.conversationReferenceStore,
2386
+ }));
2387
+ }
2388
+ /**
2389
+ * Get all targets where the bot is installed.
2390
+ *
2391
+ * @remarks
2392
+ * The result is retrieving from the persisted storage.
2393
+ *
2394
+ * @returns - an array of {@link TeamsBotInstallation}.
2395
+ *
2396
+ * @beta
2397
+ */
2398
+ async installations() {
2399
+ if (this.conversationReferenceStore === undefined || this.adapter === undefined) {
2400
+ throw new Error("NotificationBot has not been initialized.");
2401
+ }
2402
+ const references = (await this.conversationReferenceStore.getAll()).values();
2403
+ const targets = [];
2404
+ for (const reference of references) {
2405
+ // validate connection
2406
+ let valid = true;
2407
+ this.adapter.continueConversation(reference, async (context) => {
2408
+ try {
2409
+ // try get member to see if the installation is still valid
2410
+ await TeamsInfo.getPagedMembers(context, 1);
2411
+ }
2412
+ catch (error) {
2413
+ if (error.code === "BotNotInConversationRoster") {
2414
+ valid = false;
2415
+ }
2416
+ }
2417
+ });
2418
+ if (valid) {
2419
+ targets.push(new TeamsBotInstallation(this.adapter, reference));
2420
+ }
2421
+ else {
2422
+ this.conversationReferenceStore.delete(reference);
2423
+ }
2424
+ }
2425
+ return targets;
2426
+ }
2427
+ }
2428
+
2429
+ // Copyright (c) Microsoft Corporation.
2430
+ /**
2431
+ * Provide utilities for bot conversation, including:
2432
+ * - handle command and response.
2433
+ * - send notification to varies targets (e.g., member, group, channel).
2434
+ *
2435
+ * @example
2436
+ * For command and response, you can register your commands through the constructor, or use the `registerCommand` and `registerCommands` API to add commands later.
2437
+ *
2438
+ * ```typescript
2439
+ * // register through constructor
2440
+ * const conversationBot = new ConversationBot({
2441
+ * command: {
2442
+ * enabled: true,
2443
+ * commands: [ new HelloWorldCommandHandler() ],
2444
+ * },
2445
+ * });
2446
+ *
2447
+ * // register through `register*` API
2448
+ * conversationBot.command.registerCommand(new HelpCommandHandler());
2449
+ * ```
2450
+ *
2451
+ * For notification, you can enable notification at initialization, then send notifications at any time.
2452
+ *
2453
+ * ```typescript
2454
+ * // enable through constructor
2455
+ * const conversationBot = new ConversationBot({
2456
+ * notification: {
2457
+ * enabled: true,
2458
+ * },
2459
+ * });
2460
+ *
2461
+ * // get all bot installations and send message
2462
+ * for (const target of await conversationBot.notification.installations()) {
2463
+ * await target.sendMessage("Hello Notification");
2464
+ * }
2465
+ *
2466
+ * // alternative - send message to all members
2467
+ * for (const target of await conversationBot.notification.installations()) {
2468
+ * for (const member of await target.members()) {
2469
+ * await member.sendMessage("Hello Notification");
2470
+ * }
2471
+ * }
2472
+ * ```
2473
+ *
2474
+ * @remarks
2475
+ * Set `adapter` in {@link ConversationOptions} to use your own bot adapter.
2476
+ *
2477
+ * 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.
2478
+ *
2479
+ * For notification, set `notification.storage` in {@link ConversationOptions} to use your own storage implementation.
2480
+ *
2481
+ * @beta
2482
+ */
2483
+ class ConversationBot {
2484
+ /**
2485
+ * Creates new instance of the `ConversationBot`.
2486
+ *
2487
+ * @remarks
2488
+ * It's recommended to create your own adapter and storage for production environment instead of the default one.
2489
+ *
2490
+ * @param options - initialize options
2491
+ *
2492
+ * @beta
2493
+ */
2494
+ constructor(options) {
2495
+ var _a, _b;
2496
+ if (options.adapter) {
2497
+ this.adapter = options.adapter;
2498
+ }
2499
+ else {
2500
+ this.adapter = this.createDefaultAdapter(options.adapterConfig);
2501
+ }
2502
+ if ((_a = options.command) === null || _a === void 0 ? void 0 : _a.enabled) {
2503
+ this.command = new CommandBot(this.adapter, options.command);
2504
+ }
2505
+ if ((_b = options.notification) === null || _b === void 0 ? void 0 : _b.enabled) {
2506
+ this.notification = new NotificationBot(this.adapter, options.notification);
2507
+ }
2508
+ }
2509
+ createDefaultAdapter(adapterConfig) {
2510
+ const adapter = adapterConfig === undefined
2511
+ ? new BotFrameworkAdapter({
2512
+ appId: process.env.BOT_ID,
2513
+ appPassword: process.env.BOT_PASSWORD,
2514
+ })
2515
+ : new BotFrameworkAdapter(adapterConfig);
2516
+ // the default error handler
2517
+ adapter.onTurnError = async (context, error) => {
2518
+ // This check writes out errors to console.
2519
+ console.error(`[onTurnError] unhandled error: ${error}`);
2520
+ // Send a trace activity, which will be displayed in Bot Framework Emulator
2521
+ await context.sendTraceActivity("OnTurnError Trace", `${error}`, "https://www.botframework.com/schemas/error", "TurnError");
2522
+ // Send a message to the user
2523
+ await context.sendActivity(`The bot encountered unhandled error: ${error.message}`);
2524
+ await context.sendActivity("To continue to run this bot, please fix the bot source code.");
2525
+ };
2526
+ return adapter;
2527
+ }
2528
+ /**
2529
+ * The request handler to integrate with web request.
2530
+ *
2531
+ * @param req - an Express or Restify style request object.
2532
+ * @param res - an Express or Restify style response object.
2533
+ * @param logic - the additional function to handle bot context.
2534
+ *
2535
+ * @example
2536
+ * For example, to use with Restify:
2537
+ * ``` typescript
2538
+ * // The default/empty behavior
2539
+ * server.post("api/messages", conversationBot.requestHandler);
2540
+ *
2541
+ * // Or, add your own logic
2542
+ * server.post("api/messages", async (req, res) => {
2543
+ * await conversationBot.requestHandler(req, res, async (context) => {
2544
+ * // your-own-context-logic
2545
+ * });
2546
+ * });
2547
+ * ```
2548
+ *
2549
+ * @beta
2550
+ */
2551
+ async requestHandler(req, res, logic) {
2552
+ if (logic === undefined) {
2553
+ // create empty logic
2554
+ logic = async () => { };
2555
+ }
2556
+ await this.adapter.processActivity(req, res, logic);
2557
+ }
2558
+ }
2559
+
2560
+ // Copyright (c) Microsoft Corporation.
2561
+ const { AdaptiveCards } = require("@microsoft/adaptivecards-tools");
2562
+ /**
2563
+ * Provides utility method to build bot message with cards that supported in Teams.
2564
+ */
2565
+ class MessageBuilder {
2566
+ /**
2567
+ * Build a bot message activity attached with adaptive card.
2568
+ *
2569
+ * @param getCardData Function to prepare your card data.
2570
+ * @param cardTemplate The adaptive card template.
2571
+ * @returns A bot message activity attached with an adaptive card.
2572
+ *
2573
+ * @example
2574
+ * ```javascript
2575
+ * const cardTemplate = {
2576
+ * type: "AdaptiveCard",
2577
+ * body: [
2578
+ * {
2579
+ * "type": "TextBlock",
2580
+ * "text": "${title}",
2581
+ * "size": "Large"
2582
+ * },
2583
+ * {
2584
+ * "type": "TextBlock",
2585
+ * "text": "${description}"
2586
+ * }],
2587
+ * $schema: "http://adaptivecards.io/schemas/adaptive-card.json",
2588
+ * version: "1.4"
2589
+ * };
2590
+ *
2591
+ * type CardData = {
2592
+ * title: string,
2593
+ * description: string
2594
+ * };
2595
+ * const card = MessageBuilder.attachAdaptiveCard<CardData>(() => {
2596
+ * return {
2597
+ * title: "sample card title",
2598
+ * description: "sample card description"
2599
+ * }}, cardTemplate);
2600
+ * ```
2601
+ *
2602
+ * @beta
2603
+ */
2604
+ static attachAdaptiveCard(getCardData, cardTemplate) {
2605
+ const cardData = getCardData();
2606
+ return {
2607
+ attachments: [CardFactory.adaptiveCard(AdaptiveCards.declare(cardTemplate).render(cardData))],
2608
+ };
2609
+ }
2610
+ /**
2611
+ * Build a bot message activity attached with an adaptive card.
2612
+ *
2613
+ * @param card The adaptive card content.
2614
+ * @returns A bot message activity attached with an adaptive card.
2615
+ *
2616
+ * @beta
2617
+ */
2618
+ static attachAdaptiveCardWithoutData(card) {
2619
+ return {
2620
+ attachments: [CardFactory.adaptiveCard(AdaptiveCards.declareWithoutData(card).render())],
2621
+ };
2622
+ }
2623
+ /**
2624
+ * Build a bot message activity attached with an hero card.
2625
+ *
2626
+ * @param title The card title.
2627
+ * @param images Optional. The array of images to include on the card.
2628
+ * @param buttons Optional. The array of buttons to include on the card. Each `string` in the array
2629
+ * is converted to an `imBack` button with a title and value set to the value of the string.
2630
+ * @param other Optional. Any additional properties to include on the card.
2631
+ *
2632
+ * @returns A bot message activity attached with a hero card.
2633
+ *
2634
+ * @example
2635
+ * ```javascript
2636
+ * const message = MessageBuilder.attachHeroCard(
2637
+ * 'sample title',
2638
+ * ['https://example.com/sample.jpg'],
2639
+ * ['action']
2640
+ * );
2641
+ * ```
2642
+ *
2643
+ * @beta
2644
+ */
2645
+ static attachHeroCard(title, images, buttons, other) {
2646
+ return MessageBuilder.attachContent(CardFactory.heroCard(title, images, buttons, other));
2647
+ }
2648
+ /**
2649
+ * Returns an attachment for a sign-in card.
2650
+ *
2651
+ * @param title The title for the card's sign-in button.
2652
+ * @param url The URL of the sign-in page to use.
2653
+ * @param text Optional. Additional text to include on the card.
2654
+ *
2655
+ * @returns A bot message activity attached with a sign-in card.
2656
+ *
2657
+ * @remarks
2658
+ * For channels that don't natively support sign-in cards, an alternative message is rendered.
2659
+ *
2660
+ * @beta
2661
+ */
2662
+ static attachSigninCard(title, url, text) {
2663
+ return MessageBuilder.attachContent(CardFactory.signinCard(title, url, text));
2664
+ }
2665
+ /**
2666
+ * Build a bot message activity attached with an Office 365 connector card.
2667
+ *
2668
+ * @param card A description of the Office 365 connector card.
2669
+ * @returns A bot message activity attached with an Office 365 connector card.
2670
+ *
2671
+ * @beta
2672
+ */
2673
+ static attachO365ConnectorCard(card) {
2674
+ return MessageBuilder.attachContent(CardFactory.o365ConnectorCard(card));
2675
+ }
2676
+ /**
2677
+ * Build a message activity attached with a receipt card.
2678
+ * @param card A description of the receipt card.
2679
+ * @returns A message activity attached with a receipt card.
2680
+ *
2681
+ * @beta
2682
+ */
2683
+ static AttachReceiptCard(card) {
2684
+ return MessageBuilder.attachContent(CardFactory.receiptCard(card));
2685
+ }
2686
+ /**
2687
+ *
2688
+ * @param title The card title.
2689
+ * @param images Optional. The array of images to include on the card.
2690
+ * @param buttons Optional. The array of buttons to include on the card. Each `string` in the array
2691
+ * is converted to an `imBack` button with a title and value set to the value of the string.
2692
+ * @param other Optional. Any additional properties to include on the card.
2693
+ * @returns A message activity attached with a thumbnail card
2694
+ *
2695
+ * @beta
2696
+ */
2697
+ static attachThumbnailCard(title, images, buttons, other) {
2698
+ return MessageBuilder.attachContent(CardFactory.thumbnailCard(title, images, buttons, other));
2699
+ }
2700
+ /**
2701
+ * Add an attachement to a bot activity.
2702
+ * @param attachement The attachment object to attach.
2703
+ * @returns A message activity with an attachment.
2704
+ *
2705
+ * @beta
2706
+ */
2707
+ static attachContent(attachement) {
2708
+ return {
2709
+ attachments: [attachement],
2710
+ };
2711
+ }
2712
+ }
2713
+
2714
+ export { AppCredential, 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
2715
  //# sourceMappingURL=index.esm2017.mjs.map