@microsoft/teamsfx 4.0.1-alpha.f172b74a7.0 → 4.0.1-alpha.fa365893d.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.
package/README.md CHANGED
@@ -1,5 +1,7 @@
1
1
  # TeamsFx SDK for TypeScript/JavaScript
2
2
 
3
+ > This package will be deprecated by 2026-07. Please use [Microsoft 365 Agents SDK](https://www.npmjs.com/package/@microsoft/agents-hosting) instead.
4
+
3
5
  TeamsFx aims to reduce the developer tasks of leveraging Teams SSO and access to cloud resources down to single-line statements with "zero configuration".
4
6
 
5
7
  Use the library to:
@@ -16,15 +18,15 @@ Use the library to:
16
18
 
17
19
  > Important: Please be advised that access tokens are stored in sessionStorage for you by default. This can make it possible for malicious code in your app (or code pasted into a console on your page) to access APIs at the same privilege level as your client application. Please ensure you only request the minimum necessary scopes from your client application, and perform any sensitive operations from server side code that your client has to authenticate with.
18
20
 
19
- TeamsFx SDK is pre-configured in scaffolded project using Teams Toolkit extension for Visual Studio and vscode, or the `teamsfx` cli from the `teamsfx-cli` npm package.
21
+ TeamsFx SDK is pre-configured in scaffolded project using Microsoft 365 Agents Toolkit extension for Visual Studio and vscode, or the `atk` cli from the `@microsoft/m365agentstoolkit-cli` npm package.
20
22
  Please check the [README](https://github.com/OfficeDev/TeamsFx/blob/main/packages/vscode-extension/README.md) to see how to create a Teams App project.
21
23
 
22
24
  ### Prerequisites
23
25
 
24
26
  - Node.js version 18 or higher
25
27
  - PNPM version 8 or higher
26
- - A project created by the Teams Toolkit VS Code extension or `teamsfx` CLI tool.
27
- - If your project has installed `botbuilder` related [packages](https://github.com/Microsoft/botbuilder-js#packages) as dependencies, ensure they are of the same version and the version `>= 4.18.0`. ([Issue - all of the BOTBUILDER packages should be the same version](https://github.com/BotBuilderCommunity/botbuilder-community-js/issues/57#issuecomment-508538548))
28
+ - A project created by the Microsoft 365 Agents Toolkit VS Code extension or `atk` CLI tool.
29
+ - If your project has installed `@microsoft/agents-hosting` related [packages](https://github.com/microsoft/Agents-for-js) as dependencies, ensure they are of the same version.
28
30
 
29
31
  ### Install the `@microsoft/teamsfx` package
30
32
 
@@ -437,13 +439,13 @@ const token = appCredential.getToken();
437
439
  Add `TeamsBotSsoPrompt` to dialog set.
438
440
 
439
441
  ```ts
440
- const { ConversationState, MemoryStorage } = require("botbuilder");
441
- const { DialogSet, WaterfallDialog } = require("botbuilder-dialogs");
442
- const {
442
+ import { ConversationState, MemoryStorage } from "@microsoft/agents-hosting";
443
+ import { DialogSet, WaterfallDialog } from "@microsoft/agents-hosting-dialogs";
444
+ import {
443
445
  TeamsBotSsoPrompt,
444
446
  OnBehalfOfCredentialAuthConfig,
445
447
  TeamsBotSsoPromptSettings,
446
- } = require("@microsoft/teamsfx");
448
+ } from "@microsoft/teamsfx";
447
449
 
448
450
  const convoState = new ConversationState(new MemoryStorage());
449
451
  const dialogState = convoState.createProperty("dialogState");
@@ -596,13 +598,13 @@ Also see [Credential](#Credential) for furthur description.
596
598
 
597
599
  ## How to use SDK implemented with `CloudAdapter`
598
600
 
599
- From `botbuilder@4.16.0`, `BotFrameworkAdapter` is deprecated, and `CloudAdapter` is recommended to be used instead. You can import `ConversationBot` from `BotBuilderCloudAdapter` to use the latest SDK implemented with `CloudAdapter`.
601
+ From `@microsoft/teamsfx@4.0.0`, `BotBuilderCloudAdapter` has been renamed to `AgentBuilderCloudAdapter`. You can import `ConversationBot` from `AgentBuilderCloudAdapter` to use the latest SDK implemented with `CloudAdapter`.
600
602
 
601
- 1. Install `@microsoft/teamsfx @^2.2.0`, `botbuilder @^4.18.0`, (and `@types/node @^18.0.0` for TS projects) via `npm install` as follows.
603
+ 1. Install `@microsoft/teamsfx @^4.0.0`, `@microsoft/agents-hosting @^0.2.14`, (and `@types/node @^18.0.0` for TS projects) via `npm install` as follows.
602
604
 
603
605
  ```sh
604
606
  npm install @microsoft/teamsfx
605
- npm install botbuilder
607
+ npm install @microsoft/agents-hosting@^0.2.14
606
608
 
607
609
  // For TS projects only
608
610
  npm install --save-dev @types/node
@@ -612,17 +614,17 @@ From `botbuilder@4.16.0`, `BotFrameworkAdapter` is deprecated, and `CloudAdapter
612
614
 
613
615
  ```ts
614
616
  import { HelloWorldCommandHandler } from "../helloworldCommandHandler";
615
- import { BotBuilderCloudAdapter } from "@microsoft/teamsfx";
616
- import ConversationBot = BotBuilderCloudAdapter.ConversationBot;
617
+ import { AgentBuilderCloudAdapter } from "@microsoft/teamsfx";
618
+ import ConversationBot = AgentBuilderCloudAdapter.ConversationBot;
617
619
  import config from "./config";
618
620
 
619
621
  export const commandBot = new ConversationBot({
620
622
  // The bot id and password to create CloudAdapter.
621
623
  // See https://aka.ms/about-bot-adapter to learn more about adapters.
622
624
  adapterConfig: {
623
- MicrosoftAppId: config.botId,
624
- MicrosoftAppPassword: config.botPassword,
625
- MicrosoftAppType: "MultiTenant",
625
+ clientId: config.MicrosoftAppId,
626
+ clientSecret: config.MicrosoftAppPassword,
627
+ issuers: [],
626
628
  },
627
629
  command: {
628
630
  enabled: true,
@@ -665,50 +667,13 @@ From `botbuilder@4.16.0`, `BotFrameworkAdapter` is deprecated, and `CloudAdapter
665
667
  });
666
668
  ```
667
669
 
668
- 5. If the project has `responseWrapper.ts`, please update the class `responseWrapper` to the class below.
669
-
670
- ```ts
671
- import { Response } from "botbuilder";
672
-
673
- // A wrapper to convert Azure Functions Response to Bot Builder's Response.
674
- export class ResponseWrapper implements Response {
675
- socket: any;
676
- originalResponse?: any;
677
- headers?: any;
678
- body?: any;
679
-
680
- constructor(functionResponse?: { [key: string]: any }) {
681
- this.socket = undefined;
682
- this.originalResponse = functionResponse;
683
- }
684
-
685
- end(...args: any[]) {
686
- // do nothing since res.end() is deprecated in Azure Functions.
687
- }
688
-
689
- header(name: string, value: any) {
690
- this.headers[name] = value;
691
- }
692
-
693
- send(body: any) {
694
- // record the body to be returned later.
695
- this.body = body;
696
- this.originalResponse.body = body;
697
- }
698
- status(status: number) {
699
- // call Azure Functions' res.status().
700
- return this.originalResponse?.status(status);
701
- }
702
- }
703
- ```
704
-
705
670
  ## Next steps
706
671
 
707
672
  Please take a look at the [Samples](https://github.com/OfficeDev/TeamsFx-Samples) project for detailed examples on how to use this library.
708
673
 
709
674
  ## Related projects
710
675
 
711
- - [Microsoft Teams Toolkit for Visual Studio Code](https://github.com/OfficeDev/TeamsFx/tree/main/packages/vscode-extension)
676
+ - [Microsoft Microsoft 365 Agents Toolkit for Visual Studio Code](https://github.com/OfficeDev/TeamsFx/tree/main/packages/vscode-extension)
712
677
  - [TeamsFx Cli](https://github.com/OfficeDev/TeamsFx/tree/main/packages/cli)
713
678
 
714
679
  ## Data Collection.
@@ -1 +1 @@
1
- {"version":3,"file":"index.esm2017.js","sources":["../../src/core/errors.ts","../../src/util/logger.ts","../../src/util/utils.ts","../../src/credential/appCredential.browser.ts","../../src/credential/onBehalfOfUserCredential.browser.ts","../../src/credential/teamsUserCredential.browser.ts","../../src/bot/teamsBotSsoPrompt.browser.ts","../../src/apiClient/apiClient.ts","../../src/apiClient/bearerTokenAuthProvider.ts","../../src/apiClient/basicAuthProvider.browser.ts","../../src/apiClient/apiKeyProvider.browser.ts","../../src/conversation/interface.ts","../../src/conversationWithCloudAdapter/notification.browser.ts","../../src/apiClient/certificateAuthProvider.browser.ts","../../src/conversation/sso/botSsoExecutionDialog.browser.ts","../../src/messageExtension/executeWithSSO.browser.ts","../../src/conversationWithCloudAdapter/cardAction.browser.ts","../../src/conversationWithCloudAdapter/command.browser.ts","../../src/conversationWithCloudAdapter/conversation.browser.ts"],"sourcesContent":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"names":["ErrorCode","LogLevel","ErrorMessage","InvalidConfiguration","ConfigurationNotExists","ResourceConfigurationNotExists","MissingResourceConfiguration","AuthenticationConfigurationNotExists","BrowserRuntimeNotSupported","NodejsRuntimeNotSupported","FailToAcquireTokenOnBehalfOfUser","OnlyMSTeamsChannelSupported","FailedToProcessSsoHandler","FailedToRetrieveSsoToken","CannotFindCommand","FailedToRunSsoStep","FailedToRunDedupStep","SsoActivityHandlerIsNull","AuthorizationHeaderAlreadyExists","BasicCredentialAlreadyExists","EmptyParameter","DuplicateHttpsOptionProperty","DuplicateApiKeyInHeader","DuplicateApiKeyInQueryParam","OnlySupportInQueryActivity","OnlySupportInLinkQueryActivity","ErrorWithCode","Error","constructor","message","code","super","this","Object","setPrototypeOf","prototype","name","setLogLevel","level","internalLogger","getLogLevel","logLevel","undefined","defaultLogger","verbose","console","debug","info","warn","error","log","x","Warn","Info","Verbose","logFunction","trim","timestamp","Date","toUTCString","logHeader","logMessage","customLogger","customLogFunction","setLogger","logger","setLogFunction","parseJwt","token","tokenObj","jwtDecode","exp","InternalError","err","errorMsg","formatString","str","replacements","args","replace","match","number","validateScopesType","value","String","Array","isArray","length","every","item","InvalidParameter","AppCredential","authConfig","RuntimeNotSupported","getToken","scopes","options","Promise","reject","OnBehalfOfUserCredential","ssoToken","config","getUserInfo","TeamsUserCredential","loadAndValidateConfig","initialized","login","resources","scopesStr","join","result","init","app","initialize","params","url","initiateLoginEndpoint","clientId","encodeURI","loginHint","width","height","authentication","authenticate","ConsentFailed","resultJson","JSON","parse","failedToParseResult","InvalidResponse","usingPreviousAuthPage","sessionStorage","setSessionStorage","getSSOToken","scopeStr","tokenResponse","scopesArray","split","domain","window","location","origin","account","msalInstance","getAccountByUsername","scopesRequestForAcquireTokenSilent","redirectUri","acquireTokenSilent","acquireTokenSilentFailedMessage","scopesRequestForSsoSilent","ssoSilent","ssoSilentFailedMessage","UiRequiredError","accessToken","tokenResponseObject","tokenObject","ver","expiresOnTimestamp","parseAccessTokenFromAuthCodeTokenResponse","userInfo","displayName","objectId","oid","tenantId","tid","preferredUserName","preferred_username","upn","getUserInfoFromSsoToken","getTenantIdAndLoginHintFromSsoToken","msalConfig","auth","authority","cache","cacheLocation","PublicClientApplication","now","getAuthToken","missingValues","push","sessionStorageValues","keys","forEach","key","setItem","errorMessage","TeamsBotSsoPrompt","dialogId","settings","beginDialog","dc","continueDialog","createApiClient","apiEndpoint","authProvider","instance","axios","create","baseURL","interceptors","request","use","async","AddAuthenticationInfo","BearerTokenAuthProvider","headers","AuthorizationInfoAlreadyExists","BasicAuthProvider","userName","password","ApiKeyProvider","keyName","keyValue","keyLocation","ApiKeyLocation","NotificationTargetType","AdaptiveCardResponse","InvokeResponseErrorCode","SearchScope","CertificateAuthProvider","certOption","createPemCertOption","cert","createPfxCertOption","pfx","BotSsoExecutionDialog","dedupStorage","ssoPromptSettings","addCommand","handler","triggerPatterns","run","context","accessor","onEndDialog","handleMessageExtensionQueryWithSSO","logic","adapter","registerHandler","actionHandler","registerHandlers","actionHandlers","parent","type","Channel","sendMessage","text","onError","sendAdaptiveCard","card","commands","registerCommand","command","registerCommands","registerSsoCommand","ssoCommand","registerSsoCommands","ssoCommands","requestHandler","req","res","Person","installations","findMember","predicate","scope","findChannel","findAllMembers","findAllChannels","conversationReference","channels","members","getTeamDetails","target"],"mappings":"4LAMYA,EC2BAC,GD3BZ,SAAYD,GAIVA,EAAA,iBAAA,mBAKAA,EAAA,qBAAA,uBAKAA,EAAA,mBAAA,qBAKAA,EAAA,cAAA,gBAKAA,EAAA,oBAAA,sBAKAA,EAAA,yBAAA,2BAKAA,EAAA,0BAAA,4BAKAA,EAAA,kBAAA,oBAKAA,EAAA,mBAAA,qBAKAA,EAAA,qBAAA,uBAKAA,EAAA,8BAAA,gCAKAA,EAAA,oBAAA,sBAKAA,EAAA,cAAA,gBAKAA,EAAA,gBAAA,kBAKAA,EAAA,kBAAA,oBAKAA,EAAA,aAAA,eAKAA,EAAA,gBAAA,kBAKAA,EAAA,gBAAA,kBAKAA,EAAA,+BAAA,gCACD,CA/FD,CAAYA,IAAAA,EA+FX,CAAA,UAKYE,GAEKA,EAAoBC,qBAAG,wCACvBD,EAAsBE,uBAAG,oCACzBF,EAA8BG,+BAAG,6CACjCH,EAA4BI,6BAC1C,4DACcJ,EAAoCK,qCAClD,+CAGcL,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,EACAC,GAEA,OAAOtJ,QAAQC,OACb,IAAIxE,EACFiD,EAAazE,EAAaM,2BAA4B,eACtDR,EAAU6F,qBAGhB"}
1
+ {"version":3,"file":"index.esm2017.js","sources":["../../src/core/errors.ts","../../src/util/logger.ts","../../src/util/utils.ts","../../src/credential/appCredential.browser.ts","../../src/credential/onBehalfOfUserCredential.browser.ts","../../src/credential/teamsUserCredential.browser.ts","../../src/bot/teamsBotSsoPrompt.browser.ts","../../src/apiClient/apiClient.ts","../../src/apiClient/bearerTokenAuthProvider.ts","../../src/apiClient/basicAuthProvider.browser.ts","../../src/apiClient/apiKeyProvider.browser.ts","../../src/conversation/interface.ts","../../src/conversationWithCloudAdapter/notification.browser.ts","../../src/apiClient/certificateAuthProvider.browser.ts","../../src/conversation/sso/botSsoExecutionDialog.browser.ts","../../src/messageExtension/executeWithSSO.browser.ts","../../src/conversationWithCloudAdapter/cardAction.browser.ts","../../src/conversationWithCloudAdapter/command.browser.ts","../../src/conversationWithCloudAdapter/conversation.browser.ts"],"sourcesContent":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"names":["ErrorCode","LogLevel","ErrorMessage","InvalidConfiguration","ConfigurationNotExists","ResourceConfigurationNotExists","MissingResourceConfiguration","AuthenticationConfigurationNotExists","BrowserRuntimeNotSupported","NodejsRuntimeNotSupported","FailToAcquireTokenOnBehalfOfUser","OnlyMSTeamsChannelSupported","FailedToProcessSsoHandler","FailedToRetrieveSsoToken","CannotFindCommand","FailedToRunSsoStep","FailedToRunDedupStep","SsoActivityHandlerIsNull","AuthorizationHeaderAlreadyExists","BasicCredentialAlreadyExists","EmptyParameter","DuplicateHttpsOptionProperty","DuplicateApiKeyInHeader","DuplicateApiKeyInQueryParam","OnlySupportInQueryActivity","OnlySupportInLinkQueryActivity","ErrorWithCode","Error","constructor","message","code","super","this","Object","setPrototypeOf","prototype","name","setLogLevel","level","internalLogger","getLogLevel","logLevel","undefined","defaultLogger","verbose","console","debug","info","warn","error","log","x","Warn","Info","Verbose","logFunction","trim","timestamp","Date","toUTCString","logHeader","logMessage","customLogger","customLogFunction","setLogger","logger","setLogFunction","parseJwt","token","tokenObj","jwtDecode","exp","InternalError","err","errorMsg","formatString","str","replacements","args","replace","match","number","validateScopesType","value","String","Array","isArray","length","every","item","InvalidParameter","AppCredential","authConfig","RuntimeNotSupported","getToken","scopes","options","Promise","reject","OnBehalfOfUserCredential","ssoToken","config","getUserInfo","TeamsUserCredential","loadAndValidateConfig","initialized","login","resources","scopesStr","join","result","init","app","initialize","params","url","initiateLoginEndpoint","clientId","encodeURI","loginHint","width","height","authentication","authenticate","ConsentFailed","resultJson","JSON","parse","failedToParseResult","InvalidResponse","usingPreviousAuthPage","sessionStorage","setSessionStorage","getSSOToken","scopeStr","tokenResponse","scopesArray","split","domain","window","location","origin","account","msalInstance","getAccountByUsername","scopesRequestForAcquireTokenSilent","redirectUri","acquireTokenSilent","acquireTokenSilentFailedMessage","scopesRequestForSsoSilent","ssoSilent","ssoSilentFailedMessage","UiRequiredError","accessToken","tokenResponseObject","tokenObject","ver","expiresOnTimestamp","parseAccessTokenFromAuthCodeTokenResponse","userInfo","displayName","objectId","oid","tenantId","tid","preferredUserName","preferred_username","upn","getUserInfoFromSsoToken","getTenantIdAndLoginHintFromSsoToken","msalConfig","auth","authority","cache","cacheLocation","PublicClientApplication","now","getAuthToken","missingValues","push","sessionStorageValues","keys","forEach","key","setItem","errorMessage","TeamsBotSsoPrompt","dialogId","settings","beginDialog","dc","continueDialog","createApiClient","apiEndpoint","authProvider","instance","axios","create","baseURL","interceptors","request","use","async","AddAuthenticationInfo","BearerTokenAuthProvider","headers","AuthorizationInfoAlreadyExists","BasicAuthProvider","userName","password","ApiKeyProvider","keyName","keyValue","keyLocation","ApiKeyLocation","NotificationTargetType","AdaptiveCardResponse","InvokeResponseErrorCode","SearchScope","CertificateAuthProvider","certOption","createPemCertOption","cert","createPfxCertOption","pfx","BotSsoExecutionDialog","dedupStorage","ssoPromptSettings","addCommand","handler","triggerPatterns","run","context","accessor","onEndDialog","handleMessageExtensionQueryWithSSO","logic","adapter","registerHandler","actionHandler","registerHandlers","actionHandlers","parent","type","Channel","sendMessage","text","onError","sendAdaptiveCard","card","commands","registerCommand","command","registerCommands","registerSsoCommand","ssoCommand","registerSsoCommands","ssoCommands","requestHandler","req","res","Person","installations","findMember","predicate","scope","findChannel","findAllMembers","findAllChannels","conversationReference","channels","members","getTeamDetails","target"],"mappings":"4LAQYA,EC+BAC,GD/BZ,SAAYD,GAIVA,EAAA,iBAAA,mBAKAA,EAAA,qBAAA,uBAKAA,EAAA,mBAAA,qBAKAA,EAAA,cAAA,gBAKAA,EAAA,oBAAA,sBAKAA,EAAA,yBAAA,2BAKAA,EAAA,0BAAA,4BAKAA,EAAA,kBAAA,oBAKAA,EAAA,mBAAA,qBAKAA,EAAA,qBAAA,uBAKAA,EAAA,8BAAA,gCAKAA,EAAA,oBAAA,sBAKAA,EAAA,cAAA,gBAKAA,EAAA,gBAAA,kBAKAA,EAAA,kBAAA,oBAKAA,EAAA,aAAA,eAKAA,EAAA,gBAAA,kBAKAA,EAAA,gBAAA,kBAKAA,EAAA,+BAAA,gCACD,CA/FD,CAAYA,IAAAA,EA+FX,CAAA,UAMYE,GAEKA,EAAoBC,qBAAG,wCACvBD,EAAsBE,uBAAG,oCACzBF,EAA8BG,+BAAG,6CACjCH,EAA4BI,6BAC1C,4DACcJ,EAAoCK,qCAClD,+CAGcL,EAA0BM,2BAAG,mCAC7BN,EAAyBO,0BAAG,gCAG5BP,EAAgCQ,iCAC9C,wDAGcR,EAA2BS,4BAAG,4CAE9BT,EAAyBU,0BAAG,qCAG5BV,EAAwBW,yBACtC,4EAGcX,EAAiBY,kBAAG,2BAEpBZ,EAAkBa,mBAAG,kDAErBb,EAAoBc,qBAAG,0DAGvBd,EAAwBe,yBACtC,mFAGcf,EAAgCgB,iCAAG,uCACnChB,EAA4BiB,6BAAG,mCAE/BjB,EAAckB,eAAG,yBACjBlB,EAA4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D,EAAazE,EAAaM,2BAA4B,mBACtDR,EAAU6F,sBAgBT,eAAA+K,CACLJ,GAEA,OAAOvK,QAAQC,OACb,IAAIxE,EACFiD,EAAazE,EAAaM,2BAA4B,mBACtDR,EAAU6F,mDAnQhB,WAAAjE,CAAYiN,EAAuBgC,GACjC,MAAM,IAAInP,EACRiD,EAAazE,EAAaM,2BAA4B,wBACtDR,EAAU6F,qBAeP,WAAAwJ,CACLC,EACAC,GAEA,OAAOtJ,QAAQC,OACb,IAAIxE,EACFiD,EAAazE,EAAaM,2BAA4B,wBACtDR,EAAU6F,sBAgBT,gBAAA2J,CACLC,EACAF,GAEA,OAAOtJ,QAAQC,OACb,IAAIxE,EACFiD,EAAazE,EAAaM,2BAA4B,wBACtDR,EAAU6F,sBAaT,QAAAiL,GACL,OAAO7K,QAAQC,OACb,IAAIxE,EACFiD,EAAazE,EAAaM,2BAA4B,wBACtDR,EAAU6F,sBAaT,OAAAkL,GACL,OAAO9K,QAAQC,OACb,IAAIxE,EACFiD,EAAazE,EAAaM,2BAA4B,wBACtDR,EAAU6F,sBAUT,cAAAmL,GACL,OAAO/K,QAAQC,OACb,IAAIxE,EACFiD,EAAazE,EAAaM,2BAA4B,wBACtDR,EAAU6F,kDAvWhBoL,EACAxB,EACAF,GAEA,OAAOtJ,QAAQC,OACb,IAAIxE,EACFiD,EAAazE,EAAaM,2BAA4B,oBACtDR,EAAU6F,qBAGhB,uBApCEoL,EACA3B,EACAC,GAEA,OAAOtJ,QAAQC,OACb,IAAIxE,EACFiD,EAAazE,EAAaM,2BAA4B,eACtDR,EAAU6F,qBAGhB"}
@@ -1,4 +1,4 @@
1
- import{jwtDecode as e}from"jwt-decode";import{ConfidentialClientApplication as t}from"@azure/msal-node";import{createHash as n}from"crypto";import{CardFactory as i,MessageFactory as o,StatusCodes as a,MemoryStorage as r,UserState as s,ConversationState as c,loadAuthConfigFromEnv as d,CloudAdapter as l}from"@microsoft/agents-hosting";import{TeamsInfo as u,verifyStateOperationName as h,tokenExchangeOperationName as p,TeamsActivityHandler as v}from"@microsoft/agents-hosting-teams";import{Dialog as m,ComponentDialog as f,WaterfallDialog as y,DialogSet as g,DialogTurnStatus as w}from"@microsoft/agents-hosting-dialogs";import{ActivityTypes as C,Channels as S,ActionTypes as A,Activity as T}from"@microsoft/agents-activity";import{v4 as I}from"uuid";import k from"axios";import{Agent as E}from"https";import*as x from"adaptivecards-templating";import*as R from"path";import*as b from"fs";var O,P;!function(e){e.InvalidParameter="InvalidParameter",e.InvalidConfiguration="InvalidConfiguration",e.InvalidCertificate="InvalidCertificate",e.InternalError="InternalError",e.ChannelNotSupported="ChannelNotSupported",e.FailedToRetrieveSsoToken="FailedToRetrieveSsoToken",e.FailedToProcessSsoHandler="FailedToProcessSsoHandler",e.CannotFindCommand="CannotFindCommand",e.FailedToRunSsoStep="FailedToRunSsoStep",e.FailedToRunDedupStep="FailedToRunDedupStep",e.SsoActivityHandlerIsUndefined="SsoActivityHandlerIsUndefined",e.RuntimeNotSupported="RuntimeNotSupported",e.ConsentFailed="ConsentFailed",e.UiRequiredError="UiRequiredError",e.TokenExpiredError="TokenExpiredError",e.ServiceError="ServiceError",e.FailedOperation="FailedOperation",e.InvalidResponse="InvalidResponse",e.AuthorizationInfoAlreadyExists="AuthorizationInfoAlreadyExists"}(O||(O={}));class F{}F.InvalidConfiguration="{0} in configuration is invalid: {1}.",F.ConfigurationNotExists="Configuration does not exist. {0}",F.ResourceConfigurationNotExists="{0} resource configuration does not exist.",F.MissingResourceConfiguration="Missing resource configuration with type: {0}, name: {1}.",F.AuthenticationConfigurationNotExists="Authentication configuration does not exist.",F.BrowserRuntimeNotSupported="{0} is not supported in browser.",F.NodejsRuntimeNotSupported="{0} is not supported in Node.",F.FailToAcquireTokenOnBehalfOfUser="Failed to acquire access token on behalf of user: {0}",F.OnlyMSTeamsChannelSupported="{0} is only supported in MS Teams Channel",F.FailedToProcessSsoHandler="Failed to process sso handler: {0}",F.FailedToRetrieveSsoToken="Failed to retrieve sso token, user failed to finish the AAD consent flow.",F.CannotFindCommand="Cannot find command: {0}",F.FailedToRunSsoStep="Failed to run dialog to retrieve sso token: {0}",F.FailedToRunDedupStep="Failed to run dialog to remove duplicated messages: {0}",F.SsoActivityHandlerIsNull="Sso command can only be used or added when sso activity handler is not undefined",F.AuthorizationHeaderAlreadyExists="Authorization header already exists!",F.BasicCredentialAlreadyExists="Basic credential already exists!",F.EmptyParameter="Parameter {0} is empty",F.DuplicateHttpsOptionProperty="Axios HTTPS agent already defined value for property {0}",F.DuplicateApiKeyInHeader="The request already defined api key in request header with name {0}.",F.DuplicateApiKeyInQueryParam="The request already defined api key in query parameter with name {0}.",F.OnlySupportInQueryActivity="The handleMessageExtensionQueryWithToken only support in handleTeamsMessagingExtensionQuery with composeExtension/query type.",F.OnlySupportInLinkQueryActivity="The handleMessageExtensionLinkQueryWithSSO only support in handleTeamsAppBasedLinkQuery with composeExtension/queryLink type.";class D extends Error{constructor(e,t){if(!t)return super(e),this;super(e),Object.setPrototypeOf(this,D.prototype),this.name=`${new.target.name}.${t}`,this.code=t}}function M(e){H.level=e}function N(){return H.level}!function(e){e[e.Verbose=0]="Verbose",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(P||(P={}));const H=new class{constructor(e,t){this.level=void 0,this.defaultLogger={verbose:console.debug,info:console.info,warn:console.warn,error:console.error},this.name=e,this.level=t}error(e){this.log(P.Error,(e=>e.error),e)}warn(e){this.log(P.Warn,(e=>e.warn),e)}info(e){this.log(P.Info,(e=>e.info),e)}verbose(e){this.log(P.Verbose,(e=>e.verbose),e)}log(e,t,n){if(""===n.trim())return;const i=(new Date).toUTCString();let o;o=this.name?`[${i}] : @microsoft/teamsfx - ${this.name} : ${P[e]} - `:`[${i}] : @microsoft/teamsfx : ${P[e]} - `;const a=`${o}${n}`;void 0!==this.level&&this.level<=e&&(this.customLogger?t(this.customLogger)(a):this.customLogFunction?this.customLogFunction(e,a):t(this.defaultLogger)(a))}};function B(e){H.customLogger=e}function U(e){H.customLogFunction=e}function j(t){try{const n=e(t);if(!n||!n.exp)throw new D("Decoded token is null or exp claim does not exists.",O.InternalError);return n}catch(e){const t="Parse jwt token failed in node env with error: "+e.message;throw H.error(t),new D(t,O.InternalError)}}function q(e,...t){const n=t;return e.replace(/{(\d+)}/g,(function(e,t){return void 0!==n[t]?n[t]:e}))}function L(e){if("string"==typeof e||e instanceof String)return;if(Array.isArray(e)&&0===e.length)return;if(Array.isArray(e)&&e.length>0&&e.every((e=>"string"==typeof e)))return;const t="The type of scopes is not valid, it must be string or string array";throw H.error(t),new D(t,O.InvalidParameter)}function $(e){return("string"==typeof e?e.split(" "):e).filter((e=>null!==e&&""!==e))}function z(e){const i=(o=e.authorityHost,a=e.tenantId,o.replace(/\/+$/g,"")+"/"+a);var o,a;const r=function(e){if(!e)return;const t=/(-+BEGIN CERTIFICATE-+)(\n\r?|\r\n?)([A-Za-z0-9+/\n\r]+=*)(\n\r?|\r\n?)(-+END CERTIFICATE-+)/.exec(e);if(!t){const e="The certificate content does not contain a PEM-encoded certificate.";throw H.error(e),new D(e,O.InvalidCertificate)}return{thumbprintSha256:n("sha256").update(Buffer.from(t[3],"base64")).digest("hex").toUpperCase(),privateKey:e}}(e.certificateContent),s={clientId:e.clientId,authority:i};return r?s.clientCertificate=r:s.clientSecret=e.clientSecret,new t({auth:s})}class K{constructor(e){H.info("Create M365 tenant credential");const t=this.loadAndValidateConfig(e);this.msalClient=z(t)}async getToken(e,t){let n;L(e);const i="string"==typeof e?e:e.join(" ");H.info("Get access token with scopes: "+i);try{const t=$(e),i=await this.msalClient.acquireTokenByClientCredential({scopes:t});i&&(n={token:i.accessToken,expiresOnTimestamp:i.expiresOn.getTime()})}catch(e){const t="Get M365 tenant credential failed with error: "+e.message;throw H.error(t),new D(t,O.ServiceError)}if(!n){const e="Get M365 tenant credential access token failed with empty access token";throw H.error(e),new D(e,O.InternalError)}return n}loadAndValidateConfig(e){if(H.verbose("Validate authentication configuration"),e.clientId&&(e.clientSecret||e.certificateContent)&&e.tenantId&&e.authorityHost)return e;const t=[];e.clientId||t.push("clientId"),e.clientSecret||e.certificateContent||t.push("clientSecret or certificateContent"),e.tenantId||t.push("tenantId"),e.authorityHost||t.push("authorityHost");const n=q(F.InvalidConfiguration,t.join(", "),"undefined");throw H.error(n),new D(n,O.InvalidConfiguration)}}class G{constructor(e,t){H.info("Get on behalf of user credential");const n=[];if(t.clientId||n.push("clientId"),t.authorityHost||n.push("authorityHost"),t.clientSecret||t.certificateContent||n.push("clientSecret or certificateContent"),t.tenantId||n.push("tenantId"),0!=n.length){const e=q(F.InvalidConfiguration,n.join(", "),"undefined");throw H.error(e),new D(e,O.InvalidConfiguration)}this.msalClient=z(t);const i=j(e);this.ssoToken={token:e,expiresOnTimestamp:i.exp}}async getToken(e,t){L(e);const n=$(e);let i;if(n.length){let e;H.info("Get access token with scopes: "+n.join(" "));try{e=await this.msalClient.acquireTokenOnBehalfOf({oboAssertion:this.ssoToken.token,scopes:n})}catch(e){throw this.generateAuthServerError(e)}if(!e){const e="Access token is null";throw H.error(e),new D(q(F.FailToAcquireTokenOnBehalfOfUser,e),O.InternalError)}i={token:e.accessToken,expiresOnTimestamp:e.expiresOn.getTime()}}else{if(H.info("Get SSO token."),Math.floor(Date.now()/1e3)>this.ssoToken.expiresOnTimestamp){const e="Sso token has already expired.";throw H.error(e),new D(e,O.TokenExpiredError)}i=this.ssoToken}return i}getUserInfo(){return H.info("Get basic user info from SSO token"),function(e){if(!e){const e="SSO token is undefined.";throw H.error(e),new D(e,O.InvalidParameter)}const t=j(e),n={displayName:t.name,objectId:t.oid,tenantId:t.tid,preferredUserName:""};return"2.0"===t.ver?n.preferredUserName=t.preferred_username:"1.0"===t.ver&&(n.preferredUserName=t.upn),n}(this.ssoToken.token)}generateAuthServerError(e){const t=e.errorMessage;if("InteractionRequiredAuthError"===e.name){const e="Failed to get access token from AAD server, interaction required: "+t;return H.warn(e),new D(e,O.UiRequiredError)}if(t&&t.indexOf("AADSTS50013")>=0){const e="Failed to get access token from AAD server, assertion is invalid because of various reasons: "+t;return H.error(e),new D(e,O.TokenExpiredError)}{const e=q(F.FailToAcquireTokenOnBehalfOfUser,t);return H.error(e),new D(e,O.ServiceError)}}}class Q{constructor(e){throw new D(q(F.NodejsRuntimeNotSupported,"TeamsUserCredential"),O.RuntimeNotSupported)}login(e,t){return Promise.reject(new D(q(F.NodejsRuntimeNotSupported,"TeamsUserCredential"),O.RuntimeNotSupported))}getToken(e,t){return Promise.reject(new D(q(F.NodejsRuntimeNotSupported,"TeamsUserCredential"),O.RuntimeNotSupported))}getUserInfo(e){return Promise.reject(new D(q(F.NodejsRuntimeNotSupported,"TeamsUserCredential"),O.RuntimeNotSupported))}}const V="invokeResponse";class _{constructor(e,t){this.id=e,this.failureDetail=t}}class W extends m{constructor(e,t,n,i){super(n),this.initiateLoginEndpoint=t,this.authConfig=e,this.settings=i,L(this.settings.scopes),function(e){if(e.clientId&&(e.clientSecret||e.certificateContent)&&e.tenantId&&e.authorityHost)return;const t=[];e.clientId||t.push("clientId"),e.clientSecret||e.certificateContent||t.push("clientSecret or certificateContent"),e.tenantId||t.push("tenantId"),e.authorityHost||t.push("authorityHost");const n=q(F.InvalidConfiguration,t.join(", "),"undefined");throw H.error(n),new D(n,O.InvalidConfiguration)}(this.authConfig),H.info("Create a new Teams Bot SSO Prompt")}async beginDialog(e){var t;H.info("Begin Teams Bot SSO Prompt"),this.ensureMsTeamsChannel(e);let n=9e5;if(this.settings.timeout){if("number"!=typeof this.settings.timeout){const e="type of timeout property in teamsBotSsoPromptSettings should be number.";throw H.error(e),new D(e,O.InvalidParameter)}if(this.settings.timeout<=0){const e="value of timeout property in teamsBotSsoPromptSettings should be positive.";throw H.error(e),new D(e,O.InvalidParameter)}n=this.settings.timeout}void 0===this.settings.endOnInvalidMessage&&(this.settings.endOnInvalidMessage=!0);const i=null===(t=e.activeDialog)||void 0===t?void 0:t.state;return i.state={},i.options={},i.expires=(new Date).getTime()+n,await this.sendOAuthCardAsync(e.context),m.EndOfTurn}async continueDialog(e){var t;H.info("Continue Teams Bot SSO Prompt"),this.ensureMsTeamsChannel(e);const n=null===(t=e.activeDialog)||void 0===t?void 0:t.state,i=e.context.activity.type===C.Message;if((i||this.isTeamsVerificationInvoke(e.context)||this.isTokenExchangeRequestInvoke(e.context))&&(new Date).getTime()>n.expires)return H.warn("End Teams Bot SSO Prompt due to timeout"),await e.endDialog(void 0);if(this.isTeamsVerificationInvoke(e.context)||this.isTokenExchangeRequestInvoke(e.context)){const t=await this.recognizeToken(e);if(t.succeeded)return await e.endDialog(t.value)}else if(i&&this.settings.endOnInvalidMessage)return H.warn("End Teams Bot SSO Prompt due to invalid message"),await e.endDialog(void 0);return m.EndOfTurn}ensureMsTeamsChannel(e){if(e.context.activity.channelId!=S.Msteams){const e=q(F.OnlyMSTeamsChannelSupported,"Teams Bot SSO Prompt");throw H.error(e),new D(e,O.ChannelNotSupported)}}async sendOAuthCardAsync(e){H.verbose("Send OAuth card to get SSO token");const t=await u.getMember(e,e.activity.from.id);H.verbose("Get Teams member account user principal name: "+(t.userPrincipalName?t.userPrincipalName:""));const n=t.userPrincipalName?t.userPrincipalName:"",a=this.getSignInResource(n),r=i.oauthCard("","Teams SSO Sign In","Sign In",a);r.content.buttons[0].type=A.Signin;const s=o.attachment(r);await e.sendActivity(s)}getSignInResource(e){H.verbose("Get sign in authentication configuration");const t=`${this.initiateLoginEndpoint}?scope=${encodeURI(this.settings.scopes.join(" "))}&clientId=${this.authConfig.clientId}&tenantId=${this.authConfig.tenantId}&loginHint=${e}`;H.verbose("Sign in link: "+t);return{signInLink:t,tokenExchangeResource:{id:I()},tokenPostResource:{}}}async recognizeToken(e){const t=e.context;let n;if(this.isTokenExchangeRequestInvoke(t))if(H.verbose("Receive token exchange request"),t.activity.value&&this.isTokenExchangeRequest(t.activity.value)){const e=t.activity.value.token,i=new G(e,this.authConfig);let o;try{if(o=await i.getToken(this.settings.scopes),o){await t.sendActivity(this.getTokenExchangeInvokeResponse(a.OK,"",t.activity.value.id));const i=j(e).exp;n={ssoToken:e,ssoTokenExpiration:new Date(1e3*i).toISOString(),connectionName:"",token:o.token,expiration:o.expiresOnTimestamp.toString()}}}catch(e){const n="The bot is unable to exchange token. Ask for user consent.";H.info(n),await t.sendActivity(this.getTokenExchangeInvokeResponse(a.PRECONDITION_FAILED,n,t.activity.value.id))}}else{const e="The bot received an InvokeActivity that is missing a TokenExchangeInvokeRequest value. This is required to be sent with the InvokeActivity.";H.warn(e),await t.sendActivity(this.getTokenExchangeInvokeResponse(a.BAD_REQUEST,e))}else this.isTeamsVerificationInvoke(t)&&(H.verbose("Receive Teams state verification request"),await this.sendOAuthCardAsync(e.context),await t.sendActivity({type:V,value:{status:a.OK}}));return void 0!==n?{succeeded:!0,value:n}:{succeeded:!1}}getTokenExchangeInvokeResponse(e,t,n){return{type:V,value:{status:e,body:new _(n,t)}}}isTeamsVerificationInvoke(e){const t=e.activity;return t.type===C.Invoke&&t.name===h}isTokenExchangeRequestInvoke(e){const t=e.activity;return t.type===C.Invoke&&t.name===p}isTokenExchangeRequest(e){return e.hasOwnProperty("token")}}function J(e,t){const n=k.create({baseURL:e});return n.interceptors.request.use((async function(e){return await t.AddAuthenticationInfo(e)})),n}class Z{constructor(e){this.getToken=e}async AddAuthenticationInfo(e){const t=await this.getToken();if(e.headers||(e.headers={}),e.headers.Authorization)throw new D(F.AuthorizationHeaderAlreadyExists,O.AuthorizationInfoAlreadyExists);return e.headers.Authorization=`Bearer ${t}`,e}}class X{constructor(e,t){if(!e)throw new D(q(F.EmptyParameter,"username"),O.InvalidParameter);if(!t)throw new D(q(F.EmptyParameter,"password"),O.InvalidParameter);this.userName=e,this.password=t}AddAuthenticationInfo(e){return e.headers&&e.headers.Authorization?Promise.reject(new D(F.AuthorizationHeaderAlreadyExists,O.AuthorizationInfoAlreadyExists)):e.auth?Promise.reject(new D(F.BasicCredentialAlreadyExists,O.AuthorizationInfoAlreadyExists)):(e.auth={username:this.userName,password:this.password},Promise.resolve(e))}}class Y{constructor(e,t,n){if(!e)throw new D(q(F.EmptyParameter,"keyName"),O.InvalidParameter);if(!t)throw new D(q(F.EmptyParameter,"keyVaule"),O.InvalidParameter);this.keyName=e,this.keyValue=t,this.keyLocation=n}AddAuthenticationInfo(e){switch(this.keyLocation){case ee.Header:if(e.headers||(e.headers={}),e.headers[this.keyName])return Promise.reject(new D(q(F.DuplicateApiKeyInHeader,this.keyName),O.AuthorizationInfoAlreadyExists));e.headers[this.keyName]=this.keyValue;break;case ee.QueryParams:e.params||(e.params={});let t=!1;if(e.url){t=new URL(e.url,e.baseURL).searchParams.has(this.keyName)}if(e.params[this.keyName]||t)return Promise.reject(new D(q(F.DuplicateApiKeyInQueryParam,this.keyName),O.AuthorizationInfoAlreadyExists));e.params[this.keyName]=this.keyValue}return Promise.resolve(e)}}var ee,te,ne,ie;!function(e){e[e.Header=0]="Header",e[e.QueryParams=1]="QueryParams"}(ee||(ee={}));class oe{constructor(e){if(!e||0===Object.keys(e).length)throw new D(q(F.EmptyParameter,"certOption"),O.InvalidParameter);this.certOption=e}AddAuthenticationInfo(e){if(e.httpsAgent){const t=new Set(Object.keys(e.httpsAgent.options));for(const e of Object.keys(this.certOption))if(t.has(e))return Promise.reject(new D(q(F.DuplicateHttpsOptionProperty,e),O.InvalidParameter));Object.assign(e.httpsAgent.options,this.certOption)}else e.httpsAgent=new E(this.certOption);return Promise.resolve(e)}}function ae(e,t,n){if(0===e.length)throw new D(q(F.EmptyParameter,"cert"),O.InvalidParameter);if(0===t.length)throw new D(q(F.EmptyParameter,"key"),O.InvalidParameter);return{cert:e,key:t,passphrase:null==n?void 0:n.passphrase,ca:null==n?void 0:n.ca}}function re(e,t){if(0===e.length)throw new D(q(F.EmptyParameter,"pfx"),O.InvalidParameter);return{pfx:e,passphrase:null==t?void 0:t.passphrase}}!function(e){e.Channel="Channel",e.Group="Group",e.Person="Person"}(te||(te={})),function(e){e[e.ReplaceForInteractor=0]="ReplaceForInteractor",e[e.ReplaceForAll=1]="ReplaceForAll",e[e.NewForAll=2]="NewForAll"}(ne||(ne={})),function(e){e[e.BadRequest=400]="BadRequest",e[e.InternalServerError=500]="InternalServerError"}(ie||(ie={}));let se="BotSsoExecutionDialog",ce="TeamsFxSsoPrompt",de="CommandRouteDialog";class le extends f{constructor(e,t,n,i,o){super(null!=o?o:se),this.dedupStorageKeys=[],this.commandMapping=new Map,o&&(se=o,ce=o+ce,de=o+de);const a=new W(n,i,ce,t);this.addDialog(a),this.initialDialogId=de,this.dedupStorage=e,this.dedupStorageKeys=[];const r=new y(de,[this.commandRouteStep.bind(this)]);this.addDialog(r)}addCommand(e,t){const n=this.getCommandHash(t),i=new y(n,[this.ssoStep.bind(this),this.dedupStep.bind(this),async t=>{const n=t.result.tokenResponse,i=t.context,o=t.result.message;try{if(!n)throw new Error(F.FailedToRetrieveSsoToken);return await e(i,n,o),await t.endDialog()}catch(e){const n=q(F.FailedToProcessSsoHandler,e.message);return H.error(n),await t.endDialog(new D(n,O.FailedToProcessSsoHandler))}}]);this.commandMapping.set(n,t),this.addDialog(i)}getCommandHash(e){const t=(Array.isArray(e)?e:[e]).join();return t.replace(/[^a-zA-Z0-9]/g,"")+n("sha256").update(t).digest("hex").toLowerCase()}async run(e,t){const n=new g(t);n.add(this);const i=await n.createContext(e);this.ensureMsTeamsChannel(i);const o=await i.continueDialog();if(o&&o.status===w.empty)await i.beginDialog(this.id);else if(o&&o.status===w.complete&&o.result instanceof Error)throw o.result}getActivityText(e){let t=e.text;const n=e.removeRecipientMention();return n&&(t=n.toLowerCase().replace(/\n|\r\n/g,"").trim()),t}async commandRouteStep(e){const t=e.context,n=this.getActivityText(t.activity),i=this.getMatchesCommandId(n);if(i)return await e.beginDialog(i);const o=q(F.CannotFindCommand,t.activity.text);throw H.error(o),new D(o,O.CannotFindCommand)}async ssoStep(e){try{const t=e.context,n={text:this.getActivityText(t.activity)};return e.options.commandMessage=n,await e.beginDialog(ce)}catch(t){const n=q(F.FailedToRunSsoStep,t.message);return H.error(n),await e.endDialog(new D(n,O.FailedToRunSsoStep))}}async dedupStep(e){const t=e.result;if(!t)return H.error(F.FailedToRetrieveSsoToken),await e.endDialog(new D(F.FailedToRetrieveSsoToken,O.FailedToRunSsoStep));try{return t&&await this.shouldDedup(e.context)?m.EndOfTurn:await e.next({tokenResponse:t,message:e.options.commandMessage})}catch(t){const n=q(F.FailedToRunDedupStep,t.message);return H.error(n),await e.endDialog(new D(n,O.FailedToRunDedupStep))}}async onEndDialog(e){const t=e.activity.conversation.id,n=this.dedupStorageKeys.filter((e=>e.indexOf(t)>0));await this.dedupStorage.delete(n),this.dedupStorageKeys=this.dedupStorageKeys.filter((e=>e.indexOf(t)<0))}async shouldDedup(e){const t={eTag:e.activity.value.id},n=this.getStorageKey(e),i={[n]:t};try{await this.dedupStorage.write(i),this.dedupStorageKeys.push(n)}catch(e){if(e instanceof Error&&e.message.indexOf("eTag conflict"))return!0;throw e}return!1}getStorageKey(e){if(!e||!e.activity||!e.activity.conversation)throw new Error("Invalid context, can not get storage key!");const t=e.activity,n=t.channelId,i=t.conversation.id;if(t.type!==C.Invoke||t.name!==p)throw new Error("TokenExchangeState can only be used with Invokes of signin/tokenExchange.");const o=t.value;if(!o||!o.id)throw new Error("Invalid signin/tokenExchange. Missing activity.value.id.");return`${n}/${i}/${o.id}`}matchPattern(e,t){if(t){if("string"==typeof e){return new RegExp(e,"i").test(t)}if(e instanceof RegExp){const n=t.match(e);return null!=n&&n}}return!1}isPatternMatched(e,t){const n=Array.isArray(e)?e:[e];for(const e of n){return!!this.matchPattern(e,t)}return!1}getMatchesCommandId(e){for(const t of this.commandMapping){const n=t[1];if(this.isPatternMatched(n,e))return t[0]}}ensureMsTeamsChannel(e){if(e.context.activity.channelId!=S.Msteams){const e=q(F.OnlyMSTeamsChannelSupported,"SSO execution dialog");throw H.error(e),new D(e,O.ChannelNotSupported)}}}class ue{static attachAdaptiveCard(e,t){const n={$root:t};return{attachments:[i.adaptiveCard(new x.Template(e).expand(n))]}}static attachAdaptiveCardWithoutData(e){return{attachments:[i.adaptiveCard(e)]}}static attachHeroCard(e,t,n,o){return ue.attachContent(i.heroCard(e,t,n,o))}static attachSigninCard(e,t,n){return ue.attachContent(i.signinCard(e,t,n))}static attachO365ConnectorCard(e){return ue.attachContent(i.o365ConnectorCard(e))}static AttachReceiptCard(e){return ue.attachContent(i.receiptCard(e))}static attachThumbnailCard(e,t,n,o){return ue.attachContent(i.thumbnailCard(e,t,n,o))}static attachContent(e){return{attachments:[e]}}}var he,pe,ve;!function(e){e.AdaptiveCard="application/vnd.microsoft.card.adaptive",e.Message="application/vnd.microsoft.activity.message",e.Error="application/vnd.microsoft.error"}(he||(he={}));class me{static textMessage(e){if(!e)throw new Error("The text message cannot be null or empty");return{status:a.OK,body:{statusCode:a.OK,type:he.Message,value:e}}}static adaptiveCard(e){if(!e)throw new Error("The adaptive card content cannot be null or undefined");return{status:a.OK,body:{statusCode:a.OK,type:he.AdaptiveCard,value:e}}}static errorResponse(e,t){return{status:a.OK,body:{statusCode:e,type:he.Error,value:{code:e.toString(),message:t}}}}static createInvokeResponse(e,t){return{status:e,body:t}}}async function fe(e,t,n,i,o){const a=e.activity.value;if(!a.authentication||!a.authentication.token)return H.verbose("No AccessToken in request, return silentAuth for AccessToken"),function(e,t,n){const i=$(n);return{composeExtension:{type:"silentAuth",suggestedActions:{actions:[{type:"openUrl",value:`${t}?scope=${encodeURI(i.join(" "))}&clientId=${e.clientId}&tenantId=${e.tenantId}`,title:"Message Extension OAuth"}]}}}}(t,n,i);try{const e=new G(a.authentication.token,t),n=await e.getToken(i),r=j(a.authentication.token).exp,s={ssoToken:a.authentication.token,ssoTokenExpiration:new Date(1e3*r).toISOString(),token:n.token,expiration:n.expiresOnTimestamp.toString(),connectionName:""};if(o)return await o(s)}catch(o){if(o instanceof D&&o.code===O.UiRequiredError&&"composeExtension/query"===e.activity.name){H.verbose("User not consent yet, return 412 to user consent first.");const t={status:412},n=T.fromObject({value:t,type:C.InvokeResponse});await e.sendActivity(n)}else if(o instanceof D&&o.code===O.UiRequiredError&&"composeExtension/queryLink"===e.activity.name){H.verbose("User not consent yet, return auth card for user login");const o=function(e,t,n){const i=$(n);return{composeExtension:{type:"auth",suggestedActions:{actions:[{type:"openUrl",value:`${t}?scope=${encodeURI(i.join(" "))}&clientId=${e.clientId}&tenantId=${e.tenantId}`,title:"Message Extension OAuth"}]}}}}(t,n,i);return void await e.sendActivity(T.fromObject({value:{status:200,body:o},type:C.InvokeResponse}))}throw o}}async function ye(e,t,n,i,o){if("composeExtension/query"!=e.activity.name)throw H.error(F.OnlySupportInQueryActivity),new D(q(F.OnlySupportInQueryActivity),O.FailedOperation);return await fe(e,null!=t?t:{},n,i,o)}async function ge(e,t,n,i,o){if("composeExtension/queryLink"!=e.activity.name)throw H.error(F.OnlySupportInLinkQueryActivity),new D(q(F.OnlySupportInLinkQueryActivity),O.FailedOperation);return await fe(e,null!=t?t:{},n,i,o)}class we{constructor(e){this.actionHandlers=[],this.defaultMessage="Your response was sent to the app",e&&e.length>0&&this.actionHandlers.push(...e)}async onTurn(e,t){var n,a,r;if("adaptiveCard/action"===e.activity.name){const t=e.activity.value.action,s=t.verb;for(const c of this.actionHandlers)if((null===(n=c.triggerVerb)||void 0===n?void 0:n.toLowerCase())===(null==s?void 0:s.toLowerCase())){let n;try{n=await c.handleActionInvoked(e,t.data)}catch(t){const n=me.errorResponse(ie.InternalServerError,t.message);throw await this.sendInvokeResponse(e,n),t}switch(null===(a=n.body)||void 0===a?void 0:a.type){case he.AdaptiveCard:const t=null===(r=n.body)||void 0===r?void 0:r.value;if(!t){const t="Adaptive card content cannot be found in the response body";throw await this.sendInvokeResponse(e,me.errorResponse(ie.InternalServerError,t)),new Error(t)}t.refresh&&c.adaptiveCardResponse!==ne.NewForAll&&(c.adaptiveCardResponse=ne.ReplaceForAll);const a=o.attachment(i.adaptiveCard(t));c.adaptiveCardResponse===ne.NewForAll?(await this.sendInvokeResponse(e,me.textMessage(this.defaultMessage)),await e.sendActivity(a)):c.adaptiveCardResponse===ne.ReplaceForAll?(a.id=e.activity.replyToId,await e.updateActivity(a),await this.sendInvokeResponse(e,n)):await this.sendInvokeResponse(e,n);break;case he.Message:case he.Error:default:await this.sendInvokeResponse(e,n)}break}}await t()}async sendInvokeResponse(e,t){await e.sendActivity({type:C.InvokeResponse,value:t})}}class Ce{constructor(e,t){this.middleware=new we(null==t?void 0:t.actions),this.adapter=e.use(this.middleware)}registerHandler(e){e&&this.middleware.actionHandlers.push(e)}registerHandlers(e){e&&this.middleware.actionHandlers.push(...e)}}class Se{constructor(e,t,n){if(this.commandHandlers=[],this.ssoCommandHandlers=[],e=null!=e?e:[],t=null!=t?t:[],this.hasSsoCommand=t.length>0,this.ssoActivityHandler=n,this.hasSsoCommand&&!this.ssoActivityHandler)throw H.error(F.SsoActivityHandlerIsNull),new D(F.SsoActivityHandlerIsNull,O.SsoActivityHandlerIsUndefined);this.commandHandlers.push(...e);for(const e of t)this.addSsoCommand(e)}addSsoCommand(e){var t;null===(t=this.ssoActivityHandler)||void 0===t||t.addCommand((async(t,n,i)=>{const o=this.shouldTrigger(e.triggerPatterns,i.text);i.matches=Array.isArray(o)?o:void 0;const a=await e.handleCommandReceived(t,i,n);await this.processResponse(t,a)}),e.triggerPatterns),this.ssoCommandHandlers.push(e),this.hasSsoCommand=!0}async onTurn(e,t){var n,i;if(e.activity.type===C.Message){const t=this.getActivityText(e.activity);let i=!1;for(const n of this.commandHandlers){const o=this.shouldTrigger(n.triggerPatterns,t);if(o){const a={text:t};a.matches=Array.isArray(o)?o:void 0;const r=await n.handleCommandReceived(e,a);await this.processResponse(e,r),i=!0;break}}if(!i)for(const i of this.ssoCommandHandlers){if(this.shouldTrigger(i.triggerPatterns,t)){await(null===(n=this.ssoActivityHandler)||void 0===n?void 0:n.run(e));break}}}else this.hasSsoCommand&&await(null===(i=this.ssoActivityHandler)||void 0===i?void 0:i.run(e));await t()}async processResponse(e,t){if("string"==typeof t)await e.sendActivity(t);else{const n=t;n&&await e.sendActivity(n)}}matchPattern(e,t){if(t){if("string"==typeof e){return new RegExp(e,"i").test(t)}if(e instanceof RegExp){const n=t.match(e);return null!=n&&n}}return!1}shouldTrigger(e,t){const n=Array.isArray(e)?e:[e];for(const e of n){const n=this.matchPattern(e,t);if(n)return n}return!1}getActivityText(e){let t=e.text;const n=e.removeRecipientMention();return n&&(t=n.toLowerCase().replace(/\n|\r\n/g,"").trim()),t}}class Ae{constructor(e,t,n,i){this.ssoConfig=i,this.middleware=new Se(null==t?void 0:t.commands,null==t?void 0:t.ssoCommands,n),this.adapter=e.use(this.middleware)}registerCommand(e){e&&this.middleware.commandHandlers.push(e)}registerCommands(e){e&&this.middleware.commandHandlers.push(...e)}registerSsoCommand(e){this.validateSsoActivityHandler(),this.middleware.addSsoCommand(e)}registerSsoCommands(e){if(e.length>0){this.validateSsoActivityHandler();for(const t of e)this.middleware.addSsoCommand(t)}}validateSsoActivityHandler(){if(!this.middleware.ssoActivityHandler)throw H.error(F.SsoActivityHandlerIsNull),new D(F.SsoActivityHandlerIsNull,O.SsoActivityHandlerIsUndefined)}}function Te(e){return JSON.parse(JSON.stringify(e))}function Ie(e){var t,n;return`_${null===(t=e.conversation)||void 0===t?void 0:t.tenantId}_${null===(n=e.conversation)||void 0===n?void 0:n.id}`}function ke(e){var t,n,i,o,a;const r=null===(i=null===(n=null===(t=e.activity)||void 0===t?void 0:t.channelData)||void 0===n?void 0:n.team)||void 0===i?void 0:i.id;return r||(void 0===(null===(o=e.activity.conversation)||void 0===o?void 0:o.name)&&(null===(a=e.activity.conversation)||void 0===a?void 0:a.id)?e.activity.conversation.id:void 0)}!function(e){e[e.CurrentBotInstalled=0]="CurrentBotInstalled",e[e.CurrentBotMessaged=1]="CurrentBotMessaged",e[e.CurrentBotUninstalled=2]="CurrentBotUninstalled",e[e.TeamDeleted=3]="TeamDeleted",e[e.TeamRestored=4]="TeamRestored",e[e.Unknown=5]="Unknown"}(pe||(pe={}));class Ee{constructor(e){this.conversationReferenceStore=e.conversationReferenceStore}async onTurn(e,t){switch(this.classifyActivity(e.activity)){case pe.CurrentBotInstalled:case pe.TeamRestored:{const t=e.activity.getConversationReference();await this.conversationReferenceStore.add(Ie(t),t,{overwrite:!0});break}case pe.CurrentBotMessaged:await this.tryAddMessagedReference(e);break;case pe.CurrentBotUninstalled:case pe.TeamDeleted:{const t=e.activity.getConversationReference();await this.conversationReferenceStore.remove(Ie(t),t);break}}await t()}classifyActivity(e){var t,n;const i=e.type;if("installationUpdate"===i){const n=null===(t=e.action)||void 0===t?void 0:t.toLowerCase();return"add"===n||"add-upgrade"===n?pe.CurrentBotInstalled:pe.CurrentBotUninstalled}if("conversationUpdate"===i){const t=null===(n=e.channelData)||void 0===n?void 0:n.eventType;if("teamDeleted"===t)return pe.TeamDeleted;if("teamRestored"===t)return pe.TeamRestored}else if("message"===i)return pe.CurrentBotMessaged;return pe.Unknown}async tryAddMessagedReference(e){var t,n,i,o,a,r;const s=e.activity.getConversationReference(),c=null===(t=null==s?void 0:s.conversation)||void 0===t?void 0:t.conversationType;if("personal"===c||"groupChat"===c)await this.conversationReferenceStore.add(Ie(s),s,{overwrite:!1});else if("channel"===c){const t=null===(o=null===(i=null===(n=e.activity)||void 0===n?void 0:n.channelData)||void 0===i?void 0:i.team)||void 0===o?void 0:o.id,c=null===(r=null===(a=e.activity.channelData)||void 0===a?void 0:a.channel)||void 0===r?void 0:r.id;if(void 0!==t&&(void 0===c||t===c)){const e=Te(s);e.conversation.id=t,await this.conversationReferenceStore.add(Ie(e),e,{overwrite:!1})}}}}class xe{constructor(e){var t;this.localFileName=null!==(t=process.env.TEAMSFX_NOTIFICATION_STORE_FILENAME)&&void 0!==t?t:".notification.localstore.json",this.filePath=R.resolve(e,this.localFileName)}async add(e,t,n){if(n.overwrite||!await this.storeFileExists()){if(await this.storeFileExists()){const n=await this.readFromFile();await this.writeToFile(Object.assign(n,{[e]:t}))}else await this.writeToFile({[e]:t});return!0}return!1}async remove(e,t){if(!await this.storeFileExists())return!1;if(await this.storeFileExists()){const t=await this.readFromFile();void 0!==t[e]&&(delete t[e],await this.writeToFile(t))}return!0}async list(e,t){if(!await this.storeFileExists())return{data:[],continuationToken:""};const n=await this.readFromFile();return{data:Object.entries(n).map((e=>e[1])),continuationToken:""}}storeFileExists(){return new Promise((e=>{try{b.access(this.filePath,(t=>{e(!t)}))}catch(t){e(!1)}}))}readFromFile(){return new Promise(((e,t)=>{try{b.readFile(this.filePath,{encoding:"utf-8"},((n,i)=>{n?t(n):e(JSON.parse(i))}))}catch(e){t(e)}}))}async writeToFile(e){return new Promise(((t,n)=>{try{const i=JSON.stringify(e,void 0,2);b.writeFile(this.filePath,i,{encoding:"utf-8"},(e=>{e?n(e):t()}))}catch(e){n(e)}}))}}class Re{constructor(e,t){this.type=te.Channel,this.parent=e,this.info=t}async sendMessage(e,t){const n={};return await this.parent.adapter.continueConversation(this.parent.conversationReference,(async i=>{const o=await this.newConversation(i);await this.parent.adapter.continueConversation(o,(async i=>{try{const t=await i.sendActivity(e);n.id=null==t?void 0:t.id}catch(e){if(!t)throw e;await t(i,e)}}))})),n}async sendAdaptiveCard(e,t){const n={};return await this.parent.adapter.continueConversation(this.parent.conversationReference,(async o=>{const a=await this.newConversation(o);await this.parent.adapter.continueConversation(a,(async o=>{try{const t=await o.sendActivity({attachments:[i.adaptiveCard(e)],type:C.Message});n.id=null==t?void 0:t.id}catch(e){if(!t)throw e;await t(o,e)}}))}),!0),n}newConversation(e){const t=Te(e.activity.getConversationReference());return t.conversation.id=this.info.id||"",Promise.resolve(t)}}class be{constructor(e,t){this.type=te.Person,this.parent=e,this.account=t}async sendMessage(e,t){const n={};return await this.parent.adapter.continueConversation(this.parent.conversationReference,(async i=>{const o=await this.newConversation(i);await this.parent.adapter.continueConversation(o,(async i=>{try{const t=await i.sendActivity(e);n.id=null==t?void 0:t.id}catch(e){if(!t)throw e;await t(i,e)}}))})),n}async sendAdaptiveCard(e,t){const n={};return await this.parent.adapter.continueConversation(this.parent.conversationReference,(async o=>{const a=await this.newConversation(o);await this.parent.adapter.continueConversation(a,(async o=>{try{const t=await o.sendActivity({attachments:[i.adaptiveCard(e)],type:C.Message});n.id=null==t?void 0:t.id}catch(e){if(!t)throw e;await t(o,e)}}))}),!0),n}async newConversation(e){const t=Te(e.activity.getConversationReference()),n=e.turnState.get(this.parent.adapter.ConnectorClientKey),i={members:[this.account],isGroup:!1,agent:e.activity.recipient,tenantId:e.activity.conversation.tenantId,activity:e.activity,channelData:e.activity.channelData},o=await n.createConversationAsync(i);return t.conversation.id=o.id,t}}class Oe{constructor(e,t,n){this.adapter=e,this.conversationReference=t,this.type=function(e){var t;const n=null===(t=e.conversation)||void 0===t?void 0:t.conversationType;return"personal"===n?te.Person:"groupChat"===n?te.Group:"channel"===n?te.Channel:void 0}(t),this.botAppId=n}async sendMessage(e,t){const n={};return await this.adapter.continueConversation(this.conversationReference,(async i=>{try{const t=await i.sendActivity(e);n.id=null==t?void 0:t.id}catch(e){if(!t)throw e;await t(i,e)}})),n}async sendAdaptiveCard(e,t){const n={};return await this.adapter.continueConversation(this.conversationReference,(async o=>{try{const t={attachments:[i.adaptiveCard(e)],type:C.Message},a=await o.sendActivity(t);n.id=null==a?void 0:a.id}catch(e){if(!t)throw e;await t(o,e)}}),!0),n}async channels(){const e=[];if(this.type!==te.Channel)return e;let t=[];await this.adapter.continueConversation(this.conversationReference,(async e=>{const n=ke(e);void 0!==n&&(t=await u.getTeamChannels(e,n))}));for(const n of t)e.push(new Re(this,n));return e}async getPagedMembers(e,t){let n={data:[],continuationToken:""};return await this.adapter.continueConversation(this.conversationReference,(async i=>{const o=await u.getPagedMembers(i,e,t);n={data:o.members.map((e=>new be(this,e))),continuationToken:o.continuationToken}})),n}async getTeamDetails(){if(this.type!==te.Channel)return;let e;return await this.adapter.continueConversation(this.conversationReference,(async t=>{const n=ke(t);void 0!==n&&(e=await u.getTeamDetails(t,n))})),e}}class Pe{constructor(e,t){var n,i;(null==t?void 0:t.store)?this.conversationReferenceStore=t.store:this.conversationReferenceStore=new xe(R.resolve("1"===process.env.RUNNING_ON_AZURE&&null!==(n=process.env.TEMP)&&void 0!==n?n:"./")),this.adapter=e.use(new Ee({conversationReferenceStore:this.conversationReferenceStore})),this.botAppId=null!==(i=null==t?void 0:t.botAppId)&&void 0!==i?i:process.env.BOT_ID}buildTeamsBotInstallation(e){if(!e)throw new Error("conversationReference is required.");return new Oe(this.adapter,e,this.botAppId)}async validateInstallation(e){let t=!0;return await this.adapter.continueConversation(e,(async e=>{try{await u.getPagedMembers(e,1)}catch(e){"BotNotInConversationRoster"===e.code&&(t=!1)}})),t}async getPagedInstallations(e,t,n=!0){if(void 0===this.conversationReferenceStore||void 0===this.adapter)throw new Error("NotificationBot has not been initialized.");const i=await this.conversationReferenceStore.list(e,t),o=[];for(const e of i.data){let t;n&&(t=await this.validateInstallation(e)),!n||n&&t?o.push(new Oe(this.adapter,e,this.botAppId)):await this.conversationReferenceStore.remove(Ie(e),e)}return{data:o,continuationToken:i.continuationToken}}async findMember(e,t){for(const n of await this.installations())if(this.matchSearchScope(n,t)){const t=[];let i;do{const e=await n.getPagedMembers(void 0,i);i=e.continuationToken,t.push(...e.data)}while(i);for(const n of t)if(await e(n))return n}}async findChannel(e){for(const t of await this.installations())if(t.type===te.Channel){const n=await t.getTeamDetails();for(const i of await t.channels())if(await e(i,n))return i}}async findAllMembers(e,t){const n=[];for(const i of await this.installations())if(this.matchSearchScope(i,t)){const t=[];let o;do{const e=await i.getPagedMembers(void 0,o);o=e.continuationToken,t.push(...e.data)}while(o);for(const i of t)await e(i)&&n.push(i)}return n}async findAllChannels(e){const t=[];for(const n of await this.installations())if(n.type===te.Channel){const i=await n.getTeamDetails();for(const o of await n.channels())await e(o,i)&&t.push(o)}return t}matchSearchScope(e,t){return t=null!=t?t:ve.All,e.type===te.Channel&&!!(t&ve.Channel)||e.type===te.Group&&!!(t&ve.Group)||e.type===te.Person&&!!(t&ve.Person)}async installations(){let e;const t=[];do{const n=await this.getPagedInstallations(void 0,e);e=n.continuationToken,t.push(...n.data)}while(e);return t}}!function(e){e[e.Person=1]="Person",e[e.Group=2]="Group",e[e.Channel=4]="Channel",e[e.All=7]="All"}(ve||(ve={}));class Fe extends v{constructor(e){var t,n,i,o,a,d,l,u,h,p;super();const v=new r,m=null!==(n=null===(t=e.dialog)||void 0===t?void 0:t.userState)&&void 0!==n?n:new s(v),f=null!==(o=null===(i=e.dialog)||void 0===i?void 0:i.conversationState)&&void 0!==o?o:new c(v),y=null!==(d=null===(a=e.dialog)||void 0===a?void 0:a.dedupStorage)&&void 0!==d?d:v,g=e.aad,{scopes:w}=g,C=
1
+ import{jwtDecode as e}from"jwt-decode";import{ConfidentialClientApplication as t}from"@azure/msal-node";import{createHash as n}from"crypto";import{CardFactory as i,MessageFactory as o,StatusCodes as a,MemoryStorage as r,UserState as s,ConversationState as c,loadAuthConfigFromEnv as d,CloudAdapter as l}from"@microsoft/agents-hosting";import{TeamsInfo as u,TeamsActivityHandler as h}from"@microsoft/agents-hosting-extensions-teams";import{Dialog as p,ComponentDialog as v,WaterfallDialog as m,DialogSet as f,DialogTurnStatus as y}from"@microsoft/agents-hosting-dialogs";import{ActivityTypes as g,Channels as w,ActionTypes as C,Activity as S}from"@microsoft/agents-activity";import{v4 as A}from"uuid";import T from"axios";import{Agent as I}from"https";import*as k from"adaptivecards-templating";import*as E from"path";import*as x from"fs";var R,b;!function(e){e.InvalidParameter="InvalidParameter",e.InvalidConfiguration="InvalidConfiguration",e.InvalidCertificate="InvalidCertificate",e.InternalError="InternalError",e.ChannelNotSupported="ChannelNotSupported",e.FailedToRetrieveSsoToken="FailedToRetrieveSsoToken",e.FailedToProcessSsoHandler="FailedToProcessSsoHandler",e.CannotFindCommand="CannotFindCommand",e.FailedToRunSsoStep="FailedToRunSsoStep",e.FailedToRunDedupStep="FailedToRunDedupStep",e.SsoActivityHandlerIsUndefined="SsoActivityHandlerIsUndefined",e.RuntimeNotSupported="RuntimeNotSupported",e.ConsentFailed="ConsentFailed",e.UiRequiredError="UiRequiredError",e.TokenExpiredError="TokenExpiredError",e.ServiceError="ServiceError",e.FailedOperation="FailedOperation",e.InvalidResponse="InvalidResponse",e.AuthorizationInfoAlreadyExists="AuthorizationInfoAlreadyExists"}(R||(R={}));class O{}O.InvalidConfiguration="{0} in configuration is invalid: {1}.",O.ConfigurationNotExists="Configuration does not exist. {0}",O.ResourceConfigurationNotExists="{0} resource configuration does not exist.",O.MissingResourceConfiguration="Missing resource configuration with type: {0}, name: {1}.",O.AuthenticationConfigurationNotExists="Authentication configuration does not exist.",O.BrowserRuntimeNotSupported="{0} is not supported in browser.",O.NodejsRuntimeNotSupported="{0} is not supported in Node.",O.FailToAcquireTokenOnBehalfOfUser="Failed to acquire access token on behalf of user: {0}",O.OnlyMSTeamsChannelSupported="{0} is only supported in MS Teams Channel",O.FailedToProcessSsoHandler="Failed to process sso handler: {0}",O.FailedToRetrieveSsoToken="Failed to retrieve sso token, user failed to finish the AAD consent flow.",O.CannotFindCommand="Cannot find command: {0}",O.FailedToRunSsoStep="Failed to run dialog to retrieve sso token: {0}",O.FailedToRunDedupStep="Failed to run dialog to remove duplicated messages: {0}",O.SsoActivityHandlerIsNull="Sso command can only be used or added when sso activity handler is not undefined",O.AuthorizationHeaderAlreadyExists="Authorization header already exists!",O.BasicCredentialAlreadyExists="Basic credential already exists!",O.EmptyParameter="Parameter {0} is empty",O.DuplicateHttpsOptionProperty="Axios HTTPS agent already defined value for property {0}",O.DuplicateApiKeyInHeader="The request already defined api key in request header with name {0}.",O.DuplicateApiKeyInQueryParam="The request already defined api key in query parameter with name {0}.",O.OnlySupportInQueryActivity="The handleMessageExtensionQueryWithToken only support in handleTeamsMessagingExtensionQuery with composeExtension/query type.",O.OnlySupportInLinkQueryActivity="The handleMessageExtensionLinkQueryWithSSO only support in handleTeamsAppBasedLinkQuery with composeExtension/queryLink type.";class P extends Error{constructor(e,t){if(!t)return super(e),this;super(e),Object.setPrototypeOf(this,P.prototype),this.name=`${new.target.name}.${t}`,this.code=t}}function F(e){M.level=e}function D(){return M.level}!function(e){e[e.Verbose=0]="Verbose",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(b||(b={}));const M=new class{constructor(e,t){this.level=void 0,this.defaultLogger={verbose:console.debug,info:console.info,warn:console.warn,error:console.error},this.name=e,this.level=t}error(e){this.log(b.Error,(e=>e.error),e)}warn(e){this.log(b.Warn,(e=>e.warn),e)}info(e){this.log(b.Info,(e=>e.info),e)}verbose(e){this.log(b.Verbose,(e=>e.verbose),e)}log(e,t,n){if(""===n.trim())return;const i=(new Date).toUTCString();let o;o=this.name?`[${i}] : @microsoft/teamsfx - ${this.name} : ${b[e]} - `:`[${i}] : @microsoft/teamsfx : ${b[e]} - `;const a=`${o}${n}`;void 0!==this.level&&this.level<=e&&(this.customLogger?t(this.customLogger)(a):this.customLogFunction?this.customLogFunction(e,a):t(this.defaultLogger)(a))}};function N(e){M.customLogger=e}function H(e){M.customLogFunction=e}function B(t){try{const n=e(t);if(!n||!n.exp)throw new P("Decoded token is null or exp claim does not exists.",R.InternalError);return n}catch(e){const t="Parse jwt token failed in node env with error: "+e.message;throw M.error(t),new P(t,R.InternalError)}}function U(e,...t){const n=t;return e.replace(/{(\d+)}/g,(function(e,t){return void 0!==n[t]?n[t]:e}))}function j(e){if("string"==typeof e||e instanceof String)return;if(Array.isArray(e)&&0===e.length)return;if(Array.isArray(e)&&e.length>0&&e.every((e=>"string"==typeof e)))return;const t="The type of scopes is not valid, it must be string or string array";throw M.error(t),new P(t,R.InvalidParameter)}function q(e){return("string"==typeof e?e.split(" "):e).filter((e=>null!==e&&""!==e))}function L(e){const i=(o=e.authorityHost,a=e.tenantId,o.replace(/\/+$/g,"")+"/"+a);var o,a;const r=function(e){if(!e)return;const t=/(-+BEGIN CERTIFICATE-+)(\n\r?|\r\n?)([A-Za-z0-9+/\n\r]+=*)(\n\r?|\r\n?)(-+END CERTIFICATE-+)/.exec(e);if(!t){const e="The certificate content does not contain a PEM-encoded certificate.";throw M.error(e),new P(e,R.InvalidCertificate)}return{thumbprintSha256:n("sha256").update(Buffer.from(t[3],"base64")).digest("hex").toUpperCase(),privateKey:e}}(e.certificateContent),s={clientId:e.clientId,authority:i};return r?s.clientCertificate=r:s.clientSecret=e.clientSecret,new t({auth:s})}class ${constructor(e){M.info("Create M365 tenant credential");const t=this.loadAndValidateConfig(e);this.msalClient=L(t)}async getToken(e,t){let n;j(e);const i="string"==typeof e?e:e.join(" ");M.info("Get access token with scopes: "+i);try{const t=q(e),i=await this.msalClient.acquireTokenByClientCredential({scopes:t});i&&(n={token:i.accessToken,expiresOnTimestamp:i.expiresOn.getTime()})}catch(e){const t="Get M365 tenant credential failed with error: "+e.message;throw M.error(t),new P(t,R.ServiceError)}if(!n){const e="Get M365 tenant credential access token failed with empty access token";throw M.error(e),new P(e,R.InternalError)}return n}loadAndValidateConfig(e){if(M.verbose("Validate authentication configuration"),e.clientId&&(e.clientSecret||e.certificateContent)&&e.tenantId&&e.authorityHost)return e;const t=[];e.clientId||t.push("clientId"),e.clientSecret||e.certificateContent||t.push("clientSecret or certificateContent"),e.tenantId||t.push("tenantId"),e.authorityHost||t.push("authorityHost");const n=U(O.InvalidConfiguration,t.join(", "),"undefined");throw M.error(n),new P(n,R.InvalidConfiguration)}}class z{constructor(e,t){M.info("Get on behalf of user credential");const n=[];if(t.clientId||n.push("clientId"),t.authorityHost||n.push("authorityHost"),t.clientSecret||t.certificateContent||n.push("clientSecret or certificateContent"),t.tenantId||n.push("tenantId"),0!=n.length){const e=U(O.InvalidConfiguration,n.join(", "),"undefined");throw M.error(e),new P(e,R.InvalidConfiguration)}this.msalClient=L(t);const i=B(e);this.ssoToken={token:e,expiresOnTimestamp:i.exp}}async getToken(e,t){j(e);const n=q(e);let i;if(n.length){let e;M.info("Get access token with scopes: "+n.join(" "));try{e=await this.msalClient.acquireTokenOnBehalfOf({oboAssertion:this.ssoToken.token,scopes:n})}catch(e){throw this.generateAuthServerError(e)}if(!e){const e="Access token is null";throw M.error(e),new P(U(O.FailToAcquireTokenOnBehalfOfUser,e),R.InternalError)}i={token:e.accessToken,expiresOnTimestamp:e.expiresOn.getTime()}}else{if(M.info("Get SSO token."),Math.floor(Date.now()/1e3)>this.ssoToken.expiresOnTimestamp){const e="Sso token has already expired.";throw M.error(e),new P(e,R.TokenExpiredError)}i=this.ssoToken}return i}getUserInfo(){return M.info("Get basic user info from SSO token"),function(e){if(!e){const e="SSO token is undefined.";throw M.error(e),new P(e,R.InvalidParameter)}const t=B(e),n={displayName:t.name,objectId:t.oid,tenantId:t.tid,preferredUserName:""};return"2.0"===t.ver?n.preferredUserName=t.preferred_username:"1.0"===t.ver&&(n.preferredUserName=t.upn),n}(this.ssoToken.token)}generateAuthServerError(e){const t=e.errorMessage;if("InteractionRequiredAuthError"===e.name){const e="Failed to get access token from AAD server, interaction required: "+t;return M.warn(e),new P(e,R.UiRequiredError)}if(t&&t.indexOf("AADSTS50013")>=0){const e="Failed to get access token from AAD server, assertion is invalid because of various reasons: "+t;return M.error(e),new P(e,R.TokenExpiredError)}{const e=U(O.FailToAcquireTokenOnBehalfOfUser,t);return M.error(e),new P(e,R.ServiceError)}}}class K{constructor(e){throw new P(U(O.NodejsRuntimeNotSupported,"TeamsUserCredential"),R.RuntimeNotSupported)}login(e,t){return Promise.reject(new P(U(O.NodejsRuntimeNotSupported,"TeamsUserCredential"),R.RuntimeNotSupported))}getToken(e,t){return Promise.reject(new P(U(O.NodejsRuntimeNotSupported,"TeamsUserCredential"),R.RuntimeNotSupported))}getUserInfo(e){return Promise.reject(new P(U(O.NodejsRuntimeNotSupported,"TeamsUserCredential"),R.RuntimeNotSupported))}}var G,Q,V;!function(e){e.Channel="Channel",e.Group="Group",e.Person="Person"}(G||(G={})),function(e){e[e.ReplaceForInteractor=0]="ReplaceForInteractor",e[e.ReplaceForAll=1]="ReplaceForAll",e[e.NewForAll=2]="NewForAll"}(Q||(Q={})),function(e){e[e.BadRequest=400]="BadRequest",e[e.InternalServerError=500]="InternalServerError"}(V||(V={}));const _="signin/tokenExchange",W="invokeResponse";class J{constructor(e,t){this.id=e,this.failureDetail=t}}class Z extends p{constructor(e,t,n,i){super(n),this.initiateLoginEndpoint=t,this.authConfig=e,this.settings=i,j(this.settings.scopes),function(e){if(e.clientId&&(e.clientSecret||e.certificateContent)&&e.tenantId&&e.authorityHost)return;const t=[];e.clientId||t.push("clientId"),e.clientSecret||e.certificateContent||t.push("clientSecret or certificateContent"),e.tenantId||t.push("tenantId"),e.authorityHost||t.push("authorityHost");const n=U(O.InvalidConfiguration,t.join(", "),"undefined");throw M.error(n),new P(n,R.InvalidConfiguration)}(this.authConfig),M.info("Create a new Teams Bot SSO Prompt")}async beginDialog(e){var t;M.info("Begin Teams Bot SSO Prompt"),this.ensureMsTeamsChannel(e);let n=9e5;if(this.settings.timeout){if("number"!=typeof this.settings.timeout){const e="type of timeout property in teamsBotSsoPromptSettings should be number.";throw M.error(e),new P(e,R.InvalidParameter)}if(this.settings.timeout<=0){const e="value of timeout property in teamsBotSsoPromptSettings should be positive.";throw M.error(e),new P(e,R.InvalidParameter)}n=this.settings.timeout}void 0===this.settings.endOnInvalidMessage&&(this.settings.endOnInvalidMessage=!0);const i=null===(t=e.activeDialog)||void 0===t?void 0:t.state;return i.state={},i.options={},i.expires=(new Date).getTime()+n,await this.sendOAuthCardAsync(e.context),p.EndOfTurn}async continueDialog(e){var t;M.info("Continue Teams Bot SSO Prompt"),this.ensureMsTeamsChannel(e);const n=null===(t=e.activeDialog)||void 0===t?void 0:t.state,i=e.context.activity.type===g.Message;if((i||this.isTeamsVerificationInvoke(e.context)||this.isTokenExchangeRequestInvoke(e.context))&&(new Date).getTime()>n.expires)return M.warn("End Teams Bot SSO Prompt due to timeout"),await e.endDialog(void 0);if(this.isTeamsVerificationInvoke(e.context)||this.isTokenExchangeRequestInvoke(e.context)){const t=await this.recognizeToken(e);if(t.succeeded)return await e.endDialog(t.value)}else if(i&&this.settings.endOnInvalidMessage)return M.warn("End Teams Bot SSO Prompt due to invalid message"),await e.endDialog(void 0);return p.EndOfTurn}ensureMsTeamsChannel(e){if(e.context.activity.channelId!=w.Msteams){const e=U(O.OnlyMSTeamsChannelSupported,"Teams Bot SSO Prompt");throw M.error(e),new P(e,R.ChannelNotSupported)}}async sendOAuthCardAsync(e){M.verbose("Send OAuth card to get SSO token");const t=await u.getMember(e,e.activity.from.id);M.verbose("Get Teams member account user principal name: "+(t.userPrincipalName?t.userPrincipalName:""));const n=t.userPrincipalName?t.userPrincipalName:"",a=this.getSignInResource(n),r=i.oauthCard("","Teams SSO Sign In","Sign In",a);r.content.buttons[0].type=C.Signin;const s=o.attachment(r);await e.sendActivity(s)}getSignInResource(e){M.verbose("Get sign in authentication configuration");const t=`${this.initiateLoginEndpoint}?scope=${encodeURI(this.settings.scopes.join(" "))}&clientId=${this.authConfig.clientId}&tenantId=${this.authConfig.tenantId}&loginHint=${e}`;M.verbose("Sign in link: "+t);return{signInLink:t,tokenExchangeResource:{id:A()},tokenPostResource:{}}}async recognizeToken(e){const t=e.context;let n;if(this.isTokenExchangeRequestInvoke(t))if(M.verbose("Receive token exchange request"),t.activity.value&&this.isTokenExchangeRequest(t.activity.value)){const e=t.activity.value.token,i=new z(e,this.authConfig);let o;try{if(o=await i.getToken(this.settings.scopes),o){await t.sendActivity(this.getTokenExchangeInvokeResponse(a.OK,"",t.activity.value.id));const i=B(e).exp;n={ssoToken:e,ssoTokenExpiration:new Date(1e3*i).toISOString(),connectionName:"",token:o.token,expiration:o.expiresOnTimestamp.toString()}}}catch(e){const n="The bot is unable to exchange token. Ask for user consent.";M.info(n),await t.sendActivity(this.getTokenExchangeInvokeResponse(a.PRECONDITION_FAILED,n,t.activity.value.id))}}else{const e="The bot received an InvokeActivity that is missing a TokenExchangeInvokeRequest value. This is required to be sent with the InvokeActivity.";M.warn(e),await t.sendActivity(this.getTokenExchangeInvokeResponse(a.BAD_REQUEST,e))}else this.isTeamsVerificationInvoke(t)&&(M.verbose("Receive Teams state verification request"),await this.sendOAuthCardAsync(e.context),await t.sendActivity({type:W,value:{status:a.OK}}));return void 0!==n?{succeeded:!0,value:n}:{succeeded:!1}}getTokenExchangeInvokeResponse(e,t,n){return{type:W,value:{status:e,body:new J(n,t)}}}isTeamsVerificationInvoke(e){const t=e.activity;return t.type===g.Invoke&&"signin/verifyState"===t.name}isTokenExchangeRequestInvoke(e){const t=e.activity;return t.type===g.Invoke&&t.name===_}isTokenExchangeRequest(e){return e.hasOwnProperty("token")}}function X(e,t){const n=T.create({baseURL:e});return n.interceptors.request.use((async function(e){return await t.AddAuthenticationInfo(e)})),n}class Y{constructor(e){this.getToken=e}async AddAuthenticationInfo(e){const t=await this.getToken();if(e.headers||(e.headers={}),e.headers.Authorization)throw new P(O.AuthorizationHeaderAlreadyExists,R.AuthorizationInfoAlreadyExists);return e.headers.Authorization=`Bearer ${t}`,e}}class ee{constructor(e,t){if(!e)throw new P(U(O.EmptyParameter,"username"),R.InvalidParameter);if(!t)throw new P(U(O.EmptyParameter,"password"),R.InvalidParameter);this.userName=e,this.password=t}AddAuthenticationInfo(e){return e.headers&&e.headers.Authorization?Promise.reject(new P(O.AuthorizationHeaderAlreadyExists,R.AuthorizationInfoAlreadyExists)):e.auth?Promise.reject(new P(O.BasicCredentialAlreadyExists,R.AuthorizationInfoAlreadyExists)):(e.auth={username:this.userName,password:this.password},Promise.resolve(e))}}class te{constructor(e,t,n){if(!e)throw new P(U(O.EmptyParameter,"keyName"),R.InvalidParameter);if(!t)throw new P(U(O.EmptyParameter,"keyVaule"),R.InvalidParameter);this.keyName=e,this.keyValue=t,this.keyLocation=n}AddAuthenticationInfo(e){switch(this.keyLocation){case ne.Header:if(e.headers||(e.headers={}),e.headers[this.keyName])return Promise.reject(new P(U(O.DuplicateApiKeyInHeader,this.keyName),R.AuthorizationInfoAlreadyExists));e.headers[this.keyName]=this.keyValue;break;case ne.QueryParams:e.params||(e.params={});let t=!1;if(e.url){t=new URL(e.url,e.baseURL).searchParams.has(this.keyName)}if(e.params[this.keyName]||t)return Promise.reject(new P(U(O.DuplicateApiKeyInQueryParam,this.keyName),R.AuthorizationInfoAlreadyExists));e.params[this.keyName]=this.keyValue}return Promise.resolve(e)}}var ne;!function(e){e[e.Header=0]="Header",e[e.QueryParams=1]="QueryParams"}(ne||(ne={}));class ie{constructor(e){if(!e||0===Object.keys(e).length)throw new P(U(O.EmptyParameter,"certOption"),R.InvalidParameter);this.certOption=e}AddAuthenticationInfo(e){if(e.httpsAgent){const t=new Set(Object.keys(e.httpsAgent.options));for(const e of Object.keys(this.certOption))if(t.has(e))return Promise.reject(new P(U(O.DuplicateHttpsOptionProperty,e),R.InvalidParameter));Object.assign(e.httpsAgent.options,this.certOption)}else e.httpsAgent=new I(this.certOption);return Promise.resolve(e)}}function oe(e,t,n){if(0===e.length)throw new P(U(O.EmptyParameter,"cert"),R.InvalidParameter);if(0===t.length)throw new P(U(O.EmptyParameter,"key"),R.InvalidParameter);return{cert:e,key:t,passphrase:null==n?void 0:n.passphrase,ca:null==n?void 0:n.ca}}function ae(e,t){if(0===e.length)throw new P(U(O.EmptyParameter,"pfx"),R.InvalidParameter);return{pfx:e,passphrase:null==t?void 0:t.passphrase}}let re="BotSsoExecutionDialog",se="TeamsFxSsoPrompt",ce="CommandRouteDialog";class de extends v{constructor(e,t,n,i,o){super(null!=o?o:re),this.dedupStorageKeys=[],this.commandMapping=new Map,o&&(re=o,se=o+se,ce=o+ce);const a=new Z(n,i,se,t);this.addDialog(a),this.initialDialogId=ce,this.dedupStorage=e,this.dedupStorageKeys=[];const r=new m(ce,[this.commandRouteStep.bind(this)]);this.addDialog(r)}addCommand(e,t){const n=this.getCommandHash(t),i=new m(n,[this.ssoStep.bind(this),this.dedupStep.bind(this),async t=>{const n=t.result.tokenResponse,i=t.context,o=t.result.message;try{if(!n)throw new Error(O.FailedToRetrieveSsoToken);return await e(i,n,o),await t.endDialog()}catch(e){const n=U(O.FailedToProcessSsoHandler,e.message);return M.error(n),await t.endDialog(new P(n,R.FailedToProcessSsoHandler))}}]);this.commandMapping.set(n,t),this.addDialog(i)}getCommandHash(e){const t=(Array.isArray(e)?e:[e]).join();return t.replace(/[^a-zA-Z0-9]/g,"")+n("sha256").update(t).digest("hex").toLowerCase()}async run(e,t){const n=new f(t);n.add(this);const i=await n.createContext(e);this.ensureMsTeamsChannel(i);const o=await i.continueDialog();if(o&&o.status===y.empty)await i.beginDialog(this.id);else if(o&&o.status===y.complete&&o.result instanceof Error)throw o.result}getActivityText(e){let t=e.text;const n=e.removeRecipientMention();return n&&(t=n.toLowerCase().replace(/\n|\r\n/g,"").trim()),t}async commandRouteStep(e){const t=e.context,n=this.getActivityText(t.activity),i=this.getMatchesCommandId(n);if(i)return await e.beginDialog(i);const o=U(O.CannotFindCommand,t.activity.text);throw M.error(o),new P(o,R.CannotFindCommand)}async ssoStep(e){try{const t=e.context,n={text:this.getActivityText(t.activity)};return e.options.commandMessage=n,await e.beginDialog(se)}catch(t){const n=U(O.FailedToRunSsoStep,t.message);return M.error(n),await e.endDialog(new P(n,R.FailedToRunSsoStep))}}async dedupStep(e){const t=e.result;if(!t)return M.error(O.FailedToRetrieveSsoToken),await e.endDialog(new P(O.FailedToRetrieveSsoToken,R.FailedToRunSsoStep));try{return t&&await this.shouldDedup(e.context)?p.EndOfTurn:await e.next({tokenResponse:t,message:e.options.commandMessage})}catch(t){const n=U(O.FailedToRunDedupStep,t.message);return M.error(n),await e.endDialog(new P(n,R.FailedToRunDedupStep))}}async onEndDialog(e){const t=e.activity.conversation.id,n=this.dedupStorageKeys.filter((e=>e.indexOf(t)>0));await this.dedupStorage.delete(n),this.dedupStorageKeys=this.dedupStorageKeys.filter((e=>e.indexOf(t)<0))}async shouldDedup(e){const t={eTag:e.activity.value.id},n=this.getStorageKey(e),i={[n]:t};try{await this.dedupStorage.write(i),this.dedupStorageKeys.push(n)}catch(e){if(e instanceof Error&&e.message.indexOf("eTag conflict"))return!0;throw e}return!1}getStorageKey(e){if(!e||!e.activity||!e.activity.conversation)throw new Error("Invalid context, can not get storage key!");const t=e.activity,n=t.channelId,i=t.conversation.id;if(t.type!==g.Invoke||t.name!==_)throw new Error("TokenExchangeState can only be used with Invokes of signin/tokenExchange.");const o=t.value;if(!o||!o.id)throw new Error("Invalid signin/tokenExchange. Missing activity.value.id.");return`${n}/${i}/${o.id}`}matchPattern(e,t){if(t){if("string"==typeof e){return new RegExp(e,"i").test(t)}if(e instanceof RegExp){const n=t.match(e);return null!=n&&n}}return!1}isPatternMatched(e,t){const n=Array.isArray(e)?e:[e];for(const e of n){return!!this.matchPattern(e,t)}return!1}getMatchesCommandId(e){for(const t of this.commandMapping){const n=t[1];if(this.isPatternMatched(n,e))return t[0]}}ensureMsTeamsChannel(e){if(e.context.activity.channelId!=w.Msteams){const e=U(O.OnlyMSTeamsChannelSupported,"SSO execution dialog");throw M.error(e),new P(e,R.ChannelNotSupported)}}}class le{static attachAdaptiveCard(e,t){const n={$root:t};return{attachments:[i.adaptiveCard(new k.Template(e).expand(n))]}}static attachAdaptiveCardWithoutData(e){return{attachments:[i.adaptiveCard(e)]}}static attachHeroCard(e,t,n,o){return le.attachContent(i.heroCard(e,t,n,o))}static attachSigninCard(e,t,n){return le.attachContent(i.signinCard(e,t,n))}static attachO365ConnectorCard(e){return le.attachContent(i.o365ConnectorCard(e))}static AttachReceiptCard(e){return le.attachContent(i.receiptCard(e))}static attachThumbnailCard(e,t,n,o){return le.attachContent(i.thumbnailCard(e,t,n,o))}static attachContent(e){return{attachments:[e]}}}var ue,he,pe;!function(e){e.AdaptiveCard="application/vnd.microsoft.card.adaptive",e.Message="application/vnd.microsoft.activity.message",e.Error="application/vnd.microsoft.error"}(ue||(ue={}));class ve{static textMessage(e){if(!e)throw new Error("The text message cannot be null or empty");return{status:a.OK,body:{statusCode:a.OK,type:ue.Message,value:e}}}static adaptiveCard(e){if(!e)throw new Error("The adaptive card content cannot be null or undefined");return{status:a.OK,body:{statusCode:a.OK,type:ue.AdaptiveCard,value:e}}}static errorResponse(e,t){return{status:a.OK,body:{statusCode:e,type:ue.Error,value:{code:e.toString(),message:t}}}}static createInvokeResponse(e,t){return{status:e,body:t}}}async function me(e,t,n,i,o){const a=e.activity.value;if(!a.authentication||!a.authentication.token)return M.verbose("No AccessToken in request, return silentAuth for AccessToken"),function(e,t,n){const i=q(n);return{composeExtension:{type:"silentAuth",suggestedActions:{actions:[{type:"openUrl",value:`${t}?scope=${encodeURI(i.join(" "))}&clientId=${e.clientId}&tenantId=${e.tenantId}`,title:"Message Extension OAuth"}]}}}}(t,n,i);try{const e=new z(a.authentication.token,t),n=await e.getToken(i),r=B(a.authentication.token).exp,s={ssoToken:a.authentication.token,ssoTokenExpiration:new Date(1e3*r).toISOString(),token:n.token,expiration:n.expiresOnTimestamp.toString(),connectionName:""};if(o)return await o(s)}catch(o){if(o instanceof P&&o.code===R.UiRequiredError&&"composeExtension/query"===e.activity.name){M.verbose("User not consent yet, return 412 to user consent first.");const t={status:412},n=S.fromObject({value:t,type:g.InvokeResponse});await e.sendActivity(n)}else if(o instanceof P&&o.code===R.UiRequiredError&&"composeExtension/queryLink"===e.activity.name){M.verbose("User not consent yet, return auth card for user login");const o=function(e,t,n){const i=q(n);return{composeExtension:{type:"auth",suggestedActions:{actions:[{type:"openUrl",value:`${t}?scope=${encodeURI(i.join(" "))}&clientId=${e.clientId}&tenantId=${e.tenantId}`,title:"Message Extension OAuth"}]}}}}(t,n,i);return void await e.sendActivity(S.fromObject({value:{status:200,body:o},type:g.InvokeResponse}))}throw o}}async function fe(e,t,n,i,o){if("composeExtension/query"!=e.activity.name)throw M.error(O.OnlySupportInQueryActivity),new P(U(O.OnlySupportInQueryActivity),R.FailedOperation);return await me(e,null!=t?t:{},n,i,o)}async function ye(e,t,n,i,o){if("composeExtension/queryLink"!=e.activity.name)throw M.error(O.OnlySupportInLinkQueryActivity),new P(U(O.OnlySupportInLinkQueryActivity),R.FailedOperation);return await me(e,null!=t?t:{},n,i,o)}class ge{constructor(e){this.actionHandlers=[],this.defaultMessage="Your response was sent to the app",e&&e.length>0&&this.actionHandlers.push(...e)}async onTurn(e,t){var n,a,r;if("adaptiveCard/action"===e.activity.name){const t=e.activity.value.action,s=t.verb;for(const c of this.actionHandlers)if((null===(n=c.triggerVerb)||void 0===n?void 0:n.toLowerCase())===(null==s?void 0:s.toLowerCase())){let n;try{n=await c.handleActionInvoked(e,t.data)}catch(t){const n=ve.errorResponse(V.InternalServerError,t.message);throw await this.sendInvokeResponse(e,n),t}switch(null===(a=n.body)||void 0===a?void 0:a.type){case ue.AdaptiveCard:const t=null===(r=n.body)||void 0===r?void 0:r.value;if(!t){const t="Adaptive card content cannot be found in the response body";throw await this.sendInvokeResponse(e,ve.errorResponse(V.InternalServerError,t)),new Error(t)}t.refresh&&c.adaptiveCardResponse!==Q.NewForAll&&(c.adaptiveCardResponse=Q.ReplaceForAll);const a=o.attachment(i.adaptiveCard(t));c.adaptiveCardResponse===Q.NewForAll?(await this.sendInvokeResponse(e,ve.textMessage(this.defaultMessage)),await e.sendActivity(a)):c.adaptiveCardResponse===Q.ReplaceForAll?(a.id=e.activity.replyToId,await e.updateActivity(a),await this.sendInvokeResponse(e,n)):await this.sendInvokeResponse(e,n);break;case ue.Message:case ue.Error:default:await this.sendInvokeResponse(e,n)}break}}await t()}async sendInvokeResponse(e,t){await e.sendActivity({type:g.InvokeResponse,value:t})}}class we{constructor(e,t){this.middleware=new ge(null==t?void 0:t.actions),this.adapter=e.use(this.middleware)}registerHandler(e){e&&this.middleware.actionHandlers.push(e)}registerHandlers(e){e&&this.middleware.actionHandlers.push(...e)}}class Ce{constructor(e,t,n){if(this.commandHandlers=[],this.ssoCommandHandlers=[],e=null!=e?e:[],t=null!=t?t:[],this.hasSsoCommand=t.length>0,this.ssoActivityHandler=n,this.hasSsoCommand&&!this.ssoActivityHandler)throw M.error(O.SsoActivityHandlerIsNull),new P(O.SsoActivityHandlerIsNull,R.SsoActivityHandlerIsUndefined);this.commandHandlers.push(...e);for(const e of t)this.addSsoCommand(e)}addSsoCommand(e){var t;null===(t=this.ssoActivityHandler)||void 0===t||t.addCommand((async(t,n,i)=>{const o=this.shouldTrigger(e.triggerPatterns,i.text);i.matches=Array.isArray(o)?o:void 0;const a=await e.handleCommandReceived(t,i,n);await this.processResponse(t,a)}),e.triggerPatterns),this.ssoCommandHandlers.push(e),this.hasSsoCommand=!0}async onTurn(e,t){var n,i;if(e.activity.type===g.Message){const t=this.getActivityText(e.activity);let i=!1;for(const n of this.commandHandlers){const o=this.shouldTrigger(n.triggerPatterns,t);if(o){const a={text:t};a.matches=Array.isArray(o)?o:void 0;const r=await n.handleCommandReceived(e,a);await this.processResponse(e,r),i=!0;break}}if(!i)for(const i of this.ssoCommandHandlers){if(this.shouldTrigger(i.triggerPatterns,t)){await(null===(n=this.ssoActivityHandler)||void 0===n?void 0:n.run(e));break}}}else this.hasSsoCommand&&await(null===(i=this.ssoActivityHandler)||void 0===i?void 0:i.run(e));await t()}async processResponse(e,t){if("string"==typeof t)await e.sendActivity(t);else{const n=t;n&&await e.sendActivity(n)}}matchPattern(e,t){if(t){if("string"==typeof e){return new RegExp(e,"i").test(t)}if(e instanceof RegExp){const n=t.match(e);return null!=n&&n}}return!1}shouldTrigger(e,t){const n=Array.isArray(e)?e:[e];for(const e of n){const n=this.matchPattern(e,t);if(n)return n}return!1}getActivityText(e){let t=e.text;const n=e.removeRecipientMention();return n&&(t=n.toLowerCase().replace(/\n|\r\n/g,"").trim()),t}}class Se{constructor(e,t,n,i){this.ssoConfig=i,this.middleware=new Ce(null==t?void 0:t.commands,null==t?void 0:t.ssoCommands,n),this.adapter=e.use(this.middleware)}registerCommand(e){e&&this.middleware.commandHandlers.push(e)}registerCommands(e){e&&this.middleware.commandHandlers.push(...e)}registerSsoCommand(e){this.validateSsoActivityHandler(),this.middleware.addSsoCommand(e)}registerSsoCommands(e){if(e.length>0){this.validateSsoActivityHandler();for(const t of e)this.middleware.addSsoCommand(t)}}validateSsoActivityHandler(){if(!this.middleware.ssoActivityHandler)throw M.error(O.SsoActivityHandlerIsNull),new P(O.SsoActivityHandlerIsNull,R.SsoActivityHandlerIsUndefined)}}function Ae(e){return JSON.parse(JSON.stringify(e))}function Te(e){var t,n;return`_${null===(t=e.conversation)||void 0===t?void 0:t.tenantId}_${null===(n=e.conversation)||void 0===n?void 0:n.id}`}function Ie(e){var t,n,i,o,a;const r=null===(i=null===(n=null===(t=e.activity)||void 0===t?void 0:t.channelData)||void 0===n?void 0:n.team)||void 0===i?void 0:i.id;return r||(void 0===(null===(o=e.activity.conversation)||void 0===o?void 0:o.name)&&(null===(a=e.activity.conversation)||void 0===a?void 0:a.id)?e.activity.conversation.id:void 0)}!function(e){e[e.CurrentBotInstalled=0]="CurrentBotInstalled",e[e.CurrentBotMessaged=1]="CurrentBotMessaged",e[e.CurrentBotUninstalled=2]="CurrentBotUninstalled",e[e.TeamDeleted=3]="TeamDeleted",e[e.TeamRestored=4]="TeamRestored",e[e.Unknown=5]="Unknown"}(he||(he={}));class ke{constructor(e){this.conversationReferenceStore=e.conversationReferenceStore}async onTurn(e,t){switch(this.classifyActivity(e.activity)){case he.CurrentBotInstalled:case he.TeamRestored:{const t=e.activity.getConversationReference();await this.conversationReferenceStore.add(Te(t),t,{overwrite:!0});break}case he.CurrentBotMessaged:await this.tryAddMessagedReference(e);break;case he.CurrentBotUninstalled:case he.TeamDeleted:{const t=e.activity.getConversationReference();await this.conversationReferenceStore.remove(Te(t),t);break}}await t()}classifyActivity(e){var t,n;const i=e.type;if("installationUpdate"===i){const n=null===(t=e.action)||void 0===t?void 0:t.toLowerCase();return"add"===n||"add-upgrade"===n?he.CurrentBotInstalled:he.CurrentBotUninstalled}if("conversationUpdate"===i){const t=null===(n=e.channelData)||void 0===n?void 0:n.eventType;if("teamDeleted"===t)return he.TeamDeleted;if("teamRestored"===t)return he.TeamRestored}else if("message"===i)return he.CurrentBotMessaged;return he.Unknown}async tryAddMessagedReference(e){var t,n,i,o,a,r;const s=e.activity.getConversationReference(),c=null===(t=null==s?void 0:s.conversation)||void 0===t?void 0:t.conversationType;if("personal"===c||"groupChat"===c)await this.conversationReferenceStore.add(Te(s),s,{overwrite:!1});else if("channel"===c){const t=null===(o=null===(i=null===(n=e.activity)||void 0===n?void 0:n.channelData)||void 0===i?void 0:i.team)||void 0===o?void 0:o.id,c=null===(r=null===(a=e.activity.channelData)||void 0===a?void 0:a.channel)||void 0===r?void 0:r.id;if(void 0!==t&&(void 0===c||t===c)){const e=Ae(s);e.conversation.id=t,await this.conversationReferenceStore.add(Te(e),e,{overwrite:!1})}}}}class Ee{constructor(e){var t;this.localFileName=null!==(t=process.env.TEAMSFX_NOTIFICATION_STORE_FILENAME)&&void 0!==t?t:".notification.localstore.json",this.filePath=E.resolve(e,this.localFileName)}async add(e,t,n){if(n.overwrite||!await this.storeFileExists()){if(await this.storeFileExists()){const n=await this.readFromFile();await this.writeToFile(Object.assign(n,{[e]:t}))}else await this.writeToFile({[e]:t});return!0}return!1}async remove(e,t){if(!await this.storeFileExists())return!1;if(await this.storeFileExists()){const t=await this.readFromFile();void 0!==t[e]&&(delete t[e],await this.writeToFile(t))}return!0}async list(e,t){if(!await this.storeFileExists())return{data:[],continuationToken:""};const n=await this.readFromFile();return{data:Object.entries(n).map((e=>e[1])),continuationToken:""}}storeFileExists(){return new Promise((e=>{try{x.access(this.filePath,(t=>{e(!t)}))}catch(t){e(!1)}}))}readFromFile(){return new Promise(((e,t)=>{try{x.readFile(this.filePath,{encoding:"utf-8"},((n,i)=>{n?t(n):e(JSON.parse(i))}))}catch(e){t(e)}}))}async writeToFile(e){return new Promise(((t,n)=>{try{const i=JSON.stringify(e,void 0,2);x.writeFile(this.filePath,i,{encoding:"utf-8"},(e=>{e?n(e):t()}))}catch(e){n(e)}}))}}class xe{constructor(e,t){this.type=G.Channel,this.parent=e,this.info=t}async sendMessage(e,t){const n={};return await this.parent.adapter.continueConversation(this.parent.conversationReference,(async i=>{const o=await this.newConversation(i);await this.parent.adapter.continueConversation(o,(async i=>{try{const t=await i.sendActivity(e);n.id=null==t?void 0:t.id}catch(e){if(!t)throw e;await t(i,e)}}))})),n}async sendAdaptiveCard(e,t){const n={};return await this.parent.adapter.continueConversation(this.parent.conversationReference,(async o=>{const a=await this.newConversation(o);await this.parent.adapter.continueConversation(a,(async o=>{try{const t=await o.sendActivity({attachments:[i.adaptiveCard(e)],type:g.Message});n.id=null==t?void 0:t.id}catch(e){if(!t)throw e;await t(o,e)}}))}),!0),n}newConversation(e){const t=Ae(e.activity.getConversationReference());return t.conversation.id=this.info.id||"",Promise.resolve(t)}}class Re{constructor(e,t){this.type=G.Person,this.parent=e,this.account=t}async sendMessage(e,t){const n={};return await this.parent.adapter.continueConversation(this.parent.conversationReference,(async i=>{const o=await this.newConversation(i);await this.parent.adapter.continueConversation(o,(async i=>{try{const t=await i.sendActivity(e);n.id=null==t?void 0:t.id}catch(e){if(!t)throw e;await t(i,e)}}))})),n}async sendAdaptiveCard(e,t){const n={};return await this.parent.adapter.continueConversation(this.parent.conversationReference,(async o=>{const a=await this.newConversation(o);await this.parent.adapter.continueConversation(a,(async o=>{try{const t=await o.sendActivity({attachments:[i.adaptiveCard(e)],type:g.Message});n.id=null==t?void 0:t.id}catch(e){if(!t)throw e;await t(o,e)}}))}),!0),n}async newConversation(e){var t;const n=Ae(e.activity.getConversationReference()),i=null!==(t=e.turnState.get(this.parent.adapter.ConnectorClientKey))&&void 0!==t?t:this.parent.adapter.connectorClient,o={members:[this.account],isGroup:!1,agent:e.activity.recipient,tenantId:e.activity.conversation.tenantId,activity:void 0,channelData:e.activity.channelData},a=await i.createConversationAsync(o);return n.conversation.id=a.id,n}}class be{constructor(e,t,n){this.adapter=e,this.conversationReference=t,this.type=function(e){var t;const n=null===(t=e.conversation)||void 0===t?void 0:t.conversationType;return"personal"===n?G.Person:"groupChat"===n?G.Group:"channel"===n?G.Channel:void 0}(t),this.botAppId=n}async sendMessage(e,t){const n={};return await this.adapter.continueConversation(this.conversationReference,(async i=>{try{const t=await i.sendActivity(e);n.id=null==t?void 0:t.id}catch(e){if(!t)throw e;await t(i,e)}})),n}async sendAdaptiveCard(e,t){const n={};return await this.adapter.continueConversation(this.conversationReference,(async o=>{try{const t={attachments:[i.adaptiveCard(e)],type:g.Message},a=await o.sendActivity(t);n.id=null==a?void 0:a.id}catch(e){if(!t)throw e;await t(o,e)}}),!0),n}async channels(){const e=[];if(this.type!==G.Channel)return e;let t=[];await this.adapter.continueConversation(this.conversationReference,(async e=>{const n=Ie(e);void 0!==n&&(t=await u.getTeamChannels(e,n))}));for(const n of t)e.push(new xe(this,n));return e}async getPagedMembers(e,t){let n={data:[],continuationToken:""};return await this.adapter.continueConversation(this.conversationReference,(async i=>{var o;i.activity.channelData=null!==(o=i.activity.channelData)&&void 0!==o?o:{},void 0===i.turnState.get("connectorClient")&&i.turnState.set("connectorClient",this.adapter.connectorClient);const a=await u.getPagedMembers(i,e,t);n={data:a.members.map((e=>new Re(this,e))),continuationToken:a.continuationToken}}),!0),n}async getTeamDetails(){if(this.type!==G.Channel)return;let e;return await this.adapter.continueConversation(this.conversationReference,(async t=>{const n=Ie(t);void 0!==n&&(e=await u.getTeamDetails(t,n))})),e}}class Oe{constructor(e,t){var n,i;(null==t?void 0:t.store)?this.conversationReferenceStore=t.store:this.conversationReferenceStore=new Ee(E.resolve("1"===process.env.RUNNING_ON_AZURE&&null!==(n=process.env.TEMP)&&void 0!==n?n:"./")),this.adapter=e.use(new ke({conversationReferenceStore:this.conversationReferenceStore})),this.botAppId=null!==(i=null==t?void 0:t.botAppId)&&void 0!==i?i:process.env.BOT_ID}buildTeamsBotInstallation(e){if(!e)throw new Error("conversationReference is required.");return new be(this.adapter,e,this.botAppId)}async validateInstallation(e){let t=!0;return await this.adapter.continueConversation(e,(async e=>{var n;try{e.activity.channelData=null!==(n=e.activity.channelData)&&void 0!==n?n:{},void 0===e.turnState.get("connectorClient")&&e.turnState.set("connectorClient",this.adapter.connectorClient),await u.getPagedMembers(e,1)}catch(e){"BotNotInConversationRoster"===e.code&&(t=!1)}})),t}async getPagedInstallations(e,t,n=!0){if(void 0===this.conversationReferenceStore||void 0===this.adapter)throw new Error("NotificationBot has not been initialized.");const i=await this.conversationReferenceStore.list(e,t),o=[];for(const e of i.data){let t;n&&(t=await this.validateInstallation(e)),!n||n&&t?o.push(new be(this.adapter,e,this.botAppId)):await this.conversationReferenceStore.remove(Te(e),e)}return{data:o,continuationToken:i.continuationToken}}async findMember(e,t){for(const n of await this.installations())if(this.matchSearchScope(n,t)){const t=[];let i;do{const e=await n.getPagedMembers(void 0,i);i=e.continuationToken,t.push(...e.data)}while(i);for(const n of t)if(await e(n))return n}}async findChannel(e){for(const t of await this.installations())if(t.type===G.Channel){const n=await t.getTeamDetails();for(const i of await t.channels())if(await e(i,n))return i}}async findAllMembers(e,t){const n=[];for(const i of await this.installations())if(this.matchSearchScope(i,t)){const t=[];let o;do{const e=await i.getPagedMembers(void 0,o);o=e.continuationToken,t.push(...e.data)}while(o);for(const i of t)await e(i)&&n.push(i)}return n}async findAllChannels(e){const t=[];for(const n of await this.installations())if(n.type===G.Channel){const i=await n.getTeamDetails();for(const o of await n.channels())await e(o,i)&&t.push(o)}return t}matchSearchScope(e,t){return t=null!=t?t:pe.All,e.type===G.Channel&&!!(t&pe.Channel)||e.type===G.Group&&!!(t&pe.Group)||e.type===G.Person&&!!(t&pe.Person)}async installations(){let e;const t=[];do{const n=await this.getPagedInstallations(void 0,e);e=n.continuationToken,t.push(...n.data)}while(e);return t}}!function(e){e[e.Person=1]="Person",e[e.Group=2]="Group",e[e.Channel=4]="Channel",e[e.All=7]="All"}(pe||(pe={}));class Pe extends h{constructor(e){var t,n,i,o,a,d,l,u,h,p;super();const v=new r,m=null!==(n=null===(t=e.dialog)||void 0===t?void 0:t.userState)&&void 0!==n?n:new s(v),f=null!==(o=null===(i=e.dialog)||void 0===i?void 0:i.conversationState)&&void 0!==o?o:new c(v),y=null!==(d=null===(a=e.dialog)||void 0===a?void 0:a.dedupStorage)&&void 0!==d?d:v,g=e.aad,{scopes:w}=g,C=
2
2
  /*! *****************************************************************************
3
3
  Copyright (c) Microsoft Corporation.
4
4
 
@@ -13,5 +13,5 @@ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
13
13
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
14
14
  PERFORMANCE OF THIS SOFTWARE.
15
15
  ***************************************************************************** */
16
- function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(i=Object.getOwnPropertySymbols(e);o<i.length;o++)t.indexOf(i[o])<0&&Object.prototype.propertyIsEnumerable.call(e,i[o])&&(n[i[o]]=e[i[o]])}return n}(g,["scopes"]),S={scopes:w,timeout:null===(u=null===(l=e.dialog)||void 0===l?void 0:l.ssoPromptConfig)||void 0===u?void 0:u.timeout,endOnInvalidMessage:null===(p=null===(h=e.dialog)||void 0===h?void 0:h.ssoPromptConfig)||void 0===p?void 0:p.endOnInvalidMessage};this.ssoExecutionDialog=new le(y,S,C,C.initiateLoginEndpoint),this.conversationState=f,this.dialogState=f.createProperty("DialogState"),this.userState=m,this.onMessage((async(e,t)=>{await this.ssoExecutionDialog.run(e,this.dialogState),await t()}))}addCommand(e,t){this.ssoExecutionDialog.addCommand(e,t)}async run(e){try{await super.run(e)}finally{await this.conversationState.saveChanges(e,!1),await this.userState.saveChanges(e,!1)}}async handleTeamsSigninVerifyState(e,t){await this.ssoExecutionDialog.run(e,this.dialogState)}async handleTeamsSigninTokenExchange(e,t){await this.ssoExecutionDialog.run(e,this.dialogState)}}var De=Object.freeze({__proto__:null,BotSsoExecutionDialog:le,CardActionBot:Ce,Channel:Re,CommandBot:Ae,ConversationBot:class{constructor(e){var t,n,i,o;let a;e.adapter?this.adapter=e.adapter:this.adapter=this.createDefaultAdapter(e.adapterConfig),(null==e?void 0:e.ssoConfig)&&(a=(null===(t=e.ssoConfig.dialog)||void 0===t?void 0:t.CustomBotSsoExecutionActivityHandler)?new e.ssoConfig.dialog.CustomBotSsoExecutionActivityHandler(e.ssoConfig):new Fe(e.ssoConfig)),(null===(n=e.command)||void 0===n?void 0:n.enabled)&&(this.command=new Ae(this.adapter,e.command,a,e.ssoConfig)),(null===(i=e.notification)||void 0===i?void 0:i.enabled)&&(this.notification=new Pe(this.adapter,e.notification)),(null===(o=e.cardAction)||void 0===o?void 0:o.enabled)&&(this.cardAction=new Ce(this.adapter,e.cardAction))}createDefaultAdapter(e){const t=null!=e?e:d(),n=new l(t);return n.onTurnError=async(e,t)=>{console.error("[onTurnError] unhandled error",t),"message"===e.activity.type&&(await e.sendTraceActivity("OnTurnError Trace",t instanceof Error?t.message:t,"https://www.botframework.com/schemas/error","TurnError"),await e.sendActivity(`The bot encountered unhandled error: ${t.message}`),await e.sendActivity("To continue to run this bot, please fix the bot source code."))},n}async requestHandler(e,t,n){void 0===n&&(n=async()=>{}),await this.adapter.process(e,t,n)}},Member:be,NotificationBot:Pe,get SearchScope(){return ve},TeamsBotInstallation:Oe,sendAdaptiveCard:function(e,t,n){return e.sendAdaptiveCard(t,n)},sendMessage:function(e,t,n){return e.sendMessage(t,n)}});export{ne as AdaptiveCardResponse,De as AgentBuilderCloudAdapter,ee as ApiKeyLocation,Y as ApiKeyProvider,K as AppCredential,X as BasicAuthProvider,Z as BearerTokenAuthProvider,le as BotSsoExecutionDialog,oe as CertificateAuthProvider,O as ErrorCode,D as ErrorWithCode,ie as InvokeResponseErrorCode,me as InvokeResponseFactory,P as LogLevel,ue as MessageBuilder,te as NotificationTargetType,G as OnBehalfOfUserCredential,W as TeamsBotSsoPrompt,Q as TeamsUserCredential,J as createApiClient,ae as createPemCertOption,re as createPfxCertOption,N as getLogLevel,ge as handleMessageExtensionLinkQueryWithSSO,ye as handleMessageExtensionQueryWithSSO,U as setLogFunction,M as setLogLevel,B as setLogger};
16
+ function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(i=Object.getOwnPropertySymbols(e);o<i.length;o++)t.indexOf(i[o])<0&&Object.prototype.propertyIsEnumerable.call(e,i[o])&&(n[i[o]]=e[i[o]])}return n}(g,["scopes"]),S={scopes:w,timeout:null===(u=null===(l=e.dialog)||void 0===l?void 0:l.ssoPromptConfig)||void 0===u?void 0:u.timeout,endOnInvalidMessage:null===(p=null===(h=e.dialog)||void 0===h?void 0:h.ssoPromptConfig)||void 0===p?void 0:p.endOnInvalidMessage};this.ssoExecutionDialog=new de(y,S,C,C.initiateLoginEndpoint),this.conversationState=f,this.dialogState=f.createProperty("DialogState"),this.userState=m,this.onMessage((async(e,t)=>{await this.ssoExecutionDialog.run(e,this.dialogState),await t()}))}addCommand(e,t){this.ssoExecutionDialog.addCommand(e,t)}async run(e){try{await super.run(e)}finally{await this.conversationState.saveChanges(e,!1),await this.userState.saveChanges(e,!1)}}async handleTeamsSigninVerifyState(e,t){await this.ssoExecutionDialog.run(e,this.dialogState)}async handleTeamsSigninTokenExchange(e,t){await this.ssoExecutionDialog.run(e,this.dialogState)}}var Fe=Object.freeze({__proto__:null,BotSsoExecutionDialog:de,CardActionBot:we,Channel:xe,CommandBot:Se,ConversationBot:class{constructor(e){var t,n,i,o;let a;e.adapter?this.adapter=e.adapter:this.adapter=this.createDefaultAdapter(e.adapterConfig),(null==e?void 0:e.ssoConfig)&&(a=(null===(t=e.ssoConfig.dialog)||void 0===t?void 0:t.CustomBotSsoExecutionActivityHandler)?new e.ssoConfig.dialog.CustomBotSsoExecutionActivityHandler(e.ssoConfig):new Pe(e.ssoConfig)),(null===(n=e.command)||void 0===n?void 0:n.enabled)&&(this.command=new Se(this.adapter,e.command,a,e.ssoConfig)),(null===(i=e.notification)||void 0===i?void 0:i.enabled)&&(this.notification=new Oe(this.adapter,e.notification)),(null===(o=e.cardAction)||void 0===o?void 0:o.enabled)&&(this.cardAction=new we(this.adapter,e.cardAction))}createDefaultAdapter(e){const t=null!=e?e:d(),n=new l(t);return n.onTurnError=async(e,t)=>{console.error("[onTurnError] unhandled error",t),"message"===e.activity.type&&(await e.sendTraceActivity("OnTurnError Trace",t instanceof Error?t.message:t,"https://www.botframework.com/schemas/error","TurnError"),await e.sendActivity(`The bot encountered unhandled error: ${t.message}`),await e.sendActivity("To continue to run this bot, please fix the bot source code."))},n}async requestHandler(e,t,n){void 0===n&&(n=async()=>{}),await this.adapter.process(e,t,n)}},Member:Re,NotificationBot:Oe,get SearchScope(){return pe},TeamsBotInstallation:be,sendAdaptiveCard:function(e,t,n){return e.sendAdaptiveCard(t,n)},sendMessage:function(e,t,n){return e.sendMessage(t,n)}});export{Q as AdaptiveCardResponse,Fe as AgentBuilderCloudAdapter,ne as ApiKeyLocation,te as ApiKeyProvider,$ as AppCredential,ee as BasicAuthProvider,Y as BearerTokenAuthProvider,de as BotSsoExecutionDialog,ie as CertificateAuthProvider,R as ErrorCode,P as ErrorWithCode,V as InvokeResponseErrorCode,ve as InvokeResponseFactory,b as LogLevel,le as MessageBuilder,G as NotificationTargetType,z as OnBehalfOfUserCredential,Z as TeamsBotSsoPrompt,K as TeamsUserCredential,X as createApiClient,oe as createPemCertOption,ae as createPfxCertOption,D as getLogLevel,ye as handleMessageExtensionLinkQueryWithSSO,fe as handleMessageExtensionQueryWithSSO,H as setLogFunction,F as setLogLevel,N as setLogger};
17
17
  //# sourceMappingURL=index.esm2017.mjs.map