Full Code of karigari/vscode-chat for AI

master ad72e38cb421 cached
111 files
327.5 KB
78.4k tokens
393 symbols
1 requests
Download .txt
Showing preview only (354K chars total). Download the full file or copy to clipboard to get everything.
Repository: karigari/vscode-chat
Branch: master
Commit: ad72e38cb421
Files: 111
Total size: 327.5 KB

Directory structure:
gitextract_mypbxujs/

├── .gitattributes
├── .github/
│   └── main.workflow
├── .gitignore
├── .prettierrc
├── .travis.yml
├── .vscode/
│   ├── extensions.json
│   ├── launch.json
│   ├── settings.json
│   └── tasks.json
├── .vscodeignore
├── CHANGELOG.md
├── LICENSE
├── README.md
├── VISION.md
├── azure-pipelines.yml
├── docs/
│   ├── CONFIG.md
│   ├── CONTRIBUTING.md
│   ├── DISCORD.md
│   ├── PROVIDERS.md
│   └── SLACK.md
├── oauth-service/
│   ├── README.md
│   ├── handler.ts
│   ├── html/
│   │   ├── error.template.html
│   │   ├── home.template.html
│   │   └── success.template.html
│   ├── html.d.ts
│   ├── package.json
│   ├── serverless.yml
│   ├── source-map-install.js
│   ├── tsconfig.json
│   ├── utils.ts
│   └── webpack.config.js
├── oauth-service-2/
│   ├── .gcloudignore
│   ├── README.md
│   ├── htmls.js
│   ├── index.js
│   ├── package.json
│   └── utils.js
├── package.json
├── readme/
│   ├── logo.sketch
│   └── screenshots.sketch
├── src/
│   ├── bots/
│   │   └── travis.ts
│   ├── config/
│   │   ├── https-proxy-agent.d.ts
│   │   ├── index.ts
│   │   └── keychain.ts
│   ├── constants.ts
│   ├── controller/
│   │   ├── commands.ts
│   │   ├── emoji-js.d.ts
│   │   ├── index.ts
│   │   ├── markdown-it-slack.d.ts
│   │   └── markdowner.ts
│   ├── discord/
│   │   └── index.ts
│   ├── extension.ts
│   ├── issues.ts
│   ├── logger.ts
│   ├── manager/
│   │   ├── chatManager.ts
│   │   ├── index.ts
│   │   ├── treeView.ts
│   │   └── views.ts
│   ├── onboarding.ts
│   ├── slack/
│   │   ├── client.ts
│   │   ├── common.ts
│   │   ├── index.ts
│   │   └── messenger.ts
│   ├── status/
│   │   └── index.ts
│   ├── store.ts
│   ├── strings.ts
│   ├── telemetry.ts
│   ├── test/
│   │   ├── extension.test.ts
│   │   ├── index.ts
│   │   ├── manager.test.ts
│   │   └── utils.test.ts
│   ├── tree/
│   │   ├── base.ts
│   │   ├── index.ts
│   │   └── treeItem.ts
│   ├── types.ts
│   ├── uriHandler.ts
│   ├── utils/
│   │   ├── index.ts
│   │   └── keychain.ts
│   ├── vslsSpaces/
│   │   ├── gravatar-api.d.ts
│   │   └── index.ts
│   └── webview/
│       └── index.ts
├── tsconfig.json
├── tslint.json
├── webpack.config.js
└── webview/
    ├── .gitignore
    ├── README.md
    ├── babel.config.js
    ├── package.json
    ├── src/
    │   ├── App.vue
    │   ├── components/
    │   │   ├── DateSeparator.vue
    │   │   ├── FormSection.vue
    │   │   ├── MarkdownElement.vue
    │   │   ├── MessageAuthor.vue
    │   │   ├── MessageContent.vue
    │   │   ├── MessageGroup.vue
    │   │   ├── MessageInput.vue
    │   │   ├── MessageItem.vue
    │   │   ├── MessageReaction.vue
    │   │   ├── MessageReactions.vue
    │   │   ├── MessageReplies.vue
    │   │   ├── MessageRepliesImages.vue
    │   │   ├── MessageReplyItem.vue
    │   │   ├── MessageTitle.vue
    │   │   ├── MessagesDateGroup.vue
    │   │   ├── MessagesSection.vue
    │   │   ├── StatusText.vue
    │   │   └── UserInfo.vue
    │   ├── main.js
    │   └── utils.js
    └── vue.config.js

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitattributes
================================================
# Set default behavior to automatically normalize line endings.
* text=auto



================================================
FILE: .github/main.workflow
================================================
workflow "LSIF workflow" {
  resolves = ["arjun27/lsif-action@master"]
  on = "push"
}

action "arjun27/lsif-action@master" {
  uses = "arjun27/lsif-action@master"
}

workflow "Testing fork builds" {
  on = "pull_request"
  resolves = ["post gif on fail"]
}

action "post gif on fail" {
  uses = "arjun27/shaking-finger-action@patch-1"
  secrets = ["GITHUB_TOKEN"]
}


================================================
FILE: .gitignore
================================================
out
node_modules
jspm_packages
.vscode-test/
.vs
*.vsix
static
tokens
.serverless
.webpack
env.yml


================================================
FILE: .prettierrc
================================================
{
    "tabWidth": 4,
    "printWidth": 120
}

================================================
FILE: .travis.yml
================================================
sudo: false

language: node_js

node_js:
  - "10"
  - "9"

before_install:
  - if [ $TRAVIS_OS_NAME == "linux" ]; then
      export CXX="g++-4.9" CC="gcc-4.9" DISPLAY=:99.0;
      sh -e /etc/init.d/xvfb start;
      sleep 3;
    fi

install:
  - yarn
  - yarn run vscode:prepublish

script:
  - yarn test

notifications:
  slack: karigarihq:wyMAff0ihz5w5H2UKtrU2etP


================================================
FILE: .vscode/extensions.json
================================================
{
	// See http://go.microsoft.com/fwlink/?LinkId=827846
	// for the documentation about the extensions.json format
	"recommendations": [
		"eg2.tslint"
	]
}

================================================
FILE: .vscode/launch.json
================================================
// A launch configuration that compiles the extension and then opens it inside a new window
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Extension",
      "type": "extensionHost",
      "request": "launch",
      "runtimeExecutable": "${execPath}",
      "args": ["--extensionDevelopmentPath=${workspaceFolder}"],
      "outFiles": ["${workspaceFolder}/out/**/*.js"],
      "preLaunchTask": "watch",
      "env": {
        "IS_DEBUG": "true"
      }
    },
    {
      "name": "Extension Tests",
      "type": "extensionHost",
      "request": "launch",
      "runtimeExecutable": "${execPath}",
      "args": [
        "--extensionDevelopmentPath=${workspaceFolder}",
        "--extensionTestsPath=${workspaceFolder}/out/test"
      ],
      "outFiles": ["${workspaceFolder}/out/test/**/*.js"],
      "preLaunchTask": "watch",
      "env": {
        "IS_DEBUG": "true"
      }
    }
  ]
}


================================================
FILE: .vscode/settings.json
================================================
// Place your settings in this file to overwrite default and user settings.
{
    "files.exclude": {
        "out": false // set this to true to hide the "out" folder with the compiled JS files
    },
    "search.exclude": {
        "out": true // set this to false to include "out" folder in search results
    },
    // Turn off tsc task auto detection since we have the necessary tasks as npm scripts
    "typescript.tsc.autoDetect": "off"
}

================================================
FILE: .vscode/tasks.json
================================================
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
{
  "version": "2.0.0",
  "tasks": [
    {
      "type": "shell",
      "label": "watch",
      "command": "npm run watch",
      "problemMatcher": "$tsc-watch",
      "isBackground": true,
      "presentation": {
        "reveal": "never"
      },
      "group": {
        "kind": "build",
        "isDefault": true
      }
    }
  ]
}


================================================
FILE: .vscodeignore
================================================
.vs/**
.vscode/**
.vscode-test/**
out/test/**
out/**/*.map
src/**
.gitignore
tsconfig.json
tslint.json
tokens
oauth-service/**
oauth-service-2/**
node_modules/**
readme/**
webview/**


================================================
FILE: CHANGELOG.md
================================================
# Changelog

All notable changes to the Live Share Chat extension will be documented in this file. This follows the [Keep a Changelog](http://keepachangelog.com/) format.

## [0.35.0] - 2020-06-13

Fixed

-   Slack OAuth has been fixed. Since legacy tokens are deprecated, use the "Sign in with Slack" command to use Slack.

## [0.34.0] - 2020-06-03

-   This version removes the VS Live Share integration bits, which have been now added to the main VS Live Share extension.

## [0.33.0] - 2020-03-23		

### Fixed

-   Recovery build: Bringing back Live Share integration for now. Will revert the recovery build once the new version of Live Share is released.

## [0.32.0] - 2020-03-22

### Removed

-   The integration with VS Live Share has now moved into the core VS Live Share extension! Thanks to everyone who tried it out, and helped make it a core experience for using Live Share.

## [0.31.0] - 2019-12-19

### Fixed

-   Fixes to initialization for Live Share Spaces increase reliability of the experience.

## [0.30.0] - 2019-12-19

### Fixed

-   Fixes to initialization for Live Share Chat that increase reliability of the experience.

## [0.29.0] - 2019-11-06

### Added

-   You can type `/invite` in a Live Share DM chat to invite your contacts into a Live Share collaboration session.

## [0.28.0] - 2019-10-30

### Added

-   Updated readme to reflect recent improvements and changes.

## [0.27.1] - 2019-10-25

### Fixed

-   Fixed overflow styling for at-mentions suggestion list.

## [0.27.0] - 2019-10-25

### Added

-   Support for at-mentions: type `@` to get a list of suggestions to tag. Tagging a user does not notify them in this release—that's coming up soon!

## [0.25.0] - 2019-10-18

### Added

-   Support for a `/clear` command that clears the message history in the current chat window.

## [0.24.0] - 2019-10-17

### Added

-   Live Share Chat now supports typing events!

## [0.23.0] - 2019-10-17

### Added

-   Live Share Chat now supports Direct Messages! You can DM your Live Share contacts—even outside Live Share sessions!

## [0.22.1] - 2019-09-15

### Fixed

-   Fixed presence provider validation.

## [0.22.0] - 2019-09-14

### Added

-   Renamed Live Share Communities provider to Live Share Spaces.

## [0.21.1] - 2019-09-04

### Fixed

-   Fixed date to string conversion for message groups.

## [0.21.0] - 2019-08-19

### Fixed

-   Add Live Share as an extension dependency to fix timing issues during activation

## [0.20.2] - 2019-08-14

### Added

-   Live Share Communities: updated implementation for info messages

## [0.20.0] - 2019-08-13

### Added

-   Live Share Communities: added support for info messages

## [0.19.0] - 2019-08-12

### Added

-   Live Share Communities: added support to clear messages

## [0.18.0] - 2019-08-11

### Added

-   Live Share: alert the guest if host does not have the extension installed.

### Fixed

-   Fixed a case where Live Share Chat was not initialized.

## [0.17.1] - 2019-08-08

### Added

-   Render links correctly in Live Share and Live Share Communities chat.

## [0.17.0] - 2019-08-07

### Added

-   Renamed the extension to Live Share Chat.

## [0.16.3] - 2019-08-07

### Fixed

-   [Live Share Communities](https://github.com/vsls-contrib/communities) integration: Fix cases where current user is returned as undefined.
-   [Live Share Communities](https://github.com/vsls-contrib/communities) integration: Fix a bug where new members were not recognised with an avatar and name.

## [0.16.2] - 2019-08-04

### Fixed

-   [Live Share Communities](https://github.com/vsls-contrib/communities) integration: Fix presence provider and timing issues.

## [0.16.1] - 2019-08-04

### Added

-   [Live Share Communities](https://github.com/vsls-contrib/communities) integration: Auto-launch community chat when a community is joined.

## [0.16.0] - 2019-08-02

### Added

-   Adds integration with [Live Share Communities](https://github.com/vsls-contrib/communities).

## [0.15.1] - 2019-05-12

### Fixed

-   Fixes unwanted notification for Slack/Discord login when installed alongside VS Live Share.

## [0.15.0] - 2019-05-01

### Removed

-   Removed onboarding tree view that would show Slack icon when no chat backend was configured.

## [0.14.0] - 2019-04-28

### Added

-   Faster installation and startup times with Webpack bundling.
-   Updated setup instructions for Discord to call out potential ToS violation.

## [0.13.0] - 2019-04-09

### Fixed

-   Fixes an issue where Live Share Chat would not work for guests on the collaboration session.

## [0.12.0] - 2019-02-24

### Added

-   New configuration option to disable auto-launching the Live Share Chat window on a new Live Share session: `"chat.autoLaunchLiveShareChat": false`.

## [0.11.0] - 2019-02-03

### Added

-   The VS Live Share chat window now shows up automatically for new VS Live Share sessions.

## [0.10.0] - 2019-01-21

### Added

-   Added support for multiple workspaces in Slack. Run the `Sign in with Slack` command to add new workspaces; Use the tree view to change between Slack workspaces.

### Fixed

-   Render attachments in Discord messages.
-   Usability improvements in selecting which Slack channels should be shown.

## [0.9.2] - 2019-01-04

### Fixed

-   "Account is required" errors while accessing the system keychain.

## [0.9.1] - 2018-12-31

### Fixed

-   CPU load: Removed redundant extension activation events that were causing high CPU load.

## [0.9.0] - 2018-12-16

### Added

-   Chat over VS Live Share now works alongside Slack and Discord: You can now chat with your collaboration session peers through VS Live Share, even if you are logged in on other chat providers.
-   Start chat over VS Live Share from the explorer view.

## [0.8.2] - 2018-11-20

### Fixed

-   VS Live Share integration: Updated label for chat tree item.

## [0.8.1] - 2018-11-20

### Fixed

-   Inviting online users to a Live Share session creates an IM channel with the user, if not already available.

## [0.8.0] - 2018-11-18

### Added

-   Now you can update your presence status: go invisible on chat, or turn on do-not-disturb mode. Run the `Chat: Update your presence status` command (supports Slack and Discord).
-   VS Live Share integrations:
    -   Show presence statuses for VS Live Share suggested contacts (for Slack and Discord)
    -   Update your presence status from inside VS Live Share (for Slack and Discord)
    -   Open VS Live Share chat from the VS Live Share explorer views

## [0.7.4] - 2018-11-05

### Fixed

-   Fixed bad instantiation for users and channels state causing VS Live Share chat to not work.

## [0.7.3] - 2018-10-16

### Fixed

-   Fixed channel loading for Slack workspaces that cross the user limit.

## [0.7.2] - 2018-10-15

### Fixed

-   Fixed onboarding notification for Live Share users.

## [0.7.1] - 2018-10-15

### Added

-   Chat over VS Live Share RPC is the default backend for users that have the Live Share extension. Users can optionally upgrade to Slack or Discord.
-   New status bar item to open the chat window during a VS Live Share session.
-   Unread message notification and user joined/left info messages for Live Share chat.

### Fixed

-   Slack messages are sent over websocket, to not count towards http rate limits.
-   Limit Slack channels to relevant channels only, by using the Slack conversations API.

## [0.7.0] - 2018-10-11

### Added

-   Chat with VS Live Share session participants, without relying on a chat backend like Slack/Discord. To use this, start a Live Share session and run the `Chat with VS Live Share participants` command.

## [0.6.3] - 2018-10-09

### Added

-   Added token validation for manual entry for Slack and Discord tokens.
-   Keychain access operations can now be retried in case access is denied.
-   Added workspace name to the status item notification.

## [0.6.2] - 2018-09-28

### Fixed

-   Handle deactivated Slack users, and not show their direct messages and groups (thanks [Tristan Partin](https://github.com/tristan957)).
-   Private channels are now shown under the Channels view, and not Groups.

## [0.6.1] - 2018-09-22

### Fixed

-   Fixed migration condition for pre-0.6.x installations (thanks [ACharLuk](https://github.com/acharluk)).

## [0.6.0] - 2018-09-21

### Added

-   Added support for Discord as a chat provider, in addition to Slack.
-   [Breaking] Commands are now namespaced as "Chat: ...", instead of "Slack: ...".
-   Updates to extension metadata and readme: the extension is now called Team Chat.

## [0.5.11] - 2018-09-18

### Added

-   Added support for replying to thread messages.

### Fixed

-   Fixed rendering of duplicate thread replies.

## [0.5.10] - 2018-09-17

### Added

-   Added new configuration `chat.rejectTlsUnauthorized` for self-signed certificate users (thanks [Seth Bromberger](https://github.com/sbromberger)).
-   Load vue.js assets locally, removing dependency on the jsdelivr CDN.
-   Upgraded Slack dependency to keep up with the network library improvements upstream.

## [0.5.9] - 2018-09-04

### Added

-   Support for muted channels: new messages in muted channels do not update the unread count.
-   Added support to expand thread messages to render replies, with text and file attachments.
-   Consistency between Slack clients for unread counts: marking messages as read from other Slack clients will update the unread count.
-   Unread messages are now highlighted in the webview.
-   Added documentation for [product roadmap](VISION.md) and [adding chat providers](docs/PROVIDERS.md).

### Fixed

-   The unread count does not include alerts for users joining/leaving channels anymore.

## [0.5.8] - 2018-08-31

### Added

-   Added support for the system keychain to store authentication tokens.
-   Added a new command to sign out from Slack.

### Fixed

-   Fix handling of composition start/end events while composing messages (thanks [Yukai Huang](https://github.com/Yukaii)).
-   Opening Slack or changing channel without authentication now prompts users to authenticate.

## [0.5.7] - 2018-08-29

### Added

-   Added support for "Sign in with Slack" from the activity bar.

### Fixed

-   New line characters in messages are rendered correctly.
-   Date separators show the correct month string.
-   Fixed event source property for webview telemetry.

## [0.5.6] - 2018-08-23

### Added

-   Slack webview font size now matches the font size of your editor.
-   Introductory support for message threads: historical messages show the number of thread replies. Future releases will build on this to add full thread replies support.
-   Added anonymized telemetry data collection; this respects the telemetry setting in your editor and you can opt-out by setting `telemetry.enableTelemetry` to false.

### Fixed

-   Updated user display names to be consistent with Slack clients.

## [0.5.5] - 2018-08-20

### Added

-   Added a fallback for "Sign in with Slack" for situations where the system-level URI scheme handler fails.

## [0.5.4] - 2018-08-18

### Added

-   Added "Sign in with Slack" for an easier onboarding experience

## [0.5.3] - 2018-08-18

### Fixed

-   Fixed issues with duplicated state when configuration gets changed in the editor.
-   Fixed unread message notifications for messages with files.

## [0.5.2] - 2018-08-18

### Fixed

-   Fixed date separators computation for local time zones
-   Fixed a race condition where loading channel message history would assign messages to an incorrect channel.

## [0.5.1] - 2018-08-16

### Fixed

-   Fixed extension activation for the VS Live Share activity bar.

## [0.5.0] - 2018-08-16

### Added

-   Sidebar view to show channels, private groups and direct messages.
-   Support to show user presence (online/offline) in the sidebar view.
-   Better integration with VS Live Share: one-click action to invite users or channels to your collaboration session.
-   Minor improvements to extension setup for first-time users.

### Fixed

-   Fixed a case where the unread count would get updated incorrectly.

## [0.4.10] - 2018-08-14

### Added

-   Slack username tags in messages are not cryptic anymore.
-   Better keyboard-only support: pressing tab will focus the input text box, ignoring other selectable HTML elements in the webview.
-   Added date separators on the messages UI

### Fixed

-   Fixed real-time UI updates for bot messages.
-   Fixed select-all behaviour through the cmd+A keybinding (needs VS Code 1.26+).

## [0.4.9] - 2018-08-13

### Fixed

-   Fixed issue where new messages were not getting updated on the UI.

## [0.4.8] - 2018-08-09

### Added

-   Added support to render message reactions, and live update UI as reactions are added or removed
-   The unread count now also reflects messages that were received before the extension gets activated, by calling the relevant Slack API.

### Fixed

-   Messages with files were not rendered correctly since the last Slack update. This has been fixed now.

## [0.4.7] - 2018-08-08

### Added

-   Added a status bar item to show the number of new/unread messages. For now, this is available only after the chat panel has been opened once.

## [0.4.6] - 2018-08-08

### Added

-   Added support for marking messages as read
-   Improved how multi-party DM group name are shown in the UI

## [0.4.5] - 2018-07-21

### Added

-   Added support for network connections via proxies. To setup, add the `chat.proxyUrl` configuration.

## [0.4.4] - 2018-07-17

### Fixed

-   Fixed demo gif on the Visual Studio Marketplace

## [0.4.3] - 2018-07-17

### Added

-   Open Travis CI logs inside the editor, with the new extensible Providers support. New providers can be create for other Slack bots and integrations.
-   New demo gifs and examples in the README.

### Fixed

-   Fixed an issue where messages from a previously opened Slack channel would show up in the current view.

## [0.4.2] - 2018-07-15

### Fixed

-   Fixed the change channel quick-pick prompt for workspaces that invite guest users.

## [0.4.1] - 2018-07-06

### Added

-   Add a "reload channels" option to the channel switcher which refreshes the user/channels list from Slack API.

## [0.4.0] - 2018-07-06

### Added

-   Adds "reverse initiation" for VS Live Share: a user can ask another user to host a Live Share session by sending the `/live request` command. The recipient can choose to accept the request, which would kickstart the shared session.

## [0.3.4] - 2018-07-04

### Fixed

-   Fixes a bug that showed new messages sent via the extension as blank

## [0.3.3] - 2018-07-03

### Added

-   Support for rendering file attachments, code snippets, multi-line messages
-   Support for rendering Slack app messages, with author, title, coloured border, and footer
-   Support for rendering message edits and deletions

### Fixed

-   Fixed click behaviour for links inside messages


================================================
FILE: LICENSE
================================================
                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<https://www.gnu.org/philosophy/why-not-lgpl.html>.

================================================
FILE: README.md
================================================
<h1 align="center">Chat for VS Code</h1>

<h3 align="center">Chat with your Slack and Discord teams from within VS Code</h3>

<p align="center"><img src="https://raw.githubusercontent.com/karigari/vscode-chat/master/readme/Live Share Chat.gif" alt="Screenshot" width="800" /></p>

<p align="center">
    <a href="https://marketplace.visualstudio.com/items?itemName=karigari.chat"><img alt="Visual Studio Marketplace Downloads" src="https://img.shields.io/visual-studio-marketplace/d/karigari.chat"></a>
    <a href="https://marketplace.visualstudio.com/items?itemName=karigari.chat"><img alt="Visual Studio Marketplace Rating" src="https://img.shields.io/visual-studio-marketplace/r/karigari.chat"></a>
    <a href="https://aka.ms/vsls"><img src="https://aka.ms/vsls-badge" alt="Live Share enabled" /></a>
</p>

> **0.34.0**: With this release, the integration with VS Live Share has now moved into the core VS Live Share extension! Thanks to everyone who tried it out, and helped make it a core experience for using Live Share.
> 
> The extension now only supports Slack, Discord and Live Share Spaces as chat providers.

# Features

- **Quiet notifications**: Chat apps can be painfully distracting. This extension emphasizes on making chat useful, contextual, and without distracting notifications.
- **Rich formatting**: Share markdown code snippets, and add emojis to your chat messages.
- **Native look-and-feel**: Use chat in your preferred theme and grid editor layout.

<p align="center">
    <img src="https://raw.githubusercontent.com/karigari/vscode-chat/master/readme/feature-1-magnifier.png" alt="Quiet notifications" width="290" />
    <img src="https://raw.githubusercontent.com/karigari/vscode-chat/master/readme/feature-2.png" alt="Rich formatting" width="290" />
    <img src="https://raw.githubusercontent.com/karigari/vscode-chat/master/readme/feature-3.png" alt="Theme and grid layout" width="290" />
</p>

# Get started with chat

## Slack

To configure your Slack workspace, run the **Sign In with Slack** command in VS Code. Are you a Slack workspace admin? [Approve this app](https://slack.com/apps/ACB4LQKN1-slack-chat-for-vs-code) for your team.

Start a new VS Live Share session within a Slack channel: Use the slash commands `/live share` and `/live end` to start and end a session.

## Discord

Discord support is experimental. Please see [this doc](docs/DISCORD.md) to set it up.

## Live Share Spaces

To explore richer ways to connect and collaborate with developers across your teams, classrooms and communities, check out [Live Share Spaces](https://marketplace.visualstudio.com/items?itemName=vsls-contrib.spaces).

# Support

- **Configuration settings**: To use behind a network proxy and other settings, see [CONFIGURATION](docs/CONFIG.md).
- **Raise an issue**: Feel free to [report an issue](https://github.com/karigari/vscode-chat/issues), or find [me on Twitter](https://twitter.com/arjunattam) for any suggestions or support.

# Developer docs

- **Get started with contribution**: See [CONTRIBUTING](docs/CONTRIBUTING.md) to understand repo structure, building and testing.
- **New chat integrations**: The implementation can be extended to support any chat provider, see [PROVIDERS](docs/PROVIDERS.md).
- **Vision**: Read the [VISION](VISION.md) doc to understand the motivation behind this extension and the roadmap ahead.


================================================
FILE: VISION.md
================================================
# Vision

This doc outlines our vision and product roadmap. The goal is to crystallize the driving ideas: for our community of users and contributors. On a tactical level, this will also help us prioritize feature requests.

Suggestions to update this document are very welcome. Feel free to raise an issue or a pull request! My DMs are also open at [@arjunattam](http://twitter.com/arjunattam).

## The goal

Editors have been historically built to maximize the productivity of one developer. Developers working in teams use version control tools and other services, in addition to their editor: services for project management, continuous integration, and crash reporting.

Personified as bots on Slack, these services have evolved to become our peers in shipping quality code: our bots and our teammates now work in tandem. But there is a gap: this collaboration happens one step away from our code, and that leads to context switches, and consequently knowledge falling through the cracks.

This extension is an experiment to see how the editor can evolve to become the center of collaboration for engineering teams. Perhaps like an IDE for our teams, to maximize team productivity.

## Use-cases

I think of collaboration on an axis of real-time: on one end, there are synchronous use-cases (like pair programming), and then there are asynchronous ones on the other (reviewing pull requests). With this extension, we want to target **the synchronous half** of that axis.

This implies not focusing on teams that collaborate only asynchronously, such as open source projects with longer development cycles.

### Sync collaboration

Chat is a natural fit for synchronous collaboration, and therefore these use-cases will be a focus. Integration with the excellent [VS Live Share extension](https://aka.ms/vsls) is and will continue to be a focus area.

### Pseudo-sync collaboration

Engineering teams that run on Slack often collaborate in a pseudo-synchronous level, where collaboration is close to real-time, except when developers are deep in their code. The goal is to further improve the flexibility.

For example, the following frequent tasks should take just a click:

- Open a build log from your remote CI tool, and go to the failed tests in the code
- Open a teammate's commit diff for a quick code review on chat
- Open a Sentry crash report inside the VS Code debugger, to show state of the call stack and variable values at the time of the crash

And you will have your teammates alongside for a quick discussion without losing focus. Pseudo-sync use-cases are also a good place for teams to start sync sessions, and the extension will assist that transition.

## Chat providers

While Slack offered us an excellent API to kick-start the above, there is no reason for this extension to be tied to just Slack. The goal is to support other chat providers that teams use. See [PROVIDERS](docs/PROVIDERS.md) for more details on how that works.

## Healthy notifications

Chat notifications can be unhealthy: we need our focused time to think deeply about the code we write. The extension will always prioritize this need, and strive for a healthy balance between collaboration and focused solo time.


================================================
FILE: azure-pipelines.yml
================================================
queue:
  name: Hosted VS2017

steps:
  - task: NodeTool@0
    inputs:
      versionSpec: '10.x'
  - script: |
      npm install
      npm run compile
  - task: RichCodeNavIndexer@0
    inputs:
      serviceConnection: 'rich-code-nav'
      githubServiceConnection: 'vsls-contrib'
      languages: typescript


================================================
FILE: docs/CONFIG.md
================================================
# Configuration

## Network proxy

To use this extension behind a proxy, configure the proxy url.

```json
{
  "chat.proxyUrl": "YOUR_PROXY_URL"
}
```

## Self-signed certificates

If you have overriding self-signed SSL certificates, you can set the `rejectTlsUnauthorized` config to false.

```json
{
  "chat.rejectTlsUnauthorized": false
}
```

## Telemetry

This extension collects anonymized telemetry data to improve the product. This respects your editor's telemetry settings, and you can opt-out by setting the `enableTelemetry` setting to `false`.

```json
{
  "telemetry.enableTelemetry": false
}
```

## Auto-launch Live Share Chat

By default, the extension auto-launches the Live Share Chat window every time a new Live Share session is started. This behaviour can be disabled:

```json
{
  "chat.autoLaunchLiveShareChat": false
}
```


================================================
FILE: docs/CONTRIBUTING.md
================================================
# Contributing

The repo is actively developed, and you are welcome to [submit feature requests](https://github.com/karigari/vscode-chat/issues/new) and pull requests. [Issues](https://github.com/karigari/vscode-chat/issues) are the best place to look for contribution ideas.

If you want to work on something, just create a discussion thread (on PRs/issues) and we will help you get started.

## Repo structure

The repo has three parts:

1. Main extension code in TypeScript, in `src/**`
2. Webview UI code, written with Vue.js, in `src/webview/**`
3. OAuth service, built with the Serverless framework, in `oauth-service/**`

## Building

Open the project inside VS Code, and start debugging (F5). This will launch a new VS Code window (the extension development host) with the development code. See [this guide](https://code.visualstudio.com/docs/extensions/developing-extensions) to get started with development.

When you run a debug session, the `npm run watch` task starts up. This watches for file changes, recompiles, and you can reload the extension development host window to get the new code.

## Known issue

The watch command does not watch for CSS file changes. This means if you make changes to the `src/ui/static.css` file, you need to restart the `npm run watch` command manually. Best to make CSS changes live, with the Chrome dev tools, and then make file changes.

## Styling

The code is styled with [Prettier](https://prettier.io).

## Tests

`npm run test`

Tests can only be run when VS Code is not running. If you want to run tests alongside development, use VS Code Insiders for development.


================================================
FILE: docs/DISCORD.md
================================================
# Discord Setup

## Warning

The Discord integration involves an unofficial approach to getting the token, and is not recommended. The approach is similar to how users can potentially automate their logins ("create self-bots"), which are not allowed by the Discord ToS.

The goal is to move to [Discord RPC](https://discordapp.com/developers/docs/topics/rpc#proxied-api-requests) in the near-term, which supports proxied API/websocket requests with OAuth. Discord RPC is in private beta at the moment.

If you have any suggestions to improve this flow, please [create an issue](https://github.com/karigari/vscode-chat/issues).

## Obtaining the token

To set up Discord inside VS Code, you need to have your **Discord token**. To obtain your token, follow the steps [given here](https://discordhelp.net/discord-token).

This is an unofficial token setup, one that is used by other Discord clients ([Discline](https://github.com/MitchWeaver/Discline), [terminal-discord](https://github.com/xynxynxyn/terminal-discord)), and the recommended approach by a Discord team member, as [given here](https://github.com/discordapp/discord-api-docs/issues/69#issuecomment-223886862):

> Instead, log in on the discord client, pop open the web inspector, (ctrl/cmd shift I), and type localStorage.token in the console to get your auth token.

## Configuring the token

Once you have the token, run the following commands from the VS Code command palette:

1. Run **Chat: Configure Access Token**, select "Discord", and then paste your token in the input box. The token will be saved securely in your system keychain.

2. Next, you will be prompted to choose your primary Discord guild. If you don't want to select now, you can run the **Chat: Change Workspace** command later.


================================================
FILE: docs/PROVIDERS.md
================================================
# Chat providers

The goal of this extension is to open up support for other chat providers, in addition to Slack and Discord. Chat providers can be added by implementing the `IChatProvider` [interface](src/interfaces/index.ts). Providers will use a common set of types for `User`, `Channel`, `Message`.

For reference, see the implementation [for Slack](src/slack/index.ts) and [for Discord](src/discord/index.ts).

## Supported features

The extension supports the following features for Slack. Other chat providers can implement one or more features, depending on their API.

1. [Authentication](#authentication): Users can sign in with chat provider's OAuth
2. [Messaging](#messaging): Users can open a chat channel in a webview, and then send and receive messages
3. [Channels list](#channels-list): Users can see the list of public channels, direct messages and private groups (with unread counts) in the tree view
4. [Unreads](#unreads): Users can see the unread count in the status bar
5. [Presence](#presence): Users can see other online users in the Live Share tree view (requires VS Live Share)
6. [Collaboration invites](#collaboration-invites): Users can invite users or channels for a Live Share collaboration session (requires VS Live Share)

## Authentication

Slack uses OAuth with `client` scope. The result of a successful auth flow is a token string which is saved in the keychain. The other features are dependent on a successful authentication.

Requirements for providers

- Provide a "Sign in with X" link to launch OAuth flow
- Auth flow should return a token string that can be saved to system keychain

## Messaging

In addition to normal send/receive of messages in real-time, the Slack integration also supports threaded message replies, message reactions and file attachments. These are incorporated in the `Message` data type.

Requirements for providers

- API support to receive messages in real-time (Slack uses websocket)
- API support to send messages, as the authenticated user (not a bot)
- Optionally: thread replies, emoji reactions, file attachments

## Channels list

Slack supports three channel types: `channel` (public channels), `im` (direct messages), and `group` (private groups). These are fetched (from API, and then onwards from local storage) when the extension is activated.

Requirements for providers

- API support to fetch channels and users

## Unreads

The unread count can be historical (unread messages before user comes online) and in real-time (new messages when the user is online).

Requirements for providers

- Historical unreads: API support to return unread count for every channel
- Real-time unreads: The real-time messaging API can be used to update a running unread count for new messages
- API support to mark messages as read (which takes the count to 0)
- If the provider has other clients, then the API should support real-time updates to maintain unread count consistent with the other clients.

## Presence

User presence (online/offline status) shows green dots next to direct messaging channels in the tree view. When VS Live Share is available, a list of online users is shown in the Live Share activity bar, to send one-click collaboration invites.

Requirements for providers

- API support for real-time support for user presence updates

## Collaboration invites

To start a VS Live Share collaboration session, the extension supports one-click collaboration invites. The requirements for this are similar to the messaging feature.

Requirements for providers

- API support to receive real-time messages in the background
- API support to send messages


================================================
FILE: docs/SLACK.md
================================================
# Slack authorization

Many users have reported running into `access_denied` issues on Slack, and this doc attempts to list potential solutions to the problem.

In case you have questions about permission levels or what this extension accesses, please report an issue with your question.

## Admin approval required

Some workspaces require an explicit admin approval before users can install specific apps.

If your workspace needs this, please forward [this link](https://slack.com/apps/ACB4LQKN1-slack-chat-for-vs-code) to your workspace admins.

## Slack App Directory

Some workspaces also restrict apps that are only approved by the Slack app review process. Getting this done is in our backlog, and you can track progress in [this issue](https://github.com/karigari/vscode-chat/issues/78).

For now, you will need to manually approve the app for your workspace. This can be done by any admin of the workspace. Please use [this link](https://slack.com/apps/ACB4LQKN1-slack-chat-for-vs-code) for that.

## Free workspace app limit

If you are on a free Slack workspace, you can only have 10 installed apps. Attempting to install any more gives an `access_denied` error. To make this work without upgrading your Slack plan, you will need to remove an existing app.


================================================
FILE: oauth-service/README.md
================================================
# oauth-service

This is a serverless app to handle OAuth redirection for the Slack Chat extension, and it is deployed on AWS Lambda.

To deploy a new version of this service, run

```
serverless deploy --verbose
```

To test this service locally, run

```
serverless offline start
```

This service requires the `env.yml` file with the SLACK_CLIENT_ID and SLACK_CLIENT_SECRET keys.

## Custom domain

The oauth service runs on a custom domain ([vscode.chat](https://vscode.chat)), configured with the [serverless-domain-manager](https://github.com/amplify-education/serverless-domain-manager) plugin.

The following command needs to run before a new deploy if there are any changes to the yml, wrt function route definitions.

```
serverless create_domain
```


================================================
FILE: oauth-service/handler.ts
================================================
import { APIGatewayEvent, Callback, Context, Handler } from "aws-lambda";
import * as request from "request-promise-native";
import {
  parseQueryParams,
  getIssueUrl,
  getRedirect,
  getRedirectError
} from "./utils";
import errorHtml from "./html/error.template.html";
import successHtml from "./html/success.template.html";
import homeHtml from "./html/home.template.html";

interface TokenAPIResponse {
  accessToken: string;
  teamId?: string;
  expiresIn?: Date;
  refreshToken?: string;
  error: string;
}

const getSlackToken = async (code: string): Promise<TokenAPIResponse> => {
  const uri = "https://slack.com/api/oauth.access";
  var options = {
    uri,
    json: true,
    qs: {
      client_id: process.env.SLACK_CLIENT_ID,
      client_secret: process.env.SLACK_CLIENT_SECRET,
      code,
      // When testing locally, pass the redirect_uri to slack
      // redirect_uri: "http://localhost:3000/slack_redirect"
    }
  };

  const result = await request.get(options);
  const { ok, error, access_token, team_id } = result;

  if (!ok) {
    return { accessToken: null, error };
  } else {
    return { accessToken: access_token, teamId: team_id, error: null };
  }
};

const getDiscordToken = async (code: string): Promise<TokenAPIResponse> => {
  const uri = "https://discordapp.com/api/v6/oauth2/token";
  var options = {
    uri,
    method: "POST",
    formData: {
      client_id: process.env.DISCORD_CLIENT_ID,
      client_secret: process.env.DISCORD_CLIENT_SECRET,
      grant_type: "authorization_code",
      code
    }
  };

  try {
    const result = await request.post(options);
    const parsed = JSON.parse(result);
    var t = new Date();
    t.setSeconds(t.getSeconds() + parsed.expires_in);
    return {
      accessToken: parsed.access_token,
      expiresIn: t,
      refreshToken: parsed.refresh_token,
      error: null
    };
  } catch (error) {
    return { accessToken: null, error: error.message };
  }
};

const renderSuccess = (
  token: string,
  service: string,
  teamId: string,
  cb: Callback
) => {
  const redirect = getRedirect(token, service, teamId);
  const response = {
    statusCode: 200,
    headers: {
      "Content-Type": "text/html"
    },
    body: successHtml
      .replace(/{{redirect}}/g, redirect)
      .replace(/{{token}}/g, token)
  };
  cb(null, response);
};

const renderError = (error: string, service: string, cb: Callback) => {
  const issueUrl = getIssueUrl(error, service);
  const redirect = getRedirectError(error, service);
  const response = {
    statusCode: 200,
    headers: {
      "Content-Type": "text/html"
    },
    body: errorHtml
      .replace(/{{error}}/g, error)
      .replace(/{{redirect}}/g, redirect)
      .replace(/{{issues}}/g, issueUrl)
  };
  cb(null, response);
};

export const slackRedirect: Handler = (
  event: APIGatewayEvent,
  context: Context,
  cb: Callback
) => {
  const { error, code } = parseQueryParams(event);

  if (!!code) {
    const tokenPromise = getSlackToken(code);
    tokenPromise.then(result => {
      const { accessToken, error, teamId } = result;

      if (!accessToken) {
        renderError(error, "slack", cb);
      } else {
        renderSuccess(accessToken, "slack", teamId, cb);
      }
    });
  }

  if (!!error) {
    renderError(error, "slack", cb);
  }
};

export const discordRedirect: Handler = (
  event: APIGatewayEvent,
  context: Context,
  cb: Callback
) => {
  const { error, code } = parseQueryParams(event);

  if (!!code) {
    const tokenPromise = getDiscordToken(code);
    tokenPromise.then(result => {
      const { accessToken, error } = result;

      if (!accessToken) {
        renderError(error, "discord", cb);
      } else {
        renderSuccess(accessToken, "discord", "team-id", cb);
      }
    });
  }

  if (!!error) {
    renderError(error, "discord", cb);
  }
};

export const home: Handler = (
  event: APIGatewayEvent,
  context: Context,
  cb: Callback
) => {
  const response = {
    statusCode: 200,
    headers: {
      "Content-Type": "text/html"
    },
    body: homeHtml
  };
  cb(null, response);
};


================================================
FILE: oauth-service/html/error.template.html
================================================
<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
        crossorigin="anonymous">

    <title>Slack Chat for VS Code</title>
</head>

<body>
    <iframe width="0" height="0" src="{{redirect}}"></iframe>
    <div class="container my-4 text-center">
        <p>We have run into an error: <strong>{{error}}</strong></p>
        <p>If this is not right, please <a href="{{issues}}">report an issue</a></p>
    </div>
</body>

</html>

================================================
FILE: oauth-service/html/home.template.html
================================================
<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
        crossorigin="anonymous">

    <title>Slack Chat for VS Code</title>
</head>

<body>
    <div class="container my-4 text-center">
        <div class="my-4">
            <img src="https://raw.githubusercontent.com/karigari/vscode-chat/master/readme/preview.png" />
        </div>

        <div class="my-4">
            <img src="https://vsmarketplacebadge.apphb.com/installs/karigari.chat.svg" />
            <img src="https://img.shields.io/vscode-marketplace/r/karigari.chat.svg" />
        </div>

        <div class="my-4">
            <a href="https://github.com/karigari/vscode-chat">View Source</a> &#183; <a href="https://marketplace.visualstudio.com/items?itemName=karigari.chat">Install
                in VS Code</a>
        </div>

        <div class="my-4 alert alert-info" role="alert">
            <h5 class="alert-heading">Are you a Slack admin?</h5>
            <div><a href="https://slack.com/apps/ACB4LQKN1-slack-chat-for-vs-code">Approve for your workspace
                </a></div>
        </div>

        <div class="my-4 small">
            <a href="https://github.com/karigari/vscode-chat/issues/new">Support</a>
        </div>
    </div>
</body>

</html>

================================================
FILE: oauth-service/html/success.template.html
================================================
<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
        crossorigin="anonymous">

    <title>Slack Chat for VS Code</title>
</head>

<body>
    <iframe width="0" height="0" src="{{redirect}}"></iframe>
    <div class="container my-4 text-center">
        <p class="h3">Redirecting to VS Code...</p>
        <p class="my-4">Unable to redirect? Configure manually.</p>
        <div class="modal-dialog text-left">
            <div class="modal-content">
                <div class="modal-title">
                    <div class="d-flex align-items-center justify-content-center m-3">
                        <code id="code-token" style="height: 0; width: 1px; opacity: 0;">{{token}}</code>
                        <button type="button" class="btn btn-secondary btn-sm mx-2" onclick="runCopy()" id="copy-button">Copy
                            token
                        </button>
                    </div>
                </div>
                <div class="modal-body">
                    <ol>
                        <li class="my-1">Copy the token to clipboard.</li>
                        <li class="my-1">Inside VS Code, open the Command Palette.</li>
                        <li class="my-1">Pick <strong>Chat: Configure Slack Access Token</strong>.</li>
                        <li class="my-1">Paste the token.</li>
                    </ol>
                </div>
            </div>
        </div>
        <p><a href="https://github.com/karigari/vscode-chat/issues">Report an issue</a></p>
    </div>
</body>

<script type="text/javascript">
    function runCopy() {
        var code = document.getElementById("code-token")
        var range = document.createRange();
        range.selectNode(code);
        window.getSelection().removeAllRanges();
        window.getSelection().addRange(range);
        var button = document.getElementById('copy-button')
        try {
            document.execCommand("copy");
            button.textContent = "Copied!"
        } catch (err) {
            button.textContent = "Failed to copy"
        }
    }
</script>

</html>

================================================
FILE: oauth-service/html.d.ts
================================================
declare module "*.html" {
  const value: string;
  export default value;
}


================================================
FILE: oauth-service/package.json
================================================
{
  "name": "vscode-chat-oauth-service",
  "description": "Serverless app to handle Slack OAuth for vscode-chat",
  "version": "1.0.0",
  "main": "handler.js",
  "scripts": {
    "start": "npx serverless offline start"
  },
  "dependencies": {
    "request": "^2.88.0",
    "request-promise-native": "^1.0.5",
    "source-map-support": "^0.5.0"
  },
  "devDependencies": {
    "@types/aws-lambda": "8.10.1",
    "@types/node": "^8.0.57",
    "html-loader": "^0.5.5",
    "serverless-domain-manager": "^2.6.0",
    "serverless-offline": "^3.25.8",
    "serverless-webpack": "^5.1.1",
    "ts-loader": "^4.2.0",
    "typescript": "^2.8.1",
    "webpack": "^4.5.0"
  }
}


================================================
FILE: oauth-service/serverless.yml
================================================
service:
  name: vscode-chat-oauth-service

plugins:
  - serverless-webpack
  - serverless-offline
  - serverless-domain-manager

provider:
  name: aws
  runtime: nodejs8.10
  environment: ${file(./env.yml):${opt:stage, self:provider.stage}}

functions:
  slack-redirect:
    handler: handler.slackRedirect
    timeout: 10
    events:
      - http:
          method: get
          path: slack_redirect
  discord-redirect:
    handler: handler.discordRedirect
    timeout: 10
    events:
      - http:
          method: get
          path: discord_redirect
  home:
    handler: handler.home
    events:
      - http:
          method: get
          path: /

custom:
  customDomain:
    domainName: vscode.chat
    certificateArn: arn:aws:acm:us-east-1:750374355341:certificate/dd3d7f2f-e25f-46b9-8cad-93784e9b2e9b
    stage: ${self:provider.stage}
    createRoute53Record: true


================================================
FILE: oauth-service/source-map-install.js
================================================
require('source-map-support').install();


================================================
FILE: oauth-service/tsconfig.json
================================================
{
  "compilerOptions": {
    "sourceMap": true,
    "target": "es6",
    "lib": [
      "esnext"
    ],
    "moduleResolution": "node"
  },
  "exclude": [
    "node_modules"
  ]
}


================================================
FILE: oauth-service/utils.ts
================================================
import { APIGatewayEvent } from "aws-lambda";

export const parseQueryParams = (event: APIGatewayEvent) => {
  const { queryStringParameters } = event;
  let error, code;

  if (!!queryStringParameters) {
    code = queryStringParameters.code;
    error = queryStringParameters.error;
  } else {
    error = "no_code_param";
  }

  return { code, error };
};

export const getIssueUrl = (errorMessage: string, serviceName: string) => {
  const encode = encodeURIComponent;
  const title = `[oauth-service] Sign in with ${serviceName} failed: ${errorMessage}`;
  const body = `- Extension version:\n- VS Code version:`;
  const baseUrl = "https://github.com/karigari/vscode-chat/issues/new/";
  return `${baseUrl}?title=${encode(title)}&body=${encode(body)}`;
};

export const getRedirect = (token: string, service: string, team: string) => {
  return `vscode://karigari.chat/redirect?token=${token}&service=${service}&team=${team}`;
};

export const getRedirectError = (errorMessage: string, serviceName: string) => {
  return `vscode://karigari.chat/error?msg=${errorMessage}&service=${serviceName}`;
};


================================================
FILE: oauth-service/webpack.config.js
================================================
const path = require("path");
const slsw = require("serverless-webpack");

const entries = {};

Object.keys(slsw.lib.entries).forEach(
  key => (entries[key] = ["./source-map-install.js", slsw.lib.entries[key]])
);

module.exports = {
  mode: slsw.lib.webpack.isLocal ? "development" : "production",
  entry: entries,
  devtool: "source-map",
  resolve: {
    extensions: [".js", ".jsx", ".json", ".ts", ".tsx", ".html"]
  },
  output: {
    libraryTarget: "commonjs",
    path: path.join(__dirname, ".webpack"),
    filename: "[name].js"
  },
  target: "node",
  module: {
    rules: [
      { test: /\.tsx?$/, loader: "ts-loader" },
      { test: /\.html$/, loader: "html-loader" }
    ]
  }
};


================================================
FILE: oauth-service-2/.gcloudignore
================================================
# This file specifies files that are *not* uploaded to Google Cloud Platform
# using gcloud. It follows the same syntax as .gitignore, with the addition of
# "#!include" directives (which insert the entries of the given .gitignore-style
# file at that point).
#
# For more information, run:
#   $ gcloud topic gcloudignore
#
.gcloudignore
# If you would like to upload your .git directory, .gitignore file or files
# from your .gitignore file, remove the corresponding line
# below:
.git
.gitignore

node_modules


================================================
FILE: oauth-service-2/README.md
================================================
# Oauth redirection service

## Running locally

```
npm start
```

## Deployment

```
gcloud functions deploy slackRedirect --set-env-vars SLACK_CLIENT_ID=<VALUE>,SLACK_CLIENT_SECRET=<VALUE> --runtime nodejs10 --trigger-http
```


================================================
FILE: oauth-service-2/htmls.js
================================================
exports.success = `
<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
        crossorigin="anonymous">

    <title>Slack Chat for VS Code</title>
</head>

<body>
    <iframe width="0" height="0" src="{{redirect}}"></iframe>
    <div class="container my-4 text-center">
        <p class="h3">Redirecting to VS Code...</p>
        <p class="my-4">Unable to redirect? Configure manually.</p>
        <div class="modal-dialog text-left">
            <div class="modal-content">
                <div class="modal-title">
                    <div class="d-flex align-items-center justify-content-center m-3">
                        <code id="code-token" style="height: 0; width: 1px; opacity: 0;">{{token}}</code>
                        <button type="button" class="btn btn-secondary btn-sm mx-2" onclick="runCopy()" id="copy-button">Copy
                            token
                        </button>
                    </div>
                </div>
                <div class="modal-body">
                    <ol>
                        <li class="my-1">Copy the token to clipboard.</li>
                        <li class="my-1">Inside VS Code, open the Command Palette.</li>
                        <li class="my-1">Pick <strong>Chat: Configure Slack Access Token</strong>.</li>
                        <li class="my-1">Paste the token.</li>
                    </ol>
                </div>
            </div>
        </div>
        <p><a href="https://github.com/karigari/vscode-chat/issues">Report an issue</a></p>
    </div>
</body>

<script type="text/javascript">
    function runCopy() {
        var code = document.getElementById("code-token")
        var range = document.createRange();
        range.selectNode(code);
        window.getSelection().removeAllRanges();
        window.getSelection().addRange(range);
        var button = document.getElementById('copy-button')
        try {
            document.execCommand("copy");
            button.textContent = "Copied!"
        } catch (err) {
            button.textContent = "Failed to copy"
        }
    }
</script>

</html>
`

exports.error = `
<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
        crossorigin="anonymous">

    <title>Slack Chat for VS Code</title>
</head>

<body>
    <iframe width="0" height="0" src="{{redirect}}"></iframe>
    <div class="container my-4 text-center">
        <p>We have run into an error: <strong>{{error}}</strong></p>
        <p>If this is not right, please <a href="{{issues}}">report an issue</a></p>
    </div>
</body>

</html>
`

================================================
FILE: oauth-service-2/index.js
================================================
//@ts-check
const utils = require('./utils');
const htmls = require('./htmls');
const request = require('request-promise-native');

async function getSlackToken(code) {
  const uri = "https://slack.com/api/oauth.access";
  var options = {
    uri,
    json: true,
    qs: {
      client_id: process.env.SLACK_CLIENT_ID,
      client_secret: process.env.SLACK_CLIENT_SECRET,
      code,
      // When testing locally, pass the redirect_uri to slack
      redirect_uri: "https://us-central1-eco-theater-119616.cloudfunctions.net/slackRedirect"
    }
  };

  const result = await request.get(options);
  const { ok, error, access_token, team_id } = result;

  if (!ok) {
    return { accessToken: null, error };
  } else {
    return { accessToken: access_token, teamId: team_id, error: null };
  }
}

const renderSuccess = (token, service, teamId, response) => {
  const redirect = utils.redirectUrl(token, service, teamId);
  response.set('Content-Type', 'text/html');
  response.status(200).send(
    htmls.success
      .replace(/{{redirect}}/g, redirect)
      .replace(/{{token}}/g, token)
  );
};

const renderError = (error, service, response) => {
  const issueUrl = utils.issueUrl(error, service);
  const redirect = utils.redirectError(error, service);
  response.set('Content-Type', 'text/html');
  response.status(200).send(
    htmls.error
      .replace(/{{error}}/g, error)
      .replace(/{{redirect}}/g, redirect)
      .replace(/{{issues}}/g, issueUrl)
  );
};

exports.slackRedirect = async (req, res) => {
  const { error, code } = req.query;
  if (!!code) {
    const tokenPromise = getSlackToken(code);
    tokenPromise.then(result => {
      const { accessToken, error, teamId } = result;

      if (!accessToken) {
        renderError(error, "slack", res);
      } else {
        renderSuccess(accessToken, "slack", teamId, res);
      }
    });
  } else {
    renderError(error, "slack", res);
  }
};

================================================
FILE: oauth-service-2/package.json
================================================
{
  "name": "oauth-service-2",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "functions-framework --target=slackRedirect"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@google-cloud/functions-framework": "^1.5.1"
  },
  "dependencies": {
    "request": "^2.88.2",
    "request-promise-native": "^1.0.8"
  }
}


================================================
FILE: oauth-service-2/utils.js
================================================
exports.redirectUrl = (token, service, team) => {
  return `vscode://karigari.chat/redirect?token=${token}&service=${service}&team=${team}`;
}

exports.issueUrl = (errorMessage, serviceName) => {
  const encode = encodeURIComponent;
  const title = `[oauth-service] Sign in with ${serviceName} failed: ${errorMessage}`;
  const body = `- Extension version:\n- VS Code version:`;
  const baseUrl = "https://github.com/karigari/vscode-chat/issues/new/";
  return `${baseUrl}?title=${encode(title)}&body=${encode(body)}`;
};

exports.redirectError = (errorMessage, serviceName) => {
  return `vscode://karigari.chat/error?msg=${errorMessage}&service=${serviceName}`;
};


================================================
FILE: package.json
================================================
{
    "name": "chat",
    "displayName": "Chat",
    "description": "Chat with your Slack and Discord teams from within VS Code",
    "version": "0.35.0",
    "homepage": "https://github.com/vsls-contrib/chat",
    "license": "SEE LICENSE IN LICENSE",
    "repository": {
        "type": "git",
        "url": "https://github.com/vsls-contrib/chat.git"
    },
    "bugs": {
        "url": "https://github.com/vsls-contrib/chat/issues"
    },
    "publisher": "karigari",
    "engines": {
        "vscode": "^1.26.0"
    },
    "icon": "public/icon.png",
    "galleryBanner": {
        "color": "#233f6c",
        "theme": "dark"
    },
    "categories": [
        "Other"
    ],
    "keywords": [
        "slack",
        "discord",
        "collaboration",
        "chat",
        "live"
    ],
    "activationEvents": [
        "*"
    ],
    "main": "./out/extension",
    "contributes": {
        "configuration": {
            "type": "object",
            "title": "Team Chat",
            "properties": {
                "chat.slack.legacyToken": {
                    "type": "string",
                    "default": null,
                    "description": "[Deprecated] Run the \"Sign In with Slack\" command instead."
                },
                "chat.proxyUrl": {
                    "type": "string",
                    "default": null,
                    "description": "Proxy URL for network connections to the Slack http/websocket requests."
                },
                "chat.rejectTlsUnauthorized": {
                    "type": "boolean",
                    "default": true,
                    "description": "Set this to false to accept unauthorized SSL connections. Defaults to true."
                },
                "chat.providers": {
                    "type": "array",
                    "default": null,
                    "description": "[Experimental] Open bot links inside VS Code. For travis-ci.org, set configuration [\"travis\"]."
                },
                "chat.autoLaunchLiveShareChat": {
                    "type": "boolean",
                    "default": true,
                    "description": "If enabled, the Live Share Chat window will auto-launch when a collaboration session is started."
                }
            }
        },
        "commands": [
            {
                "command": "extension.chat.openChatPanel",
                "title": "Open",
                "category": "Chat"
            },
            {
                "command": "extension.chat.changeChannel",
                "title": "Change Channel",
                "category": "Chat",
                "icon": {
                    "light": "public/icons/light/search.svg",
                    "dark": "public/icons/dark/search.svg"
                }
            },
            {
                "command": "extension.chat.changeWorkspace",
                "title": "Change Workspace",
                "category": "Chat"
            },
            {
                "command": "extension.chat.authenticate",
                "title": "Sign In with Slack",
                "category": "Chat"
            },
            {
                "command": "extension.chat.signout",
                "title": "Sign Out",
                "category": "Chat"
            },
            {
                "command": "extension.chat.configureToken",
                "title": "Configure Access Token",
                "category": "Chat"
            },
            {
                "command": "extension.chat.updateSelfPresence",
                "title": "Update your presence status",
                "category": "Chat"
            },
            {
                "command": "extension.chat.startLiveShare",
                "title": "Invite to Live Share",
                "category": "Chat",
                "icon": {
                    "light": "public/icons/light/share.svg",
                    "dark": "public/icons/dark/share.svg"
                }
            },
            {
                "command": "extension.chat.chatWithSpace",
                "title": "Open Chat",
                "category": "Chat",
                "icon": {
                    "light": "public/icons/light/chat.svg",
                    "dark": "public/icons/dark/chat.svg"
                }
            }
        ],
        "views": {
            "chatActivityViewSlack": [
                {
                    "id": "chat.treeView.workspaces.slack",
                    "name": "Workspaces",
                    "when": "chat:slack"
                },
                {
                    "id": "chat.treeView.unreads.slack",
                    "name": "Unreads",
                    "when": "chat:slack"
                },
                {
                    "id": "chat.treeView.channels.slack",
                    "name": "Channels",
                    "when": "chat:slack"
                },
                {
                    "id": "chat.treeView.groups.slack",
                    "name": "Groups",
                    "when": "chat:slack"
                },
                {
                    "id": "chat.treeView.ims.slack",
                    "name": "Direct Messages",
                    "when": "chat:slack"
                }
            ],
            "chatActivityViewDiscord": [
                {
                    "id": "chat.treeView.workspaces.discord",
                    "name": "Workspaces",
                    "when": "chat:discord"
                },
                {
                    "id": "chat.treeView.unreads.discord",
                    "name": "Unreads",
                    "when": "chat:discord"
                },
                {
                    "id": "chat.treeView.channels.discord",
                    "name": "Channels",
                    "when": "chat:discord"
                },
                {
                    "id": "chat.treeView.groups.discord",
                    "name": "Groups",
                    "when": "chat:discord"
                },
                {
                    "id": "chat.treeView.ims.discord",
                    "name": "Direct Messages",
                    "when": "chat:discord"
                }
            ]
        },
        "viewsContainers": {
            "activitybar": [
                {
                    "id": "chatActivityViewSlack",
                    "title": "Slack",
                    "icon": "public/icons/activity-bar-slack-icon.svg",
                    "when": "chat:slack"
                },
                {
                    "id": "chatActivityViewDiscord",
                    "title": "Discord",
                    "icon": "public/icons/activity-bar-discord-icon.svg",
                    "when": "chat:discord"
                }
            ]
        },
        "menus": {
            "view/item/context": [
                {
                    "command": "extension.chat.startLiveShare",
                    "when": "chat:vslsEnabled && viewItem == channel",
                    "group": "inline"
                },
                {
                    "command": "extension.chat.chatWithSpace",
                    "when": "view == liveshare.spaces && viewItem =~ /^space/",
                    "group": "chat@1"
                },
                {
                    "command": "extension.chat.chatWithSpace",
                    "when": "view == liveshare.spaces && viewItem =~ /^space/",
                    "group": "inline@1"
                }
            ],
            "view/title": [
                {
                    "command": "extension.chat.changeChannel",
                    "when": "view =~ /^chat.treeView(?!.onboarding)/",
                    "group": "navigation@1"
                }
            ],
            "commandPalette": [
                {
                    "command": "extension.chat.openChatPanel",
                    "when": "false"
                },
                {
                    "command": "extension.chat.updateSelfPresence",
                    "when": "false"
                },
                {
                    "command": "extension.chat.startLiveShare",
                    "when": "false"
                },
                {
                    "command": "extension.chat.chatWithSpace",
                    "when": "false"
                }
            ]
        }
    },
    "scripts": {
        "compile": "webpack",
        "compile:tsc": "tsc -p ./",
        "postcompile": "npm run webview",
        "watch": "tsc-watch -p ./",
        "postinstall": "node ./node_modules/vscode/bin/install",
        "test": "npm run compile:tsc && node ./node_modules/vscode/bin/test",
        "webview": "cd webview && npm run build",
        "vscode:prepublish": "npm run compile"
    },
    "devDependencies": {
        "@types/http-proxy-agent": "^2.0.0",
        "@types/keytar": "^4.0.1",
        "@types/markdown-it": "^0.0.7",
        "@types/mixpanel": "^2.14.0",
        "@types/mocha": "^2.2.42",
        "@types/node": "*",
        "@types/request-promise-native": "^1.0.15",
        "@types/semver": "^5.5.0",
        "@types/webpack": "^4.4.10",
        "native-modules": "^1.1.0",
        "shx": "^0.3.2",
        "ts-loader": "^5.3.3",
        "ts-mockito": "^2.3.1",
        "tsc-watch": "^1.0.22",
        "tslint": "^5.8.0",
        "typescript": "^3.1.4",
        "vscode": "^1.1.6",
        "webpack": "^4.28.3",
        "webpack-cli": "^3.2.0"
    },
    "dependencies": {
        "@slack/client": "^4.6.0",
        "discord.js": "^11.4.2",
        "emoji-js": "^3.4.1",
        "gravatar-api": "^1.5.0",
        "https-proxy-agent": "^2.2.1",
        "mixpanel": "^0.9.2",
        "request": "^2.88.0",
        "request-promise-native": "^1.0.5",
        "semver": "^5.5.1",
        "vsls": "^0.3.1291"
    }
}


================================================
FILE: src/bots/travis.ts
================================================
import * as vscode from "vscode";
import * as rp from "request-promise-native";
import {
  CommandHandler,
  CommandResponse,
  MessageCommand
} from "../controller/commands";
import { TRAVIS_SCHEME } from "../constants";

function getTravisBuild(username: string, reponame: string, build: string) {
  return rp({
    baseUrl: "https://api.travis-ci.org/",
    uri: `repos/${username}/${reponame}/builds/${build}`,
    json: true,
    headers: {
      Accept: "application/vnd.travis-ci.2.1+json"
    }
  }).then(response => {
    const { jobs } = response;

    if (jobs) {
      return rp({
        baseUrl: "https://api.travis-ci.org/",
        uri: `jobs/${jobs[0].id}/log`
      });
    }
  });
}

function stripAnsiEscapes(input: string) {
  // Credits: https://stackoverflow.com/a/29497680/1469222
  return input.replace(
    /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,
    ""
  );
}

export class TravisLinkHandler implements CommandHandler {
  handle(cmd: MessageCommand): Promise<CommandResponse> {
    const { subcommand } = cmd;
    const { path } = vscode.Uri.parse(subcommand);
    const matched = path.match(/^\/(.+)\/(.+)\/(.+)\/(.+)$/);

    if (!!matched && matched.length) {
      const user = matched[1];
      const repo = matched[2];
      const buildId = matched[4];
      vscode.window.showTextDocument(
        vscode.Uri.parse(`${TRAVIS_SCHEME}://${user}/${repo}/${buildId}`),
        { viewColumn: vscode.ViewColumn.One }
      );
    }

    const response: CommandResponse = { sendToSlack: false, response: "" };
    return Promise.resolve(response);
  }
}

class TravisDocumentContentProvider
  implements vscode.TextDocumentContentProvider {
  provideTextDocumentContent(uri: vscode.Uri): vscode.ProviderResult<string> {
    const { authority, path } = uri;
    const splitPath = path.split("/");
    return getTravisBuild(authority, splitPath[1], splitPath[2]).then(
      response => stripAnsiEscapes(response)
    );
  }
}

export default new TravisDocumentContentProvider();


================================================
FILE: src/config/https-proxy-agent.d.ts
================================================
// foo.d.ts
declare module "https-proxy-agent";


================================================
FILE: src/config/index.ts
================================================
import * as vscode from "vscode";
import * as https from "https";
import * as HttpsProxyAgent from "https-proxy-agent";
import { CONFIG_ROOT, SelfCommands } from "../constants";
import { KeychainHelper } from "./keychain";

const TOKEN_CONFIG_KEY = "slack.legacyToken";
const TELEMETRY_CONFIG_ROOT = "telemetry";
const TELEMETRY_CONFIG_KEY = "enableTelemetry";
const CREDENTIAL_SERVICE_NAME = "vscode-chat";
const VSLS_CHAT_TOKEN = "vsls-placeholder-token";

const getAccountName = (provider: string, teamId?: string) => {
  return !!teamId ? `${provider} (${teamId})` : provider;
};

export class ConfigHelper {
  static getRootConfig() {
    return vscode.workspace.getConfiguration(CONFIG_ROOT);
  }

  static updateRootConfig(section: string, value: any): Promise<void> {
    // Convert Thenable to Promise to be able to use Promise.all
    const rootConfig = this.getRootConfig();
    return new Promise((resolve, reject) => {
      rootConfig.update(section, value, vscode.ConfigurationTarget.Global).then(
        result => {
          return resolve(result);
        },
        error => {
          return reject(error);
        }
      );
    });
  }

  static async getToken(
    service: string,
    teamId?: string
  ): Promise<string | null> {
    if (service === "vslsSpaces") {
      return VSLS_CHAT_TOKEN;
    }

    const accountName = getAccountName(service, teamId);
    const keychainToken: string | null = await KeychainHelper.get(
      CREDENTIAL_SERVICE_NAME,
      accountName
    );
    return keychainToken;
  }

  static clearTokenFromSettings() {
    this.updateRootConfig(TOKEN_CONFIG_KEY, undefined);
  }

  static async setToken(
    token: string,
    providerName: string,
    teamId?: string
  ): Promise<void> {
    // TODO: it is possible that the keychain will fail
    // See https://github.com/Microsoft/vscode-pull-request-github/commit/306dc5d27460599f3402f4b9e01d97bf638c639f
    const accountName = getAccountName(providerName, teamId);
    await KeychainHelper.set(CREDENTIAL_SERVICE_NAME, accountName, token);

    // When token is set, we need to call reset
    vscode.commands.executeCommand(SelfCommands.SETUP_NEW_PROVIDER, {
      newInitialState: { provider: providerName, teamId }
    });
  }

  static async clearToken(provider: string, teamId?: string): Promise<void> {
    await KeychainHelper.clear(
      CREDENTIAL_SERVICE_NAME,
      getAccountName(provider, teamId)
    );
  }

  static getProxyUrl() {
    // Stored under CONFIG_ROOT.proxyUrl
    const { proxyUrl } = this.getRootConfig();
    return proxyUrl;
  }

  static getTlsRejectUnauthorized() {
    const { rejectTlsUnauthorized } = this.getRootConfig();
    return rejectTlsUnauthorized;
  }

  static getAutoLaunchLiveShareChat() {
    const { autoLaunchLiveShareChat } = this.getRootConfig();
    return autoLaunchLiveShareChat;
  }

  static hasTelemetry(): boolean {
    const config = vscode.workspace.getConfiguration(TELEMETRY_CONFIG_ROOT);
    return !!config.get<boolean>(TELEMETRY_CONFIG_KEY);
  }

  static hasTravisProvider(): boolean {
    // Stored under CONFIG_ROOT.providers, which is string[]
    const { providers } = this.getRootConfig();
    return providers && providers.indexOf("travis") >= 0;
  }

  static getCustomAgent() {
    const proxyUrl = this.getProxyUrl();

    if (!!proxyUrl) {
      return new HttpsProxyAgent(proxyUrl);
    }

    const rejectUnauthorized = this.getTlsRejectUnauthorized();

    if (!rejectUnauthorized) {
      return new https.Agent({
        rejectUnauthorized: false
      });
    }
  }
}


================================================
FILE: src/config/keychain.ts
================================================
import * as vscode from "vscode";
import * as str from "../strings";
import { keychain } from "../utils/keychain";
import IssueReporter from "../issues";
import Logger from "../logger";

const UNDEFINED_ERROR = "System keychain is undefined";

export class KeychainHelper {
  // Adds retry to keychain operations if we are denied access
  static async handleException(error: Error, retryCall: Function) {
    Logger.log(`Keychain access: ${error}`);
    const actionItems = [str.RETRY, str.REPORT_ISSUE];
    const action = await vscode.window.showInformationMessage(
      str.KEYCHAIN_ERROR,
      ...actionItems
    );

    switch (action) {
      case str.RETRY:
        return retryCall();
      case str.REPORT_ISSUE:
        const title = "Unable to access keychain";
        return IssueReporter.openNewIssue(title, `${error}`);
    }
  }

  static async get(service: string, account: string) {
    try {
      if (!keychain) {
        throw new Error(UNDEFINED_ERROR);
      }

      const password = await keychain.getPassword(service, account);
      return password;
    } catch (error) {
      // If user denies, we can catch the error
      // On Mac, this looks like `Error: User canceled the operation.`
      return this.handleException(error, () => this.get(service, account));
    }
  }

  static async set(service: string, account: string, password: string) {
    try {
      if (!keychain) {
        throw new Error(UNDEFINED_ERROR);
      }

      await keychain.setPassword(service, account, password);
    } catch (error) {
      return this.handleException(error, () =>
        this.set(service, account, password)
      );
    }
  }

  static async clear(service: string, account: string) {
    try {
      if (!keychain) {
        throw new Error(UNDEFINED_ERROR);
      }

      await keychain.deletePassword(service, account);
    } catch (error) {
      return this.handleException(error, () => this.clear(service, account));
    }
  }
}


================================================
FILE: src/constants.ts
================================================
export const CONFIG_ROOT = "chat";
export const EXTENSION_ID = "karigari.chat";
export const OUTPUT_CHANNEL_NAME = "Team Chat";
export const CONFIG_AUTO_LAUNCH = "chat.autoLaunchLiveShareChat";

// Is there a way to get this url from the vsls extension?
export const LIVE_SHARE_BASE_URL = `insiders.liveshare.vsengsaas.visualstudio.com`;
export const VSLS_EXTENSION_ID = `ms-vsliveshare.vsliveshare`;
export const VSLS_EXTENSION_PACK_ID = `ms-vsliveshare.vsliveshare-pack`;
export const VSLS_SPACES_EXTENSION_ID = `vsls-contrib.spaces`;

export const LiveShareCommands = {
    START: "liveshare.start",
    END: "liveshare.end",
    JOIN: "liveshare.join"
};

export const VSCodeCommands = {
    OPEN: "vscode.open",
    OPEN_SETTINGS: "workbench.action.openSettings"
};

export const SelfCommands = {
    OPEN_WEBVIEW: "extension.chat.openChatPanel",
    CHANGE_WORKSPACE: "extension.chat.changeWorkspace",
    CHANGE_CHANNEL: "extension.chat.changeChannel",
    SIGN_IN: "extension.chat.authenticate",
    SIGN_OUT: "extension.chat.signout",
    CONFIGURE_TOKEN: "extension.chat.configureToken",
    LIVE_SHARE_FROM_MENU: "extension.chat.startLiveShare",
    LIVE_SHARE_SLASH: "extension.chat.slashLiveShare",
    LIVE_SHARE_SESSION_CHANGED: "extension.chat.vslsSessionChanged",
    RESET_STORE: "extension.chat.reset",
    SETUP_NEW_PROVIDER: "extension.chat.setupNewProvider",
    FETCH_REPLIES: "extension.chat.fetchReplies",
    UPDATE_MESSAGES: "extension.chat.updateMessages",
    CLEAR_MESSAGES: "extension.chat.clearMessages",
    UPDATE_MESSAGE_REPLIES: "extension.chat.updateReplies",
    UPDATE_PRESENCE_STATUSES: "extension.chat.updatePresenceStatuses",
    UPDATE_SELF_PRESENCE: "extension.chat.updateSelfPresence",
    UPDATE_SELF_PRESENCE_VIA_VSLS: "extension.chat.updateSelfPresenceVsls",
    ADD_MESSAGE_REACTION: "extension.chat.addMessageReaction",
    REMOVE_MESSAGE_REACTION: "extension.chat.removeMessageReaction",
    SEND_MESSAGE: "extension.chat.sendMessage",
    SEND_THREAD_REPLY: "extension.chat.sendThreadReply",
    SEND_TYPING: "extension.chat.sendTypingMessage",
    SHOW_TYPING: "extension.chat.showTypingMessage",
    INVITE_LIVE_SHARE_CONTACT: "extension.chat.inviteLiveShareContact",
    CHANNEL_MARKED: "extension.chat.updateChannelMark",
    HANDLE_INCOMING_LINKS: "extension.chat.handleIncomingLinks",
    SEND_TO_WEBVIEW: "extension.chat.sendToWebview",
    CHAT_WITH_VSLS_SPACE: "extension.chat.chatWithSpace",
    VSLS_SPACE_JOINED: "extension.chat.vslsSpaceJoined"
};

export const SLASH_COMMANDS: any = {
    live: {
        share: {
            action: LiveShareCommands.START,
            options: { suppressNotification: true }
        },
        end: { action: LiveShareCommands.END, options: {} }
    }
};

// Reverse commands are acted on when received from Slack
export const REVERSE_SLASH_COMMANDS = {
    live: {
        request: {}
    }
};

// Internal uri schemes
export const TRAVIS_BASE_URL = `travis-ci.org`;
export const TRAVIS_SCHEME = "chat-travis-ci";

// Slack App
const REDIRECT_URI = `https://us-central1-eco-theater-119616.cloudfunctions.net/slackRedirect`
const SLACK_OAUTH_BASE = `https://slack.com/oauth/authorize?scope=client&client_id=282186700213.419156835749`;
export const SLACK_OAUTH = `${SLACK_OAUTH_BASE}&redirect_uri=${REDIRECT_URI}`

// Discord
const DISCORD_SCOPES = ["identify", "rpc.api", "messages.read", "guilds"];
const DISCORD_SCOPE_STRING = DISCORD_SCOPES.join("%20");
const DISCORD_CLIENT_ID = "486416707951394817";
export const DISCORD_OAUTH = `https://discordapp.com/oauth2/authorize?client_id=${DISCORD_CLIENT_ID}&response_type=code&scope=${DISCORD_SCOPE_STRING}`;

// Telemetry
export const MIXPANEL_TOKEN = "14c9fea2bf4e06ba766e16eca1bce728";


================================================
FILE: src/controller/commands.ts
================================================
import * as vscode from "vscode";
import * as vsls from "vsls";
import {
  SLASH_COMMANDS,
  LIVE_SHARE_BASE_URL,
  TRAVIS_BASE_URL,
  VSCodeCommands
} from "../constants";
import { TravisLinkHandler } from "../bots/travis";
import { ConfigHelper } from "../config";

export interface MessageCommand {
  namespace: string;
  subcommand: string;
}

export interface CommandResponse {
  sendToSlack: Boolean;
  response: string;
}

export interface CommandHandler {
  handle: (cmd: MessageCommand) => Promise<CommandResponse>;
}

class VscodeCommandHandler implements CommandHandler {
  execute = (command: string, ...rest: any[]): Promise<any> => {
    // Wraps the executeCommand thenable into a promise
    // https://github.com/Microsoft/vscode/issues/11693#issuecomment-247495996
    return new Promise((resolve, reject) => {
      vscode.commands.executeCommand(command, ...rest).then(
        result => {
          return resolve(result);
        },
        error => {
          vscode.window.showErrorMessage(error.toString());
          return reject(error);
        }
      );
    });
  };

  handle = (cmd: MessageCommand): Promise<CommandResponse> => {
    const { namespace, subcommand } = cmd;
    const commands = SLASH_COMMANDS[namespace];
    const { action, options } = commands[subcommand];
    return this.execute(action, options).then((response: vscode.Uri) => {
      // We append </> to the URL so our link parsing works
      // TODO(arjun) Uri is only valid for `/live share` command
      const responseString = response ? `<${response.toString()}>` : "";
      const sendToSlack = namespace === "live" && subcommand === "share";
      return { sendToSlack, response: responseString };
    });
  };
}

class OpenCommandHandler extends VscodeCommandHandler {
  handle = async (cmd: MessageCommand): Promise<any> => {
    const { subcommand } = cmd;
    let uri: vscode.Uri | undefined;

    try {
      uri = vscode.Uri.parse(subcommand);

      switch (uri.authority) {
        case LIVE_SHARE_BASE_URL:
          const liveshare = await vsls.getApi();
          const opts: vsls.JoinOptions = { newWindow: false };

          if (liveshare) {
            await liveshare.join(uri, opts);
          }

          break;
        case TRAVIS_BASE_URL:
          if (ConfigHelper.hasTravisProvider()) {
            const travisHandler = new TravisLinkHandler();
            return travisHandler.handle(cmd);
          }
        default:
          return this.execute(VSCodeCommands.OPEN, uri);
      }
    } catch (err) {
      // return new Promise((_, reject) => reject());
    }
  };
}

/**
 * Finds the correct command handler for the given command
 * and runs it
 */
export default class CommandDispatch {
  handle = (message: MessageCommand): Promise<CommandResponse> => {
    const { namespace, subcommand } = message;

    if (namespace === "open") {
      // We might have to convert this into
      const openHandler = new OpenCommandHandler();
      return openHandler.handle(message);
    } else {
      // Others are all vs code commands
      const vscodeHandler = new VscodeCommandHandler();
      return vscodeHandler.handle(message);
    }
  };
}


================================================
FILE: src/controller/emoji-js.d.ts
================================================
// foo.d.ts
declare module "emoji-js";


================================================
FILE: src/controller/index.ts
================================================
import * as vscode from "vscode";
import WebviewContainer from "../webview";
import { SLASH_COMMANDS, REVERSE_SLASH_COMMANDS, SelfCommands } from "../constants";
import Logger from "../logger";
import CommandDispatch, { MessageCommand } from "./commands";
import markdownTransform from "./markdowner";

export const getCommand = (text: string): MessageCommand | undefined => {
    const pattern = /^\/(\w+) (\w+)$/;
    const trimmed = text.trim();
    const matched = trimmed.match(pattern);

    if (matched) {
        return { namespace: matched[1], subcommand: matched[2] };
    }
};

class ViewController {
    ui: WebviewContainer | undefined;
    isUIReady: Boolean = false; // Vuejs loaded
    pendingMessage: UIMessage | undefined = undefined;

    currentSource: EventSource | undefined;
    currentProvider: string | undefined;
    currentChannelId: string | undefined;

    constructor(
        private context: vscode.ExtensionContext,
        private onUIDispose: (provider: string | undefined, source: EventSource | undefined) => void,
        private onUIVisible: (provider: string | undefined) => void,
        private onUIFocus: (provider: string | undefined) => void
    ) {}

    isUILoaded = () => !!this.ui;

    loadUi = () => {
        if (this.ui) {
            this.ui.reveal();
        } else {
            const { extensionPath } = this.context;
            this.ui = new WebviewContainer(
                extensionPath,
                () => {
                    this.ui = undefined;
                    this.isUIReady = false;
                    this.onUIDispose(this.currentProvider, this.currentSource);
                },
                isVisible => (isVisible ? this.onUIVisible(this.currentProvider) : null)
            );
            this.ui.setMessageHandler(this.sendToExtension);
        }
    };

    dispatchCommand(command: MessageCommand) {
        const handler = new CommandDispatch();

        handler.handle(command).then(result => {
            if (!!result) {
                const { sendToSlack, response } = result;
                if (sendToSlack && response) {
                    this.sendTextMessage(response);
                }
            }
        });
    }

    isValidCommand = (text: string, commandList: { [name: string]: any }) => {
        const parsed = getCommand(text);

        if (parsed) {
            const { namespace, subcommand } = parsed;

            if (namespace in commandList) {
                const subcommands = Object.keys(commandList[namespace]);
                return subcommands.indexOf(subcommand) >= 0;
            }
        }

        return false;
    };

    isValidReverseCommand = (text: string) => {
        return this.isValidCommand(text, REVERSE_SLASH_COMMANDS);
    };

    handleCommand = (text: string) => {
        if (this.isValidCommand(text, SLASH_COMMANDS)) {
            const parsed = getCommand(text);

            if (!!parsed) {
                const { namespace, subcommand } = parsed;

                if (namespace === "live" && subcommand === "share") {
                    // Temporary bypass for "/live share" till we move
                    // all of this to the common command handlers
                    return vscode.commands.executeCommand(SelfCommands.LIVE_SHARE_SLASH, {
                        provider: this.currentProvider
                    });
                } else {
                    return this.dispatchCommand(parsed);
                }
            }
        }

        if (text === "/clear") {
            return vscode.commands.executeCommand(SelfCommands.CLEAR_MESSAGES, {
                channelId: this.currentChannelId,
                provider: this.currentProvider
            });
        }

        if (text === "/invite") {
            return vscode.commands.executeCommand(SelfCommands.INVITE_LIVE_SHARE_CONTACT, {
                channelId: this.currentChannelId,
                provider: this.currentProvider
            });
        }

        if (this.isValidReverseCommand(text)) {
            return this.sendTextMessage(text);
        }

        // TODO(arjun): if not valid, then we need to parse and make a chat.command
        // API call, instead of sending it as a simple text message.
        // Docs: https://github.com/ErikKalkoken/slackApiDoc/blob/master/chat.command.md
        return this.sendTextMessage(text);
    };

    handleInternal = (message: any) => {
        const { text } = message;

        if (text === "is_ready") {
            this.isUIReady = true;
            return this.pendingMessage ? this.sendToUI(this.pendingMessage) : null;
        }

        if (text === "is_focused") {
            this.onUIFocus(this.currentProvider);
        }

        if (text === "fetch_replies") {
            const { parentTimestamp } = message;
            vscode.commands.executeCommand(SelfCommands.FETCH_REPLIES, {
                parentTimestamp,
                provider: this.currentProvider
            });
        }

        if (text === "is_typing") {
            vscode.commands.executeCommand(SelfCommands.SEND_TYPING, {
                channelId: this.currentChannelId,
                provider: this.currentProvider
            });
        }
    };

    sendTextMessage = (text: string) => {
        return vscode.commands.executeCommand(SelfCommands.SEND_MESSAGE, {
            text,
            provider: this.currentProvider
        });
    };

    sendThreadReply = (payload: any) => {
        const { text, parentTimestamp } = payload;
        return vscode.commands.executeCommand(SelfCommands.SEND_THREAD_REPLY, {
            text,
            parentTimestamp,
            provider: this.currentProvider
        });
    };

    sendToExtension = (message: ExtensionMessage) => {
        const { type, text } = message;
        Logger.log(`Sending to extension (${type}) ${text}`);

        switch (type) {
            case "internal":
                return this.handleInternal(message);
            case "link":
                return this.dispatchCommand({ namespace: "open", subcommand: text });
            case "command":
                return this.handleCommand(text);
            case "text":
                return text ? this.sendTextMessage(text) : null;
            case "thread_reply":
                return this.sendThreadReply(text);
        }
    };

    handleReverseCommands = (uiMessage: UIMessage) => {
        // TODO: Reverse commands are disabled, until we fix this

        // Reverse commands are slash commands fired by other Slack users
        // For example, `/live request` requests someone to host a session
        const { currentUser, messages } = uiMessage;
        let handledMessages: ChannelMessages = {};

        Object.keys(messages).forEach(ts => {
            // Any of these messages might be reverse commands
            const { text, userId } = messages[ts];
            const notCurrentUser = currentUser.id !== userId;
            // let textHTML = messages[ts].textHTML;

            if (this.isValidReverseCommand(text) && notCurrentUser) {
                if (text === "/live request") {
                    const confirmation = `<a href="#" onclick="sendCommand('/live share'); return false;">Accept</a>`;
                    // textHTML = `${str.LIVE_REQUEST_MESSAGE} ${confirmation}`;
                }
            }

            handledMessages[ts] = {
                ...messages[ts]
                // textHTML
            };
        });

        return {
            ...uiMessage,
            messages: handledMessages
        };
    };

    updateCurrentState = (provider: string, channelId: string, source: EventSource) => {
        this.currentProvider = provider;
        this.currentChannelId = channelId;
        this.currentSource = source;
    };

    sendToUI = (uiMessage: UIMessage) => {
        const { provider: incomingProvider, channel: incomingChannel } = uiMessage;

        if (!!this.ui && this.ui.isVisible()) {
            // The webview is visible => we check if the incoming message is valid.
            const isSameProvider = !this.currentProvider || incomingProvider === this.currentProvider;
            const isSameChannel = !this.currentChannelId || incomingChannel.id === this.currentChannelId;

            if (!isSameChannel || !isSameProvider) {
                return; // Ignore this message.
            }
        }

        if (!this.isUIReady) {
            this.pendingMessage = uiMessage;
        } else {
            const { messages } = uiMessage;
            const size = Object.keys(messages).length;
            Logger.log(`Sending to webview: ${size} messages`);

            // Handle markdown
            const mdMessages = markdownTransform(uiMessage);

            // Handle reverse slash commands
            // Since this overwrites the textHTML field, it should happen
            // after the markdown
            const message = this.handleReverseCommands(mdMessages);

            // Send to UI after markdown
            if (this.ui) {
                this.ui.update(message);
                this.pendingMessage = undefined;
            }
        }
    };
}

export default ViewController;


================================================
FILE: src/controller/markdown-it-slack.d.ts
================================================
// foo.d.ts
declare module "markdown-it-slack";


================================================
FILE: src/controller/markdowner.ts
================================================
import * as EmojiConvertor from "emoji-js";

export const parseUsernames = (uiMessage: UIMessage): UIMessage => {
    // Find and replace names like <@UBCQ8LF28>
    // TODO: fix this for channel names, which show up as <#C8A187ZRQ|general>
    const { messages, users } = uiMessage;
    let newMessages: ChannelMessages = {};

    Object.keys(messages).map(ts => {
        const message = messages[ts];
        let { text } = message;
        const matched = text.match(/<@([A-Z0-9]+)>/);

        if (matched && matched.length > 0) {
            const userId = matched[1];
            if (userId in users) {
                const { name } = users[userId];
                text = text.replace(matched[0], `@${name}`);
            }
        }

        newMessages[ts] = {
            ...message,
            text
        };
    });
    return {
        ...uiMessage,
        messages: newMessages
    };
};

export const emojify = (messages: ChannelMessages): ChannelMessages => {
    // Even though we are using markdown-it-slack, it does not support
    // emoji skin tones. If that changes, we can remove this method.
    const emoji = new EmojiConvertor();
    emoji.allow_native = true;

    // We have added node_modules/emoji-datasource to vscodeignore since we use
    // allow_native. If this changes, we might have to use emoji sheets (through CDN?)
    emoji.replace_mode = "unified";
    let emojifiedMessages: ChannelMessages = {};

    Object.keys(messages).forEach(key => {
        const message = messages[key];
        const { text, reactions } = message;

        emojifiedMessages[key] = {
            ...message,
            reactions: reactions
            ? reactions.map(reaction => ({
                ...reaction,
                name: emoji.replace_colons(reaction.name)
            }))
            : [],
            text: emoji.replace_colons(text ? text : "")
        };
    });

    return emojifiedMessages;
};

const parseSimpleLinks = (messages: ChannelMessages): ChannelMessages => {
    let parsed: ChannelMessages = {};

    Object.keys(messages).forEach(key => {
        const { content, text } = messages[key];
        let newContent: MessageContent | undefined = undefined;
        const URL_REGEX = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=;\^]*)/;
        const re = new RegExp(`${URL_REGEX.source}`, "g");

        if (!!content) {
            newContent = {
                ...content,
                text: content.text
                ? content.text.replace(re, function(a, b, c, d, e) {
                    return `[${a}](${a})`;
                })
                : "",
                footer: content.footer
                ? content.footer.replace(re, function(a, b, c, d, e) {
                    return `[${a}](${a})`;
                })
                : ""
            };
        }

        parsed[key] = {
            ...messages[key],
            text: text
            ? text.replace(re, function(a, b, c, d, e) {
                return `[${a}](${a})`;
            })
            : "",
            content: newContent
        };
    });
    return parsed;
}

export const parseSlackLinks = (messages: ChannelMessages): ChannelMessages => {
    // Looks for <url|title> pattern, and replaces them with normal markdown
    // The |pattern can be optional
    let parsed: ChannelMessages = {};

    Object.keys(messages).forEach(key => {
        const { content, text } = messages[key];
        let newContent: MessageContent | undefined = undefined;
        const URL_REGEX = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=;\^]*)/;
        const SLACK_MODIFIER = /(|.[^><]+)/;
        const re = new RegExp(`<(${URL_REGEX.source})(${SLACK_MODIFIER.source})>`, "g");

        if (!!content) {
            newContent = {
                ...content,
                text: content.text
                ? content.text.replace(re, function(a, b, c, d, e) {
                    return e ? `[${e.substr(1)}](${b})` : `[${b}](${b})`;
                })
                : "",
                footer: content.footer
                ? content.footer.replace(re, function(a, b, c, d, e) {
                    return e ? `[${e.substr(1)}](${b})` : `[${b}](${b})`;
                })
                : ""
            };
        }

        parsed[key] = {
            ...messages[key],
            text: text
            ? text.replace(re, function(a, b, c, d, e) {
                return e ? `[${e.substr(1)}](${b})` : `[${b}](${b})`;
            })
            : "",
            content: newContent
        };
    });
    return parsed;
};

const transformChain = (uiMessage: UIMessage): UIMessage => {
    const { messages } = parseUsernames(uiMessage);
    const linkParser = uiMessage.provider === "vslsSpaces" ? parseSimpleLinks : parseSlackLinks;
    return {
        ...uiMessage,
        messages: linkParser(emojify(messages))
    };
};

export default transformChain;


================================================
FILE: src/discord/index.ts
================================================
import * as vscode from "vscode";
import * as Discord from "discord.js";
import * as rp from "request-promise-native";
import { SelfCommands } from "../constants";
import { toTitleCase } from "../utils";
import Logger from "../logger";

const HISTORY_LIMIT = 50;
const MEMBER_LIMIT = 500;

const getPresence = (presence: Discord.Presence): UserPresence => {
  const { status } = presence;

  switch (status) {
    case "online":
      return UserPresence.available;
    case "dnd":
      return UserPresence.doNotDisturb;
    case "idle":
      return UserPresence.idle;
    case "offline":
      return UserPresence.offline;
  }
};

const getMessageContent = (
  raw: Discord.Message
): MessageContent | undefined => {
  const { embeds } = raw;
  if (!!embeds && embeds.length > 0) {
    const firstEmbed = embeds[0];
    return {
      author: ``,
      pretext: ``,
      title: firstEmbed.title,
      titleLink: firstEmbed.url,
      text: firstEmbed.description,
      footer: ``
    };
  }
};

const getMessage = (raw: Discord.Message): Message => {
  const { author, createdTimestamp, content, reactions, editedTimestamp } = raw;
  const timestamp = (createdTimestamp / 1000).toString();
  let attachment = undefined;
  const attachments = raw.attachments.array();

  if (attachments.length > 0) {
    // This only shows the first attachment
    const selected = attachments[0];
    attachment = {
      name: selected.filename,
      permalink: selected.url
    };
  }

  return {
    timestamp,
    userId: author.id,
    text: content,
    isEdited: !!editedTimestamp,
    content: getMessageContent(raw),
    replies: {},
    attachment,
    reactions: reactions.map(rxn => ({
      name: rxn.emoji.name,
      count: rxn.count,
      userIds: rxn.users.map(user => user.id)
    }))
  };
};

const getUser = (raw: Discord.User): User => {
  const { id: userId, username, avatar, presence } = raw;
  return {
    id: userId,
    name: username,
    fullName: username,
    imageUrl: getImageUrl(userId, avatar),
    smallImageUrl: getSmallImageUrl(userId, avatar),
    presence: getPresence(presence)
  };
};

const DEFAULT_AVATARS = [
  "https://discordapp.com/assets/dd4dbc0016779df1378e7812eabaa04d.png",
  "https://discordapp.com/assets/0e291f67c9274a1abdddeb3fd919cbaa.png",
  "https://discordapp.com/assets/6debd47ed13483642cf09e832ed0bc1b.png",
  "https://discordapp.com/assets/322c936a8c8be1b803cd94861bdfa868.png",
  "https://discordapp.com/assets/1cbd08c76f8af6dddce02c5138971129.png"
];

const getAvatarUrl = (userId: string, avatar: string, size: number) => {
  if (!avatar) {
    return DEFAULT_AVATARS[Math.floor(Math.random() * DEFAULT_AVATARS.length)];
  } else {
    // size can be any power of two between 16 and 2048
    return `https://cdn.discordapp.com/avatars/${userId}/${avatar}.png?size=${size}`;
  }
};

const getImageUrl = (userId: string, avatar: string) =>
  getAvatarUrl(userId, avatar, 128);

const getSmallImageUrl = (userId: string, avatar: string) =>
  getAvatarUrl(userId, avatar, 32);

export class DiscordChatProvider implements IChatProvider {
  client: Discord.Client;
  mutedChannels: Set<string> = new Set([]);
  imChannels: Channel[] = [];

  constructor(private token: string, private manager: IManager) {
    this.client = new Discord.Client();
  }

  async validateToken(): Promise<CurrentUser | undefined> {
    const response = await rp({
      baseUrl: `https://discordapp.com/api/v6`,
      uri: `/users/@me`,
      json: true,
      headers: {
        Authorization: `${this.token}`
      }
    });
    const { id, username: name } = response;
    return {
      id,
      name,
      teams: [],
      currentTeamId: undefined,
      provider: Providers.discord
    };
  }

  connect(): Promise<CurrentUser> {
    return new Promise(resolve => {
      this.client.on("ready", () => {
        const { id, username: name } = this.client.user;
        const teams = this.client.guilds.array().map(guild => ({
          id: guild.id,
          name: guild.name
        }));
        const currentUser: CurrentUser = {
          id,
          name,
          teams,
          currentTeamId: undefined,
          provider: Providers.discord
        };
        resolve(currentUser);
      });

      if (process.env.IS_DEBUG === "true") {
        // Debug logs for local testing
        this.client.on("debug", info =>
          console.log("Discord client log:", info)
        );
      }

      this.client.on("presenceUpdate", (_, newMember: Discord.GuildMember) => {
        const { id: userId, presence } = newMember;
        vscode.commands.executeCommand(SelfCommands.UPDATE_PRESENCE_STATUSES, {
          userId,
          presence: getPresence(presence),
          provider: "discord"
        });
      });

      this.client.on("message", msg => {
        this.handleIncomingMessage(msg);
        this.handleIncomingLinks(msg);
      });

      this.client.on("messageUpdate", (_, msg: Discord.Message) => {
        this.handleIncomingMessage(msg);
      });

      this.client.on("error", error => {
        Logger.log(`[ERROR] Discord: ${error.message}`);
      });

      this.client.login(this.token);
    });
  }

  handleIncomingMessage(msg: Discord.Message) {
    // If message has guild, we check for current guild
    // Else, message is from a DM or group DM
    const currentGuild = this.getCurrentGuild();
    const { guild } = msg;

    if (!currentGuild) {
      return;
    }

    if (!guild || guild.id === currentGuild.id) {
      let newMessages: ChannelMessages = {};
      const channelId = msg.channel.id;
      const parsed = getMessage(msg);
      const { timestamp } = parsed;
      newMessages[timestamp] = parsed;
      vscode.commands.executeCommand(SelfCommands.UPDATE_MESSAGES, {
        channelId,
        messages: newMessages,
        provider: "discord"
      });
    }
  }

  handleIncomingLinks(msg: Discord.Message) {
    // For vsls invitations
    const currentGuild = this.getCurrentGuild();
    const { guild } = msg;

    if (!currentGuild) {
      return;
    }

    if (!guild || guild.id === currentGuild.id) {
      const parsed = getMessage(msg);
      let uri: vscode.Uri | undefined;
      try {
        const { text } = parsed;
        if (text.startsWith("http")) {
          uri = vscode.Uri.parse(parsed.text);
          vscode.commands.executeCommand(SelfCommands.HANDLE_INCOMING_LINKS, {
            provider: "discord",
            senderId: parsed.userId,
            uri
          });
        }
      } catch (e) {}
    }
  }

  isConnected(): boolean {
    return !!this.client && !!this.client.readyTimestamp;
  }

  getUserPreferences(): Promise<UserPreferences> {
    const mutedChannels = Array.from(this.mutedChannels);
    return Promise.resolve({ mutedChannels });
  }

  getCurrentGuild(): Discord.Guild | undefined {
    const currentUserInfo = this.manager.store.getCurrentUser("discord");

    if (!!currentUserInfo) {
      const { currentTeamId } = currentUserInfo;
      return this.client.guilds.find(guild => guild.id === currentTeamId);
    }
  }

  async fetchUsers(): Promise<Users> {
    const guild = this.getCurrentGuild();
    const readyTimestamp = (this.client.readyTimestamp / 1000.0).toString();
    let users: Users = {};

    // We first build users from IM channels, and then from the guild members
    this.imChannels = this.client.channels
      .filter(channel => channel.type === "dm")
      .map(channel => {
        const dmChannel = <Discord.DMChannel>channel;
        const { id, recipient } = dmChannel;
        const user = getUser(recipient);
        users[user.id] = user;
        return {
          id,
          name: recipient.username,
          type: ChannelType.im,
          readTimestamp: readyTimestamp,
          unreadCount: 0
        };
      });

    if (!!guild) {
      // Getting guild members requires knowing the guild
      const response = await guild.fetchMembers("", MEMBER_LIMIT);
      response.members.forEach(member => {
        const { user: discordUser, roles } = member;
        const hoistedRole = roles.find(role => role.hoist);
        let roleName = undefined;

        if (!!hoistedRole) {
          roleName = toTitleCase(hoistedRole.name);
        }

        const user = getUser(discordUser);
        users[user.id] = { ...user, roleName };
      });
    }

    return users;
  }

  async fetchUserInfo(userId: string): Promise<User> {
    const discordUser = await this.client.fetchUser(userId);
    return getUser(discordUser);
  }

  fetchChannels(users: Users): Promise<Channel[]> {
    // This fetches channels of the current guild, and (group) DMs.
    // For unreads, we are not retrieving historical unreads, not clear if API supports that.
    const readyTimestamp = (this.client.readyTimestamp / 1000.0).toString();
    const guild = this.getCurrentGuild();
    let categories: { [id: string]: string } = {};

    if (!!guild) {
      guild.channels
        .filter(channel => channel.type === "category")
        .forEach(channel => {
          const { id: channelId, name, muted } = channel;
          categories[channelId] = name;

          if (muted) {
            this.mutedChannels.add(channelId);
          }
        });

      const currentUserInfo = this.manager.store.getCurrentUser("discord");
      const guildChannels: Channel[] = guild.channels
        .filter(channel => channel.type !== "category")
        .filter(channel => {
          if (!!currentUserInfo) {
            const userId = currentUserInfo.id;
            const permissions = channel.permissionsFor(userId);
            const permissionFlag = Discord.Permissions.FLAGS.VIEW_CHANNEL;

            if (!!permissions && permissionFlag) {
              return permissions.has(permissionFlag);
            }
          }

          return false;
        })
        .map(channel => {
          const { name, id, parentID } = channel;
          return {
            id,
            name,
            categoryName: categories[parentID],
            type: ChannelType.channel,
            readTimestamp: readyTimestamp,
            unreadCount: 0
          };
        });

      const groupChannels = this.client.channels
        .filter(channel => channel.type === "group")
        .map(channel => {
          const groupChannel = <Discord.GroupDMChannel>channel;
          const { id, recipients } = groupChannel;
          return {
            id,
            name: recipients.map(recipient => recipient.username).join(", "),
            type: ChannelType.group,
            readTimestamp: readyTimestamp,
            unreadCount: 0
          };
        });

      return Promise.resolve([
        ...guildChannels,
        ...this.imChannels,
        ...groupChannels
      ]);
    }

    return Promise.resolve([]);
  }

  async loadChannelHistory(channelId: string): Promise<ChannelMessages> {
    const channel: any = this.client.channels.find(
      channel => channel.id === channelId
    );

    // channel.fetchMessages will break for voice channels
    const messages: Discord.Message[] = await channel.fetchMessages({
      limit: HISTORY_LIMIT
    });

    let result: ChannelMessages = {};
    messages.forEach(message => {
      const parsed = getMessage(message);
      const { timestamp } = parsed;
      result[timestamp] = parsed;
    });
    return result;
  }

  sendMessage(
    text: string,
    currentUserId: string,
    channelId: string
  ): Promise<void> {
    const channel: any = this.client.channels.find(
      channel => channel.id === channelId
    );
    return channel.send(text);
  }

  fetchChannelInfo(channel: Channel): Promise<Channel> {
    return Promise.resolve(channel);
  }

  subscribePresence(users: Users): void {}

  sendThreadReply() {
    return Promise.resolve();
  }

  async updateSelfPresence(
    presence: UserPresence
  ): Promise<UserPresence | undefined> {
    let status: Discord.PresenceStatus;

    switch (presence) {
      case UserPresence.available:
        status = "online";
        break;
      case UserPresence.doNotDisturb:
        status = "dnd";
        break;
      case UserPresence.idle:
        status = "idle";
        break;
      case UserPresence.invisible:
        status = "invisible";
        break;
      default:
        throw new Error("status not supported by discord");
    }

    const response = await this.client.user.setPresence({ status });
    // response.presence.status is always `invisible`
    // Hence we return the original presence input as success
    return presence;
  }

  destroy(): Promise<void> {
    if (!!this.client) {
      return this.client.destroy();
    }

    return Promise.resolve();
  }

  async markChannel(channel: Channel, ts: string): Promise<Channel> {
    // Discord does not have a concept of timestamp, it will acknowledge everything
    // return Promise.resolve(channel);
    const { id: channelId } = channel;
    const discordChannel: any = this.client.channels.find(
      channel => channel.id === channelId
    );
    await discordChannel.acknowledge();
    return { ...channel, readTimestamp: ts };
  }

  fetchThreadReplies(channelId: string, ts: string): Promise<any> {
    // Never called. Discord has no threads.
    return Promise.resolve();
  }

  createIMChannel(user: User): Promise<Channel | undefined> {
    // This is required to share vsls links with users that
    // do not have corresponding DM channels
    return Promise.resolve(undefined);
  }

  async sendTyping(currentUserId: string, channelId: string) { }
}


================================================
FILE: src/extension.ts
================================================
import * as vscode from "vscode";
import * as vsls from "vsls";
import ViewController from "./controller";
import Manager from "./manager";
import Logger from "./logger";
import { Store } from "./store";
import * as str from "./strings";
import {
    SelfCommands,
    SLACK_OAUTH,
    DISCORD_OAUTH,
    CONFIG_ROOT,
    CONFIG_AUTO_LAUNCH,
    TRAVIS_SCHEME,
    VSLS_SPACES_EXTENSION_ID
} from "./constants";
import travis from "./bots/travis";
import { ExtensionUriHandler } from "./uriHandler";
import * as utils from "./utils";
import { askForAuth } from "./onboarding";
import { ConfigHelper } from "./config";
import TelemetryReporter from "./telemetry";
import IssueReporter from "./issues";

let store: Store;
let manager: Manager;
let controller: ViewController;
let telemetry: TelemetryReporter;
let typingTimers: { [key: string]: NodeJS.Timer | undefined } = {};

export function activate(context: vscode.ExtensionContext) {
    Logger.log("Activating vscode-chat");
    store = new Store(context);
    manager = new Manager(store);
    telemetry = new TelemetryReporter(manager);
    // telemetry.record(
    //     EventType.activationStarted,
    //     undefined,
    //     undefined,
    //     undefined
    // );

    controller = new ViewController(
        context,
        (provider, source) => onUIDispose(provider, source),
        provider => {
            if (provider) {
                const lastChannelId = manager.store.getLastChannelId(provider);

                if (lastChannelId) {
                    return manager.loadChannelHistory(provider, lastChannelId);
                }
            }
        },
        provider => (!!provider ? manager.updateReadMarker(provider) : undefined)
    );

    const setupFreshInstall = () => {
        const installationId = manager.store.generateInstallationId();
        telemetry.setUniqueId(installationId);
        telemetry.record(EventType.extensionInstalled, undefined, undefined, undefined);
    };

    const handleNoToken = (canPromptForAuth: boolean) => {
        const hasVsls = utils.hasVslsExtension() || utils.hasVslsExtensionPack();

        if (canPromptForAuth && !hasVsls) {
            askForAuth();
        }

        throw new Error(str.TOKEN_NOT_FOUND);
    };

    const initializeToken = async (canPromptForAuth: boolean, newInitialState: InitialState | undefined) => {
        await manager.initializeToken(newInitialState);

        if (!manager.isTokenInitialized) {
            setTimeout(() => handleNoToken(canPromptForAuth), 5 * 1000);
        }
    };

    const setup = async (canPromptForAuth: boolean, newInitialState: InitialState | undefined): Promise<any> => {
        await store.runStateMigrations();
        const isFreshInstall = !manager.store.installationId;

        if (isFreshInstall) {
            setupFreshInstall();
        }

        if (!manager.isTokenInitialized || !!newInitialState) {
            // We force initialization if we are provided a newInitialState
            await initializeToken(canPromptForAuth, newInitialState);
        }

        await manager.initializeProviders();

        if (manager.isProviderEnabled("discord")) {
            if (!manager.getCurrentTeamIdFor("discord")) {
                await askForWorkspace("discord");
            }
        }

        // TODO: In discord, user preferences are available after channels are fetched
        manager.updateUserPrefsForAll(); // async update
        await manager.initializeStateForAll();
        manager.subscribePresenceForAll();
    };

    const sendMessage = (providerName: string, text: string, parentTimestamp: string | undefined) => {
        const lastChannelId = manager.store.getLastChannelId(providerName);
        telemetry.record(EventType.messageSent, undefined, lastChannelId, providerName);
        manager.updateReadMarker(providerName);

        if (!!lastChannelId) {
            // lastChannelId should always exist since this will only be
            // called after loading the webview (which requires lastChannelId)
            return manager.sendMessage(providerName, text, lastChannelId, parentTimestamp);
        }
    };

    const askForChannel = async (
        providerName: string | undefined
    ): Promise<{ channel: Channel; providerName: string } | undefined> => {
        // This can be called with an undefined providerName, in which
        // case we show channels from all available providers.
        let channelList = manager.getChannelLabels(providerName).sort((a, b) => b.unread - a.unread);

        const quickpickItems: vscode.QuickPickItem[] = channelList.map(channelLabel => {
            const description = `${channelLabel.providerName} · ${channelLabel.teamName}`;
            return {
                label: channelLabel.label,
                detail: channelLabel.channel.categoryName,
                description
            };
        });
        const finalList = [...quickpickItems, { label: str.RELOAD_CHANNELS }];
        const selected = await vscode.window.showQuickPick(finalList, {
            placeHolder: str.CHANGE_CHANNEL_TITLE,
            matchOnDetail: true,
            matchOnDescription: true
        });

        if (!!selected) {
            if (selected.label === str.RELOAD_CHANNELS) {
                let currentProvider = providerName;

                if (!currentProvider) {
                    const providers = manager.store.getCurrentUserForAll().map(userInfo => userInfo.provider);
                    currentProvider = await askForProvider(providers);
                }

                if (!!currentProvider) {
                    await manager.fetchUsers(currentProvider);
                    await manager.fetchChannels(currentProvider);
                    return askForChannel(providerName);
                }
            }

            const selectedChannelLabel = channelList.find(
                x => x.label === selected.label && x.channel.categoryName === selected.detail
            );

            if (!!selectedChannelLabel) {
                const { channel, providerName } = selectedChannelLabel;
                return { channel, providerName: providerName.toLowerCase() };
            }
        }
    };

    const openChatWebview = async (chatArgs?: ChatArgs) => {
        let provider = !!chatArgs ? chatArgs.providerName : undefined;
        let channelId = !!chatArgs ? chatArgs.channelId : undefined;
        const source = !!chatArgs ? chatArgs.source : EventSource.command;

        if (!chatArgs) {
            const selected = await askForChannel(undefined);

            if (!!selected) {
                provider = selected.providerName;
                channelId = selected.channel.id;
            }
        }

        if (!!provider && !!channelId) {
            controller.updateCurrentState(provider, channelId, source);
            controller.loadUi();

            await setup(true, undefined);
            await manager.updateWebviewForProvider(provider, channelId);
            telemetry.record(EventType.viewOpened, source, channelId, provider);
            manager.loadChannelHistory(provider, channelId);
        }
    };

    const onUIDispose = (provider: string | undefined, openSource: EventSource | undefined) => {
    };

    const askForWorkspace = async (provider: string): Promise<Team | undefined> => {
        const currentUserInfo = manager.store.getCurrentUser(provider);

        if (!!currentUserInfo) {
            const { teams } = currentUserInfo;
            const labels = teams.map(team => team.name);

            const selected = await vscode.window.showQuickPick([...labels], {
                placeHolder: str.CHANGE_WORKSPACE_TITLE
            });

            if (!!selected) {
                return teams.find(team => team.name === selected);
            }
        }
    };

    const changeWorkspace = async (providerAndTeam?: any) => {
        let provider: string | undefined, team;

        if (!providerAndTeam) {
            const currentUsers = manager.store.getCurrentUserForAll();
            const withMultipleTeams = currentUsers.filter(userInfo => userInfo.teams.length > 1);
            provider = await askForProvider(withMultipleTeams.map(userInfo => userInfo.provider));

            if (!provider) {
                return;
            }

            const userInfo = withMultipleTeams.find(userInfo => userInfo.provider === provider);

            if (!!userInfo) {
                const teamNames = userInfo.teams.map(team => team.name);
                const selection = await vscode.window.showQuickPick(teamNames, {
                    placeHolder: str.CHANGE_PROVIDER_TITLE
                });

                if (selection) {
                    team = userInfo.teams.find(team => team.name === selection);
                }
            }
        } else {
            provider = providerAndTeam.provider;
            team = providerAndTeam.team;
        }

        if (provider && team) {
            const isDifferentTeam = team.id !== manager.getCurrentTeamIdFor(provider);

            if (isDifferentTeam) {
                manager.updateCurrentWorkspace(provider, team);
                await manager.clearOldWorkspace(provider);
                await setup(false, { provider, teamId: team.id });
            }
        }
    };

    const changeChannel = async (args?: ChatArgs) => {
        const provider = args ? args.providerName : undefined;
        telemetry.record(EventType.channelChanged, !!args ? args.source : EventSource.command, undefined, provider);

        const selected = await askForChannel(provider);

        if (!!selected) {
            let chatArgs: any = { ...args };
            chatArgs.channelId = selected.channel.id;
            chatArgs.providerName = selected.providerName;
            return openChatWebview(chatArgs);
        }
    };

    const shareVslsLink = async (chatArgs: ChatArgs) => {
        // This method can assume chatArgs to have one of channel and user
        const { providerName } = chatArgs;
        const liveshare = await vsls.getApi();

        if (!!liveshare) {
            const vslsUri = await liveshare.share({
                suppressNotification: true
            });
            let channelId = chatArgs.channelId;
            const user = chatArgs.user;

            if (!channelId && user) {
                const newChannel = await manager.createIMChannel(chatArgs.providerName, user);

                if (!!newChannel) {
                    channelId = newChannel.id;
                }
            }

            telemetry.record(EventType.vslsShared, EventSource.activity, channelId, providerName);

            if (vslsUri && channelId) {
                manager.sendMessage(providerName, vslsUri.toString(), channelId, undefined);
            }
        }
    };

    const startOAuth = (args?: any) => {
        const hasArgs = !!args && !!args.source;
        const provider = "slack"; // Only Slack OAuth is supported
        const urls = {
            slack: SLACK_OAUTH,
            discord: DISCORD_OAUTH
        };
        telemetry.record(EventType.authStarted, hasArgs ? args.source : EventSource.command, undefined, provider);
        return utils.openUrl(urls[provider]);
    };

    const reset = async () => {
        // Reset clears all state from local storage (except for vsls chat
        // related state, since that does not get affected via call paths to reset)
        manager.clearAll();
        manager.updateAllUI();
        await setup(false, undefined);
    };

    const signout = async () => {
        await manager.signout();
    };

    const updateSelfPresence = async (provider: string, presence: UserPresence) => {
        const isSlack = provider === "slack";
        let durationInMinutes = 0;

        if (presence === UserPresence.doNotDisturb && isSlack) {
            // Ask for duration for dnd.snooze for slack implementation
            const options: { [label: string]: number } = {
                "20 minutes": 20,
                "1 hour": 60,
                "2 hours": 120,
                "4 hours": 240,
                "8 hours": 480,
                "24 hours": 1440
            };
            const selected = await vscode.window.showQuickPick(Object.keys(options), {
                placeHolder: str.SELECT_DND_DURATION
            });
            durationInMinutes = !!selected ? options[selected] : 0;
        }

        manager.updateSelfPresence(provider, presence, durationInMinutes);
    };

    const askForSelfPresence = async () => {
        // Called when user triggers a change for self presence
        // using manual command.
        const enabledProviders = manager.getEnabledProviders();
        const providerNames = enabledProviders.map(element => element.provider);
        const provider = providerNames.find(provider => provider !== "vsls");

        if (!!provider) {
            const isSlack = provider === "slack";
            const currentPresence = manager.getCurrentUserPresence(provider);
            const presenceChoices = [UserPresence.available, UserPresence.doNotDisturb, UserPresence.invisible];

            if (!isSlack) {
                // Slack does not have the idle option
                presenceChoices.push(UserPresence.idle);
            }

            const items: vscode.QuickPickItem[] = presenceChoices.map(choice => {
                const isCurrent = currentPresence === choice;
                return {
                    label: utils.camelCaseToTitle(choice),
                    description: isCurrent ? "current" : ""
                };
            });
            const status = await vscode.window.showQuickPick(items, {
                placeHolder: str.SELECT_SELF_PRESENCE
            });

            if (!!status) {
                const presence = utils.titleCaseToCamel(status.label) as UserPresence;
                updateSelfPresence(provider, presence);
            }
        }
    };

    const fetchReplies = (provider: string, parentTimestamp: string) => {
        manager.fetchThreadReplies(provider, parentTimestamp);
    };

    const resetConfiguration = (event: vscode.ConfigurationChangeEvent) => {
        const affectsExtension = event.affectsConfiguration(CONFIG_ROOT);

        if (affectsExtension) {
            // We can have a tighter check here to prevent losing slack/discord setup
            // whenever the config changes.
            const needsReset = !event.affectsConfiguration(CONFIG_AUTO_LAUNCH);

            if (needsReset) {
                reset();
            }
        }
    };

    const setVslsContext = () => {
        const isEnabled = utils.hasVslsExtension();
        utils.setVsContext("chat:vslsEnabled", isEnabled);
    };

    const askForProvider = async (enabledProviders: string[]) => {
        // VSLS providers are no longer supported. The user can still have these in their store.
        // Remove these from the list.
        const values = (enabledProviders.map(name => utils.toTitleCase(name))).filter(p => p !== 'Vsls');
        const selection = await vscode.window.showQuickPick(values, {
            placeHolder: str.CHANGE_PROVIDER_TITLE
        });
        return !!selection ? selection.toLowerCase() : undefined;
    };

    const configureToken = async () => {
        const provider = await askForProvider(["slack", "discord"]);
        telemetry.record(EventType.tokenConfigured, EventSource.command, undefined, provider);

        if (!!provider) {
            const inputToken = await vscode.window.showInputBox({
                placeHolder: str.TOKEN_PLACEHOLDER,
                password: true
            });

            if (!!inputToken) {
                const sanitisedToken = utils.sanitiseTokenString(inputToken);

                try {
                    const tokenUser = await manager.validateToken(provider, sanitisedToken);

                    if (!!tokenUser) {
                        const teamId = provider === "slack" ? tokenUser.currentTeamId : undefined;
                        return ConfigHelper.setToken(sanitisedToken, provider, teamId);
                    }
                } catch (error) {
                    const actionItems = [str.REPORT_ISSUE];
                    const messageResult = await vscode.window.showErrorMessage(
                        str.INVALID_TOKEN(utils.toTitleCase(provider)),
                        ...actionItems
                    );

                    if (!!messageResult && messageResult === str.REPORT_ISSUE) {
                        const issue = `[${provider}] Invalid token`;
                        IssueReporter.openNewIssue(issue, "");
                    }

                    return;
                }
            }
        }
    };

    const getContactFromItem = async (item: any) => {
        let contact: vsls.Contact | undefined;

        if (!!item.space) {
            // This is a space member, we need to convert to an LS contact
            const { email } = item;
            const api = (await vsls.getApi())!;
            const { contacts } = await api.getContacts([email]);
            contact = contacts[email];
        } else {
            contact = item.contactModel.contact;
        }

        return contact;
    };

    const openVslsSpaceChat = async (spaceName: string) => {
        const api = utils.getExtension(VSLS_SPACES_EXTENSION_ID)!.exports;
        const { name, email } = api.getUserInfo();
        await manager.store.updateCurrentUser("vslsSpaces", {
            id: email,
            name,
            teams: [],
            currentTeamId: undefined,
            provider: Providers.vslsSpaces
        });
        return openChatWebview({
            providerName: "vslsSpaces",
            channelId: spaceName,
            source: EventSource.command
        });
    };

    // Setup real-time messenger and updated local state
    setup(true, undefined);

    // Setup context for conditional views
    setVslsContext();

    const uriHandler = new ExtensionUriHandler();
    context.subscriptions.push(
        vscode.commands.registerCommand(SelfCommands.OPEN_WEBVIEW, openChatWebview),
        vscode.commands.registerCommand(SelfCommands.CHANGE_WORKSPACE, changeWorkspace),
        vscode.commands.registerCommand(SelfCommands.CHANGE_CHANNEL, changeChannel),
        vscode.commands.registerCommand(SelfCommands.SIGN_IN, startOAuth),
        vscode.commands.registerCommand(SelfCommands.SIGN_OUT, signout),
        vscode.commands.registerCommand(SelfCommands.RESET_STORE, reset),
        vscode.commands.registerCommand(SelfCommands.SETUP_NEW_PROVIDER, ({ newInitialState }) =>
            setup(false, newInitialState)
        ),
        vscode.commands.registerCommand(SelfCommands.CONFIGURE_TOKEN, configureToken),
        vscode.commands.registerCommand(SelfCommands.SEND_MESSAGE, ({ text, provider }) =>
            sendMessage(provider, text, undefined)
        ),
        vscode.commands.registerCommand(SelfCommands.SEND_THREAD_REPLY, ({ text, parentTimestamp, provider }) =>
            sendMessage(provider, text, parentTimestamp)
        ),
        vscode.commands.registerCommand(SelfCommands.LIVE_SHARE_FROM_MENU, (item: ChatTreeNode) => {
            return shareVslsLink({
                channelId: item.channel ? item.channel.id : undefined,
                user: item.user,
                providerName: item.providerName,
                source: EventSource.activity
            });
        }),
        vscode.commands.registerCommand(SelfCommands.LIVE_SHARE_SLASH, ({ provider }) => {
            const channelId = manager.store.getLastChannelId(provider);
            shareVslsLink({
                channelId,
                user: undefined,
                providerName: provider,
                source: EventSource.slash
            });
        }),
        vscode.commands.registerCommand(
            SelfCommands.LIVE_SHARE_SESSION_CHANGED,
            async ({ isSessionActive, currentUser }) => {
                if (!currentUser) {
                    // If the currentUser is undefined, don't launch the window
                    return;
                }

                const enabledProviders = manager.getEnabledProviders().map(e => e.provider);

                const eventType = isSessionActive ? EventType.vslsStarted : EventType.vslsEnded;
                telemetry.record(eventType, undefined, undefined, undefined);
            }
        ),
        vscode.commands.registerCommand(SelfCommands.FETCH_REPLIES, ({ parentTimestamp, provider }) =>
            fetchReplies(provider, parentTimestamp)
        ),
        vscode.commands.registerCommand(SelfCommands.UPDATE_MESSAGES, ({ channelId, messages, provider }) => {
            manager.updateMessages(provider, channelId, messages);
        }),
        vscode.commands.registerCommand(SelfCommands.CLEAR_MESSAGES, ({ channelId, provider }) => {
            manager.clearMessages(provider, channelId);
        }),
        vscode.commands.registerCommand(
            SelfCommands.ADD_MESSAGE_REACTION,
            ({ userId, msgTimestamp, channelId, reactionName, provider }) => {
                manager.addReaction(provider, channelId, msgTimestamp, userId, reactionName);
            }
        ),
        vscode.commands.registerCommand(
            SelfCommands.REMOVE_MESSAGE_REACTION,
            ({ userId, msgTimestamp, channelId, reactionName, provider }) => {
                manager.removeReaction(provider, channelId, msgTimestamp, userId, reactionName);
            }
        ),
        vscode.commands.registerCommand(SelfCommands.UPDATE_PRESENCE_STATUSES, ({ userId, presence, provider }) => {
            manager.updatePresenceForUser(provider, userId, presence);
        }),
        vscode.commands.registerCommand(SelfCommands.UPDATE_SELF_PRESENCE, askForSelfPresence),
        vscode.commands.registerCommand(SelfCommands.UPDATE_SELF_PRESENCE_VIA_VSLS, ({ presence, provider }) => {
            // Disabled to test auto-away fix
            // updateSelfPresence(provider, presence)
        }),
        vscode.commands.registerCommand(
            SelfCommands.CHANNEL_MARKED,
            ({ channelId, readTimestamp, unreadCount, provider }) => {
                return manager.updateChannelMarked(provider, channelId, readTimestamp, unreadCount);
            }
        ),
        vscode.commands.registerCommand(
            SelfCommands.UPDATE_MESSAGE_REPLIES,
            ({ provider, channelId, parentTimestamp, reply }) => {
                manager.updateMessageReply(provider, parentTimestamp, channelId, reply);
            }
        ),
        vscode.commands.registerCommand(SelfCommands.SHOW_TYPING, ({ provider, typingUserId, channelId }) => {
            manager.updateWebviewForProvider(provider, channelId, typingUserId);
            const key = `${channelId}:${typingUserId}`;

            if (typingTimers[key]) {
                clearTimeout(typingTimers[key] as NodeJS.Timer);
                typingTimers[key] = undefined;
            }

            const newTimer = setTimeout(() => {
                // This removes typing status --> this timeout should be larger than
                // the time period between typing events sent from the wire + the time
                // it takes to transfer them over the wire.
                manager.updateWebviewForProvider(provider, channelId, undefined);
            }, 5000);

            typingTimers[key] = newTimer;
        }),
        vscode.commands.registerCommand(SelfCommands.SEND_TO_WEBVIEW, ({ uiMessage }) =>
            controller.sendToUI(uiMessage)
        ),
        vscode.commands.registerCommand(SelfCommands.CHAT_WITH_VSLS_SPACE, ({ space }) => {
            const { name: spaceName } = space;
            return openVslsSpaceChat(spaceName);
        }),
        vscode.commands.registerCommand(SelfCommands.VSLS_SPACE_JOINED, async ({ name }) => {
            // Update store and launch the webview
            await manager.fetchUsers("vslsSpaces");
            await manager.fetchChannels("vslsSpaces");
            return openVslsSpaceChat(name);
        }),
        vscode.workspace.onDidChangeConfiguration(resetConfiguration),
        vscode.workspace.registerTextDocumentContentProvider(TRAVIS_SCHEME, travis),
        vscode.window.registerUriHandler(uriHandler),
        manager,
        telemetry
    );

    // telemetry.record(
    //     EventType.activationEnded,
    //     undefined,
    //     undefined,
    //     undefined
    // );
}

export function deactivate() {}


================================================
FILE: src/issues.ts
================================================
import { openUrl, getVersions } from "./utils";

const BASE_ISSUES_URL = "https://github.com/karigari/vscode-chat/issues/new";

export default class IssueReporter {
  static getVersionString() {
    const { extension, os, editor } = getVersions();
    return `- Extension Version: ${extension}\n- OS Version: ${os}\n- VSCode version: ${editor}`;
  }

  static getUrl(query: object) {
    const getParams = (p: object) =>
      Object.entries(p)
        .map(kv => kv.map(encodeURIComponent).join("="))
        .join("&");
    return `${BASE_ISSUES_URL}?${getParams(query)}`;
  }

  static openNewIssue(title: string, body: string) {
    const versions = this.getVersionString();
    const bodyText = `${body}\n\n${versions}`.replace(/\n/g, "%0A");
    const params = { title: `[vscode] ${title}`, body: bodyText };
    return openUrl(this.getUrl(params));
  }
}


================================================
FILE: src/logger.ts
================================================
import * as vscode from "vscode";
import { OUTPUT_CHANNEL_NAME } from "./constants";

export default class Logger {
  static output: vscode.OutputChannel | undefined;

  static setup() {
    this.output =
      this.output || vscode.window.createOutputChannel(OUTPUT_CHANNEL_NAME);
  }

  private static get timestamp(): string {
    const now = new Date();
    return now.toLocaleString();
  }

  private static logOnConsole(message: string): void {
    console.log(message);
  }

  private static logOnOutput(message: string): void {
    if (this.output === undefined) {
      this.setup();
    }

    if (!!this.output) {
      this.output.appendLine(message);
    }
  }

  static log(message: any): void {
    const logLine = `[${this.timestamp}] Chat: ${message}`;
    return process.env.IS_DEBUG === "true"
      ? this.logOnConsole(logLine)
      : this.logOnOutput(logLine);
  }
}


================================================
FILE: src/manager/chatManager.ts
================================================
import { isSuperset, difference, toTitleCase } from "../utils";

export class ChatProviderManager {
    messages: Messages = {};
    currentUserPrefs: UserPreferences = {};
    stateFetchedAt: Date | undefined;

    constructor(
        private store: IStore,
        public providerName: string,
        public teamId: string | undefined,
        private chatProvider: IChatProvider,
        private parentManager: IManager
    ) {}

    getTeams(): Team[] {
        // Due to design limitation we can only work with one team at a time,
        // and so this only returns the current team. (or else, Discord shows
        // multiple status items for unread messages.)
        const currentTeam = this.getCurrentTeam();
        return !!currentTeam ? [currentTeam] : [];
    }

    getCurrentTeam(): Team | undefined {
        const currentUser = this.store.getCurrentUser(this.providerName);
        return !!currentUser ? currentUser.teams.find(team => team.id === currentUser.currentTeamId) : undefined;
    }

    initializeProvider = async (): Promise<any> => {
        const isConnected = this.chatProvider.isConnected();
        const isAuthenticated = this.isAuthenticated();
        let currentUser = this.store.getCurrentUser(this.providerName);

        if (!(isConnected && isAuthenticated)) {
            if (!!this.chatProvider) {
                currentUser = await this.chatProvider.connect();
                this.store.updateCurrentUser(this.providerName, currentUser);
            }
        }

        return currentUser;
    };

    isAuthenticated() {
        const currentUserInfo = this.store.getCurrentUser(this.providerName);
        return !!currentUserInfo && !!currentUserInfo.id;
    }

    destroy() {
        this.chatProvider.destroy();
    }

    updateWebviewForLastChannel() {
        const lastChannelId = this.store.getLastChannelId(this.providerName);

        if (!!lastChannelId) {
            this.parentManager.updateWebviewForProvider(this.providerName, lastChannelId);
        }
    }

    async fetchThreadReplies(parentTimestamp: string) {
        const currentChannelId = this.store.getLastChannelId(this.providerName);

        if (!!currentChannelId) {
            const message = await this.chatProvider.fetchThreadReplies(currentChannelId, parentTimestamp);

            if (!!message) {
                let messages: ChannelMessages = {};
                messages[parentTimestamp] = message;
                this.updateMessages(currentChannelId, messages);
            }
        }
    }

    updateSelfPresence = async (presence: UserPresence, durationInMinutes: number) => {
        const currentUserInfo = this.store.getCurrentUser(this.providerName);

        if (!!currentUserInfo) {
            const presenceResult = await this.chatProvider.updateSelfPresence(presence, durationInMinutes);

            if (!!presenceResult) {
                this.updatePresenceForUser(currentUserInfo.id, presenceResult);
            }
        }
    };

    updatePresenceForUser = (userId: string, presence: UserPresence) => {
        const users = this.store.getUsers(this.providerName);

        if (userId in users) {
            const existingPresence = users[userId].presence;

            if (existingPresence === UserPresence.invisible && presence === UserPresence.offline) {
                // If we know user is `invisible`, then `offline` presence change
                // should be ignored. This will only happen for self.
                return;
            }

            this.store.updateUser(this.providerName, userId, {
                ...users[userId],
                presence
            });

            if (presence !== existingPresence) {
                this.parentManager.updateTreeViewsForProvider(this.providerName);
            }
        }
    };

    sendMessage = (text: string, channelId: string, parentTimestamp: string | undefined): Promise<void> => {
        const currentUserInfo = this.store.getCurrentUser(this.providerName);

        if (!!currentUserInfo) {
            if (!!parentTimestamp) {
                // This is a thread reply
                return this.chatProvider.sendThreadReply(text, currentUserInfo.id, channelId, parentTimestamp);
            } else {
                // THis is a normal message
                return this.chatProvider.sendMessage(text, currentUserInfo.id, channelId);
            }
        }

        return Promise.resolve();
    };

    clearMessages = (channelId: string) => {
        const existingMessages = channelId in this.messages ? this.messages[channelId] : {};
        const deletedMessages: any = {};
        Object.keys(existingMessages).forEach((ts: string) => {
            deletedMessages[ts] = undefined;
        });

        return this.updateMessages(channelId, deletedMessages);
    };

    updateMessages = (channelId: string, messages: ChannelMessagesWithUndefined) => {
        const existingMessages = channelId in this.messages ? this.messages[channelId] : {};
        const deletedTimestamps = Object.keys(messages).filter(ts => typeof messages[ts] === "undefined");

        const newMessages: ChannelMessages = {};
        Object.keys(existingMessages).forEach(ts => {
            const isDeleted = deletedTimestamps.indexOf(ts) >= 0;
            if (!isDeleted) {
                newMessages[ts] = existingMessages[ts];
            }
        });
        Object.keys(messages).forEach(ts => {
            const message = messages[ts];
            if (!!message) {
                newMessages[ts] = message;
            }
        });
        this.messages[channelId] = newMessages;

        // Remove undefined, after message deleted
        Object.keys(this.messages[channelId]).forEach(key => {
            if (typeof this.messages[channelId][key] === "undefined") {
                delete this.messages[channelId][key];
            }
        });

        // Check if we have all users. Since there is no `bots.list` Slack API
        // method, it is possible that a bot user is not in our store
        const users = this.store.getUsers(this.providerName);
        const knownUserIds = new Set(Object.keys(users));
        const channelMessages = this.messages[channelId];
        const entries = Object.entries(channelMessages);
        const userIds = new Set(entries.map(([_, message]) => message.userId));

        if (!isSuperset(knownUserIds, userIds)) {
            this.fillUpUsers(difference(userIds, knownUserIds));
        }

        this.updateWebviewForLastChannel();
        this.parentManager.updateStatusItemsForProvider(this.providerName);
        this.parentManager.updateTreeViewsForProvider(this.providerName);
    };

    sendTyping = (channelId: string) => {
        const currentUser = this.store.getCurrentUser(this.providerName);

        if (currentUser) {
            return this.chatProvider.sendTyping(currentUser.id, channelId)
        }
    };

    private async fillUpUsers(missingIds: Set<any>): Promise<void> {
        // missingIds are user/bot ids that we don't have in the store. We will
        // fetch their details, and then update the UI.
        const users = this.store.getUsers(this.providerName);
        const usersCopy: Users = { ...users };
        let ids = Array.from(missingIds);

        await Promise.all(
            ids.map(async userId => {
                let user = await this.chatProvider.fetchUserInfo(userId);

                if (!!user) {
                    const { id } = user;
                    usersCopy[id] = user;
                }
            })
        );

        this.store.updateUsers(this.providerName, usersCopy);
        this.updateWebviewForLastChannel();
    }

    updateMessageReply(parentTimestamp: string, channelId: string, reply: MessageReply) {
        // We need to have the message in our store, else we
        // ignore this reply
        const messages = channelId in this.messages ? this.messages[channelId] : {};
        const message = parentTimestamp in messages ? messages[parentTimestamp] : undefined;

        if (!!message) {
            let newMessages: ChannelMessages = {};
            const replyTs = reply.timestamp;
            let replies: MessageReplies = { ...message.replies };
            replies[replyTs] = { ...reply };
            newMessages[parentTimestamp] = {
                ...message,
                replies
            };
            this.updateMessages(channelId, newMessages);
        }
    }

    removeReaction(channelId: string, msgTimestamp: string, userId: string, reactionName: string) {
        if (channelId in this.messages) {
            const channelMessages = this.messages[channelId];

            if (msgTimestamp in channelMessages) {
                const message = channelMessages[msgTimestamp];
                let { reactions } = message;
                reactions = reactions
                    .map(r => {
                        if (r.name === reactionName) {
                            return {
                                ...r,
                                count: r.count - 1,
                                userIds: r.userIds.filter(u => u !== userId)
                            };
                        } else {
                            return { ...r };
                        }
                    })
                    .filter(r => r.count > 0);

                const newMessage = {
                    ...message,
                    reactions
                };
                const newMessages: ChannelMessages = {};
                newMessages[msgTimestamp] = newMessage;
                this.updateMessages(channelId, newMessages);
            }
        }
    }

    addReaction(channelId: string, msgTimestamp: string, userId: string, reactionName: string) {
        if (channelId in this.messages) {
            const channelMessages = this.messages[channelId];

            if (msgTimestamp in channelMessages) {
                const message = channelMessages[msgTimestamp];
                let { reactions } = message;
                const existing = reactions.find(r => r.name === reactionName);

                if (existing) {
                    reactions = reactions.map(r => {
                        if (r.name === reactionName) {
                            return {
                                ...existing,
                                count: existing.count + 1,
                                userIds: [...existing.userIds, userId]
                            };
                        } else {
                            return { ...r };
                        }
                    });
                } else {
                    reactions = [...reactions, { name: reactionName, userIds: [userId], count: 1 }];
                }

                const newMessage = {
                    ...message,
                    reactions
                };
                const newMessages: ChannelMessages = {};
                newMessages[msgTimestamp] = newMessage;
                this.updateMessages(channelId, newMessages);
            }
        }
    }

    async loadChannelHistory(channelId: string): Promise<void> {
        try {
            const messages = await this.chatProvider.loadChannelHistory(channelId);
            return this.updateMessages(channelId, messages);
        } catch (error) {
            return console.error(error);
        }
    }

    async updateUserPrefs() {
        const response = await this.chatProvider.getUserPreferences();

        if (!!response) {
            // We could also save the muted channels to local storage
            this.currentUserPrefs = response;
            this.parentManager.updateStatusItemsForProvider(this.providerName);
        }
    }

    async createIMChannel(user: User): Promise<Channel | undefined> {
        const channel = await this.chatProvider.createIMChannel(user);

        if (!!channel) {
            await this.updateChannel(channel);
            return channel;
        }
    }

    subscribeForPresence() {
        const users = this.store.getUsers(this.providerName);

        if (!!this.chatProvider) {
            this.chatProvider.subscribePresence(users);
        }
    }

    updateChannel = async (newChannel: Channel) => {
        // Adds/updates channel in this.channels
        let found = false;
        const channels = this.store.getChannels(this.providerName);
        let updatedChannels = channels.map(channel => {
            const { id } = channel;

            if (id === newChannel.id) {
                found = true;
                return {
                    ...channel,
                    ...newChannel
                };
            } else {
                return channel;
            }
        });

        if (!found) {
            updatedChannels = [...updatedChannels, newChannel];
        }

        await this.store.updateChannels(this.providerName, updatedChannels);
        this.parentManager.updateTreeViewsForProvider(this.providerName);
    };

    updateChannelMarked(channelId: string, readTimestamp: string, unreadCount: number) {
        const channel = this.getChannel(channelId);

        if (!!channel) {
            this.updateChannel({ ...channel, readTimestamp, unreadCount });
            this.updateWebviewForLastChannel();
            this.parentManager.updateStatusItemsForProvider(this.providerName);
            this.parentManager.updateTreeViewsForProvider(this.providerName);
        }
    }

    fetchUnreadCounts = async (channels: Channel[]) => {
        // We have to fetch twice here because Slack does not return the
        // historical unread counts for channels in the list API.
        const promises = channels.map(async channel => {
            const newChannel = await this.chatProvider.fetchChannelInfo(channel);

            if (!!newChannel && newChannel.unreadCount !== channel.unreadCount) {
                return this.updateChannel(newChannel);
            }
        });

        await Promise.all(promises);
        this.parentManager.updateStatusItemsForProvider(this.providerName);
    };

    fetchUsers = async (): Promise<Users> => {
        const users = await this.chatProvider.fetchUsers();
        let usersWithPresence: Users = {};
        const existingUsers = this.store.getUsers(this.providerName);

        Object.keys(users).forEach(userId => {
            // This handles two different chat providers:
            // In slack, we will get isOnline as undefined, because this API
            //    does not know about user presence
            // In discord, we will get true/false
            const existingUser = userId in existingUsers ? existingUsers[userId] : null;
            const newUser = users[userId];
            let calculatedPresence: UserPresence;

            if (newUser.presence !== UserPresence.unknown) {
                calculatedPresence = newUser.presence;
            } else {
                calculatedPresence = !!existingUser ? existingUser.presence : UserPresence.unknown;
            }

            usersWithPresence[userId] = {
                ...users[userId],
                presence: calculatedPresence
            };
        });

        this.store.updateUsers(this.providerName, usersWithPresence);
        return usersWithPresence;
    };

    fetchChannels = async (): Promise<Channel[]> => {
        const users = this.store.getUsers(this.providerName);
        const channels = await this.chatProvider.fetchChannels(users);
        await this.store.updateChannels(this.providerName, channels);
        this.parentManager.updateTreeViewsForProvider(this.providerName);
        this.fetchUnreadCounts(channels);
        return channels;
    };

    private shouldFetchNew = (lastFetchedAt: Date | undefined): boolean => {
        if (!lastFetchedAt) {
            return true;
        }

        const now = new Date();
        const difference = now.valueOf() - lastFetchedAt.valueOf();
        const FETCH_THRESHOLD = 15 * 60 * 1000; // 15-mins
        return difference > FETCH_THRESHOLD;
    };

    async initializeState(): Promise<void> {
        const users = this.store.getUsers(this.providerName);
        const hasCachedUsers = Object.keys(users).length !== 0;

        if (!hasCachedUsers) {
            await this.fetchUsers();
            const channels = this.store.getChannels(this.providerName);
            const hasCachedChannels = channels.length !== 0;

            if (!hasCachedChannels) {
                await this.fetchChannels();
                this.stateFetchedAt = new Date();
            }

            return;
        }

        // We already have a copy of the state, but if it's old, we run an async update
        if (this.shouldFetchNew(this.stateFetchedAt)) {
            this.fetchUsers().then(users => {
                this.fetchChannels();
                this.stateFetchedAt = new Date();
            });
        }
    }

    getChannel(channelId: string | undefined): Channel | undefined {
        if (!!channelId) {
            const channels = this.store.getChannels(this.providerName);
            return channels.find(channel => channel.id === channelId);
        }
    }

    getLastTimestamp(): string | undefined {
        const channelId = this.store.getLastChannelId(this.providerName);
        const channelMessages = !!channelId && channelId in this.messages ? this.messages[channelId] : {};
        const timestamps = Object.keys(channelMessages).map(tsString => +tsString);

        if (timestamps.length > 0) {
            return Math.max(...timestamps).toString();
        }
    }

    async updateReadMarker(): Promise<void> {
        const channelId = this.store.getLastChannelId(this.providerName);
        const channel = this.getChannel(channelId);
        const lastTs = this.getLastTimestamp();

        if (channel && lastTs) {
            const { readTimestamp } = channel;
            const hasNewerMsgs = !!readTimestamp ? +readTimestamp < +lastTs : true;

            if (hasNewerMsgs) {
                const incremented = (+lastTs + 1).toString(); // Slack API workaround
                const updatedChannel = await this.chatProvider.markChannel(channel, incremented);

                if (!!updatedChannel) {
                    this.updateChannel(updatedChannel);
                    this.updateWebviewForLastChannel();
                    this.parentManager.updateStatusItemsForProvider(this.providerName);
                    this.parentManager.updateTreeViewsForProvider(this.providerName);
                }
            }
        }
    }

    private isChannelMuted(channelId: string): boolean {
        const { mutedChannels } = this.currentUserPrefs;
        return !!mutedChannels && mutedChannels.indexOf(channelId) >= 0;
    }

    getUnreadCount(channel: Channel): number {
        const { id, readTimestamp, unreadCount } = channel;

        if (this.isChannelMuted(id)) {
            // This channel is muted, so return 0
            return 0;
        }

        const currentUserInfo = this.store.getCurrentUser(this.providerName);

        if (!currentUserInfo) {
            // Can be undefined during async update on vsls chat
            return 0;
        }

        const messages = id in this.messages ? this.messages[id] : {};

        const unreadMessages = Object.keys(messages).filter(ts => {
            const isDifferentUser = messages[ts].userId !== currentUserInfo.id;
            const isNewTimestamp = !!readTimestamp ? +ts > +readTimestamp : false;
            return isDifferentUser && isNewTimestamp;
        });

        return unreadCount ? unreadCount : unreadMessages.length;
    }

    getChannelLabels(): ChannelLabel[] {
        const channels = this.store.getChannels(this.providerName);
        const users = this.store.getUsers(this.providerName);
        const providerName = toTitleCase(this.providerName);
        const currentTeam = this.getCurrentTeam();
        const teamName = !!currentTeam ? currentTeam.name : "";

        return channels.map(channel => {
            const unread = this.getUnreadCount(channel);
            const { name, type, id } = channel;
            const isMuted = this.isChannelMuted(id);
            let presence: UserPresence = UserPresence.unknown;

            if (type === ChannelType.im) {
                const relatedUserId = Object.keys(users).find(value => {
                    const user = users[value];
                    const { name: username } = user;
                    // Same issue as getIMChannel(), so we handle both
                    return `@${username}` === name || username === name;
                });

                if (!!relatedUserId) {
                    const relatedUser = users[relatedUserId];
                    presence = relatedUser.presence;
                }
            }

            let label;

            if (unread > 0) {
                label = `${name} ${unread > 0 ? `(${unread} new)` : ""}`;
            } else if (isMuted) {
                label = `${name} (muted)`;
            } else {
                label = `${name}`;
            }

            return {
                channel,
                unread,
                label,
                presence,
                providerName,
                teamName
            };
        });
    }

    getUserPresence(userId: string) {
        const user = this.store.getUser(this.providerName, userId);
        return !!user ? user.presence : undefined;
    }

    getCurrentUserPresence = () => {
        const currentUser = this.store.getCurrentUser(this.providerName);
        return !!currentUser ? this.getUserPresence(currentUser.id) : undefined;
    };
}


================================================
FILE: src/manager/index.ts
================================================
import * as vscode from "vscode";
import { hasVslsSpacesExtension } from "../utils";
import { DiscordChatProvider } from "../discord";
import { SlackChatProvider } from "../slack";
import { ViewsManager } from "./views";
import { ConfigHelper } from "../config";
import { ChatProviderManager } from "./chatManager";
import { SelfCommands } from "../constants";
import { VslsSpacesProvider } from "../vslsSpaces";

export default class Manager implements IManager, vscode.Disposable {
    isTokenInitialized: boolean = false;
    viewsManager: ViewsManager;
    chatProviders = new Map<Providers, ChatProviderManager>();

    constructor(public store: IStore) {
        this.viewsManager = new ViewsManager(this);
    }

    getEnabledProviders(newInitialState?: InitialState): InitialState[] {
        // if newInitialState is specified, enabled list must include it
        let currentUserInfos = this.store.getCurrentUserForAll();
        let providerTeamIds: { [provider: string]: string | undefined } = {};

        currentUserInfos.forEach(currentUser => {
            const { provider } = currentUser;

            if (provider !== "vslsSpaces") {
                // This provider is dependent on installed extensions, not the user state
                providerTeamIds[currentUser.provider] = currentUser.currentTeamId;
            }
        });

        const hasVslsSpaces = hasVslsSpacesExtension();

        if (hasVslsSpaces) {
            providerTeamIds[Providers.vslsSpaces] = undefined;
        }

        if (!!newInitialState) {
            providerTeamIds[newInitialState.provider] = newInitialState.teamId;
        }

        if (!!providerTeamIds[Providers.discord]) {
            providerTeamIds[Providers.discord] = undefined;
        }

        return Object.keys(providerTeamIds).map(provider => ({
            provider,
            teamId: providerTeamIds[provider]
        }));
    }

    isProviderEnabled(provider: string): boolean {
        const cp = this.chatProviders.get(provider as Providers);
        return !!cp;
    }

    getCurrentTeamIdFor(provider: string) {
        const currentUser = this.store.getCurrentUser(provider);
        return !!currentUser ? currentUser.currentTeamId : undefined;
    }

    getCurrentUserFor(provider: string) {
        return this.store.getCurrentUser(provider);
    }

    getChatProvider(providerName: Providers) {
        return this.chatProviders.get(providerName);
    }

    instantiateChatProvider(token: string, provider: string): IChatProvider {
        switch (provider) {
            case "discord":
                return new DiscordChatProvider(token, this);
            case "slack":
                return new SlackChatProvider(token, this);
            case "vslsSpaces":
                return new VslsSpacesProvider();
            default:
                throw new Error(`unsupport chat provider: ${provider}`);
        }
    }

    async validateToken(provider: string, token: string) {
        const chatProvider
Download .txt
gitextract_mypbxujs/

├── .gitattributes
├── .github/
│   └── main.workflow
├── .gitignore
├── .prettierrc
├── .travis.yml
├── .vscode/
│   ├── extensions.json
│   ├── launch.json
│   ├── settings.json
│   └── tasks.json
├── .vscodeignore
├── CHANGELOG.md
├── LICENSE
├── README.md
├── VISION.md
├── azure-pipelines.yml
├── docs/
│   ├── CONFIG.md
│   ├── CONTRIBUTING.md
│   ├── DISCORD.md
│   ├── PROVIDERS.md
│   └── SLACK.md
├── oauth-service/
│   ├── README.md
│   ├── handler.ts
│   ├── html/
│   │   ├── error.template.html
│   │   ├── home.template.html
│   │   └── success.template.html
│   ├── html.d.ts
│   ├── package.json
│   ├── serverless.yml
│   ├── source-map-install.js
│   ├── tsconfig.json
│   ├── utils.ts
│   └── webpack.config.js
├── oauth-service-2/
│   ├── .gcloudignore
│   ├── README.md
│   ├── htmls.js
│   ├── index.js
│   ├── package.json
│   └── utils.js
├── package.json
├── readme/
│   ├── logo.sketch
│   └── screenshots.sketch
├── src/
│   ├── bots/
│   │   └── travis.ts
│   ├── config/
│   │   ├── https-proxy-agent.d.ts
│   │   ├── index.ts
│   │   └── keychain.ts
│   ├── constants.ts
│   ├── controller/
│   │   ├── commands.ts
│   │   ├── emoji-js.d.ts
│   │   ├── index.ts
│   │   ├── markdown-it-slack.d.ts
│   │   └── markdowner.ts
│   ├── discord/
│   │   └── index.ts
│   ├── extension.ts
│   ├── issues.ts
│   ├── logger.ts
│   ├── manager/
│   │   ├── chatManager.ts
│   │   ├── index.ts
│   │   ├── treeView.ts
│   │   └── views.ts
│   ├── onboarding.ts
│   ├── slack/
│   │   ├── client.ts
│   │   ├── common.ts
│   │   ├── index.ts
│   │   └── messenger.ts
│   ├── status/
│   │   └── index.ts
│   ├── store.ts
│   ├── strings.ts
│   ├── telemetry.ts
│   ├── test/
│   │   ├── extension.test.ts
│   │   ├── index.ts
│   │   ├── manager.test.ts
│   │   └── utils.test.ts
│   ├── tree/
│   │   ├── base.ts
│   │   ├── index.ts
│   │   └── treeItem.ts
│   ├── types.ts
│   ├── uriHandler.ts
│   ├── utils/
│   │   ├── index.ts
│   │   └── keychain.ts
│   ├── vslsSpaces/
│   │   ├── gravatar-api.d.ts
│   │   └── index.ts
│   └── webview/
│       └── index.ts
├── tsconfig.json
├── tslint.json
├── webpack.config.js
└── webview/
    ├── .gitignore
    ├── README.md
    ├── babel.config.js
    ├── package.json
    ├── src/
    │   ├── App.vue
    │   ├── components/
    │   │   ├── DateSeparator.vue
    │   │   ├── FormSection.vue
    │   │   ├── MarkdownElement.vue
    │   │   ├── MessageAuthor.vue
    │   │   ├── MessageContent.vue
    │   │   ├── MessageGroup.vue
    │   │   ├── MessageInput.vue
    │   │   ├── MessageItem.vue
    │   │   ├── MessageReaction.vue
    │   │   ├── MessageReactions.vue
    │   │   ├── MessageReplies.vue
    │   │   ├── MessageRepliesImages.vue
    │   │   ├── MessageReplyItem.vue
    │   │   ├── MessageTitle.vue
    │   │   ├── MessagesDateGroup.vue
    │   │   ├── MessagesSection.vue
    │   │   ├── StatusText.vue
    │   │   └── UserInfo.vue
    │   ├── main.js
    │   └── utils.js
    └── vue.config.js
Download .txt
SYMBOL INDEX (393 symbols across 35 files)

FILE: oauth-service-2/index.js
  function getSlackToken (line 6) | async function getSlackToken(code) {

FILE: oauth-service/handler.ts
  type TokenAPIResponse (line 13) | interface TokenAPIResponse {

FILE: src/bots/travis.ts
  function getTravisBuild (line 10) | function getTravisBuild(username: string, reponame: string, build: strin...
  function stripAnsiEscapes (line 30) | function stripAnsiEscapes(input: string) {
  class TravisLinkHandler (line 38) | class TravisLinkHandler implements CommandHandler {
    method handle (line 39) | handle(cmd: MessageCommand): Promise<CommandResponse> {
  class TravisDocumentContentProvider (line 59) | class TravisDocumentContentProvider
    method provideTextDocumentContent (line 61) | provideTextDocumentContent(uri: vscode.Uri): vscode.ProviderResult<str...

FILE: src/config/index.ts
  constant TOKEN_CONFIG_KEY (line 7) | const TOKEN_CONFIG_KEY = "slack.legacyToken";
  constant TELEMETRY_CONFIG_ROOT (line 8) | const TELEMETRY_CONFIG_ROOT = "telemetry";
  constant TELEMETRY_CONFIG_KEY (line 9) | const TELEMETRY_CONFIG_KEY = "enableTelemetry";
  constant CREDENTIAL_SERVICE_NAME (line 10) | const CREDENTIAL_SERVICE_NAME = "vscode-chat";
  constant VSLS_CHAT_TOKEN (line 11) | const VSLS_CHAT_TOKEN = "vsls-placeholder-token";
  class ConfigHelper (line 17) | class ConfigHelper {
    method getRootConfig (line 18) | static getRootConfig() {
    method updateRootConfig (line 22) | static updateRootConfig(section: string, value: any): Promise<void> {
    method getToken (line 37) | static async getToken(
    method clearTokenFromSettings (line 53) | static clearTokenFromSettings() {
    method setToken (line 57) | static async setToken(
    method clearToken (line 73) | static async clearToken(provider: string, teamId?: string): Promise<vo...
    method getProxyUrl (line 80) | static getProxyUrl() {
    method getTlsRejectUnauthorized (line 86) | static getTlsRejectUnauthorized() {
    method getAutoLaunchLiveShareChat (line 91) | static getAutoLaunchLiveShareChat() {
    method hasTelemetry (line 96) | static hasTelemetry(): boolean {
    method hasTravisProvider (line 101) | static hasTravisProvider(): boolean {
    method getCustomAgent (line 107) | static getCustomAgent() {

FILE: src/config/keychain.ts
  constant UNDEFINED_ERROR (line 7) | const UNDEFINED_ERROR = "System keychain is undefined";
  class KeychainHelper (line 9) | class KeychainHelper {
    method handleException (line 11) | static async handleException(error: Error, retryCall: Function) {
    method get (line 28) | static async get(service: string, account: string) {
    method set (line 43) | static async set(service: string, account: string, password: string) {
    method clear (line 57) | static async clear(service: string, account: string) {

FILE: src/constants.ts
  constant CONFIG_ROOT (line 1) | const CONFIG_ROOT = "chat";
  constant EXTENSION_ID (line 2) | const EXTENSION_ID = "karigari.chat";
  constant OUTPUT_CHANNEL_NAME (line 3) | const OUTPUT_CHANNEL_NAME = "Team Chat";
  constant CONFIG_AUTO_LAUNCH (line 4) | const CONFIG_AUTO_LAUNCH = "chat.autoLaunchLiveShareChat";
  constant LIVE_SHARE_BASE_URL (line 7) | const LIVE_SHARE_BASE_URL = `insiders.liveshare.vsengsaas.visualstudio.c...
  constant VSLS_EXTENSION_ID (line 8) | const VSLS_EXTENSION_ID = `ms-vsliveshare.vsliveshare`;
  constant VSLS_EXTENSION_PACK_ID (line 9) | const VSLS_EXTENSION_PACK_ID = `ms-vsliveshare.vsliveshare-pack`;
  constant VSLS_SPACES_EXTENSION_ID (line 10) | const VSLS_SPACES_EXTENSION_ID = `vsls-contrib.spaces`;
  constant SLASH_COMMANDS (line 56) | const SLASH_COMMANDS: any = {
  constant REVERSE_SLASH_COMMANDS (line 67) | const REVERSE_SLASH_COMMANDS = {
  constant TRAVIS_BASE_URL (line 74) | const TRAVIS_BASE_URL = `travis-ci.org`;
  constant TRAVIS_SCHEME (line 75) | const TRAVIS_SCHEME = "chat-travis-ci";
  constant REDIRECT_URI (line 78) | const REDIRECT_URI = `https://us-central1-eco-theater-119616.cloudfuncti...
  constant SLACK_OAUTH_BASE (line 79) | const SLACK_OAUTH_BASE = `https://slack.com/oauth/authorize?scope=client...
  constant SLACK_OAUTH (line 80) | const SLACK_OAUTH = `${SLACK_OAUTH_BASE}&redirect_uri=${REDIRECT_URI}`
  constant DISCORD_SCOPES (line 83) | const DISCORD_SCOPES = ["identify", "rpc.api", "messages.read", "guilds"];
  constant DISCORD_SCOPE_STRING (line 84) | const DISCORD_SCOPE_STRING = DISCORD_SCOPES.join("%20");
  constant DISCORD_CLIENT_ID (line 85) | const DISCORD_CLIENT_ID = "486416707951394817";
  constant DISCORD_OAUTH (line 86) | const DISCORD_OAUTH = `https://discordapp.com/oauth2/authorize?client_id...
  constant MIXPANEL_TOKEN (line 89) | const MIXPANEL_TOKEN = "14c9fea2bf4e06ba766e16eca1bce728";

FILE: src/controller/commands.ts
  type MessageCommand (line 12) | interface MessageCommand {
  type CommandResponse (line 17) | interface CommandResponse {
  type CommandHandler (line 22) | interface CommandHandler {
  class VscodeCommandHandler (line 26) | class VscodeCommandHandler implements CommandHandler {
  class OpenCommandHandler (line 57) | class OpenCommandHandler extends VscodeCommandHandler {
  class CommandDispatch (line 93) | class CommandDispatch {

FILE: src/controller/index.ts
  class ViewController (line 18) | class ViewController {
    method constructor (line 27) | constructor(
    method dispatchCommand (line 54) | dispatchCommand(command: MessageCommand) {

FILE: src/discord/index.ts
  constant HISTORY_LIMIT (line 8) | const HISTORY_LIMIT = 50;
  constant MEMBER_LIMIT (line 9) | const MEMBER_LIMIT = 500;
  constant DEFAULT_AVATARS (line 86) | const DEFAULT_AVATARS = [
  class DiscordChatProvider (line 109) | class DiscordChatProvider implements IChatProvider {
    method constructor (line 114) | constructor(private token: string, private manager: IManager) {
    method validateToken (line 118) | async validateToken(): Promise<CurrentUser | undefined> {
    method connect (line 137) | connect(): Promise<CurrentUser> {
    method handleIncomingMessage (line 188) | handleIncomingMessage(msg: Discord.Message) {
    method handleIncomingLinks (line 212) | handleIncomingLinks(msg: Discord.Message) {
    method isConnected (line 238) | isConnected(): boolean {
    method getUserPreferences (line 242) | getUserPreferences(): Promise<UserPreferences> {
    method getCurrentGuild (line 247) | getCurrentGuild(): Discord.Guild | undefined {
    method fetchUsers (line 256) | async fetchUsers(): Promise<Users> {
    method fetchUserInfo (line 298) | async fetchUserInfo(userId: string): Promise<User> {
    method fetchChannels (line 303) | fetchChannels(users: Users): Promise<Channel[]> {
    method loadChannelHistory (line 374) | async loadChannelHistory(channelId: string): Promise<ChannelMessages> {
    method sendMessage (line 393) | sendMessage(
    method fetchChannelInfo (line 404) | fetchChannelInfo(channel: Channel): Promise<Channel> {
    method subscribePresence (line 408) | subscribePresence(users: Users): void {}
    method sendThreadReply (line 410) | sendThreadReply() {
    method updateSelfPresence (line 414) | async updateSelfPresence(
    method destroy (line 442) | destroy(): Promise<void> {
    method markChannel (line 450) | async markChannel(channel: Channel, ts: string): Promise<Channel> {
    method fetchThreadReplies (line 461) | fetchThreadReplies(channelId: string, ts: string): Promise<any> {
    method createIMChannel (line 466) | createIMChannel(user: User): Promise<Channel | undefined> {
    method sendTyping (line 472) | async sendTyping(currentUserId: string, channelId: string) { }

FILE: src/extension.ts
  function activate (line 31) | function activate(context: vscode.ExtensionContext) {
  function deactivate (line 624) | function deactivate() {}

FILE: src/issues.ts
  constant BASE_ISSUES_URL (line 3) | const BASE_ISSUES_URL = "https://github.com/karigari/vscode-chat/issues/...
  class IssueReporter (line 5) | class IssueReporter {
    method getVersionString (line 6) | static getVersionString() {
    method getUrl (line 11) | static getUrl(query: object) {
    method openNewIssue (line 19) | static openNewIssue(title: string, body: string) {

FILE: src/logger.ts
  class Logger (line 4) | class Logger {
    method setup (line 7) | static setup() {
    method timestamp (line 12) | private static get timestamp(): string {
    method logOnConsole (line 17) | private static logOnConsole(message: string): void {
    method logOnOutput (line 21) | private static logOnOutput(message: string): void {
    method log (line 31) | static log(message: any): void {

FILE: src/manager/chatManager.ts
  class ChatProviderManager (line 3) | class ChatProviderManager {
    method constructor (line 8) | constructor(
    method getTeams (line 16) | getTeams(): Team[] {
    method getCurrentTeam (line 24) | getCurrentTeam(): Team | undefined {
    method isAuthenticated (line 44) | isAuthenticated() {
    method destroy (line 49) | destroy() {
    method updateWebviewForLastChannel (line 53) | updateWebviewForLastChannel() {
    method fetchThreadReplies (line 61) | async fetchThreadReplies(parentTimestamp: string) {
    method fillUpUsers (line 187) | private async fillUpUsers(missingIds: Set<any>): Promise<void> {
    method updateMessageReply (line 209) | updateMessageReply(parentTimestamp: string, channelId: string, reply: ...
    method removeReaction (line 228) | removeReaction(channelId: string, msgTimestamp: string, userId: string...
    method addReaction (line 260) | addReaction(channelId: string, msgTimestamp: string, userId: string, r...
    method loadChannelHistory (line 296) | async loadChannelHistory(channelId: string): Promise<void> {
    method updateUserPrefs (line 305) | async updateUserPrefs() {
    method createIMChannel (line 315) | async createIMChannel(user: User): Promise<Channel | undefined> {
    method subscribeForPresence (line 324) | subscribeForPresence() {
    method updateChannelMarked (line 358) | updateChannelMarked(channelId: string, readTimestamp: string, unreadCo...
    method initializeState (line 434) | async initializeState(): Promise<void> {
    method getChannel (line 460) | getChannel(channelId: string | undefined): Channel | undefined {
    method getLastTimestamp (line 467) | getLastTimestamp(): string | undefined {
    method updateReadMarker (line 477) | async updateReadMarker(): Promise<void> {
    method isChannelMuted (line 500) | private isChannelMuted(channelId: string): boolean {
    method getUnreadCount (line 505) | getUnreadCount(channel: Channel): number {
    method getChannelLabels (line 531) | getChannelLabels(): ChannelLabel[] {
    method getUserPresence (line 579) | getUserPresence(userId: string) {

FILE: src/manager/index.ts
  class Manager (line 11) | class Manager implements IManager, vscode.Disposable {
    method constructor (line 16) | constructor(public store: IStore) {
    method getEnabledProviders (line 20) | getEnabledProviders(newInitialState?: InitialState): InitialState[] {
    method isProviderEnabled (line 54) | isProviderEnabled(provider: string): boolean {
    method getCurrentTeamIdFor (line 59) | getCurrentTeamIdFor(provider: string) {
    method getCurrentUserFor (line 64) | getCurrentUserFor(provider: string) {
    method getChatProvider (line 68) | getChatProvider(providerName: Providers) {
    method instantiateChatProvider (line 72) | instantiateChatProvider(token: string, provider: string): IChatProvider {
    method validateToken (line 85) | async validateToken(provider: string, token: string) {
    method isAuthenticated (line 91) | isAuthenticated(providerName: string | undefined): boolean {
    method initializeStateForAll (line 178) | async initializeStateForAll() {
    method subscribePresenceForAll (line 185) | subscribePresenceForAll() {
    method updateUserPrefsForAll (line 192) | async updateUserPrefsForAll() {
    method signout (line 199) | async signout() {
    method clearAll (line 218) | clearAll() {
    method clearOldWorkspace (line 235) | async clearOldWorkspace(provider: string) {
    method updateWebviewForProvider (line 242) | async updateWebviewForProvider(provider: string, channelId: string, ty...
    method updateStatusItemsForProvider (line 262) | updateStatusItemsForProvider(provider: string) {
    method updateTreeViewsForProvider (line 273) | updateTreeViewsForProvider(provider: string) {
    method updateAllUI (line 277) | updateAllUI() {
    method dispose (line 292) | dispose() {
    method getChannelLabels (line 296) | getChannelLabels(provider: string | undefined): ChannelLabel[] {
    method getUserForId (line 312) | getUserForId(provider: string, userId: string) {
    method getIMChannel (line 317) | getIMChannel(provider: string, user: User): Channel | undefined {
    method createIMChannel (line 324) | async createIMChannel(providerName: string, user: User): Promise<Chann...
    method getUserPresence (line 329) | getUserPresence(provider: string, userId: string) {
    method loadChannelHistory (line 351) | async loadChannelHistory(providerName: string, channelId: string): Pro...
    method updateReadMarker (line 356) | async updateReadMarker(providerName: string): Promise<void> {
    method addReaction (line 376) | addReaction(providerName: string, channelId: string, msgTimestamp: str...
    method removeReaction (line 381) | removeReaction(
    method fetchThreadReplies (line 392) | async fetchThreadReplies(providerName: string, parentTimestamp: string) {
    method updateMessageReply (line 397) | updateMessageReply(providerName: string, parentTimestamp: string, chan...
    method updateMessages (line 402) | updateMessages(providerName: string, channelId: string, messages: Chan...
    method clearMessages (line 407) | clearMessages(providerName: string, channelId: string) {
    method updateChannelMarked (line 412) | updateChannelMarked(provider: string, channelId: string, readTimestamp...

FILE: src/manager/treeView.ts
  class TreeViewManager (line 10) | class TreeViewManager implements vscode.Disposable {
    method constructor (line 17) | constructor(public provider: string) {
    method updateData (line 25) | updateData(currentUserInfo: CurrentUser, channelLabels: ChannelLabel[]) {
    method dispose (line 33) | dispose() {

FILE: src/manager/views.ts
  constant PROVIDERS_WITH_TREE (line 8) | const PROVIDERS_WITH_TREE = ["slack", "discord"];
  class ViewsManager (line 14) | class ViewsManager implements vscode.Disposable {
    method constructor (line 19) | constructor(private parentManager: IManager) {}
    method initialize (line 21) | initialize(enabledProviders: string[], providerTeams: { [providerName:...
    method initializeStatusItems (line 50) | initializeStatusItems(newKeyMap: Map<string, { provider: string; team:...
    method initializeTreeViews (line 77) | initializeTreeViews(enabledProviders: string[]) {
    method updateStatusItem (line 101) | updateStatusItem(provider: string, team: Team) {
    method updateTreeViews (line 114) | updateTreeViews(provider: string) {
    method updateWebview (line 127) | updateWebview(
    method dispose (line 159) | dispose() {

FILE: src/onboarding.ts
  class CustomOnboardingTreeItem (line 36) | class CustomOnboardingTreeItem extends vscode.TreeItem {
    method constructor (line 37) | constructor(label: string, command: string) {
  type OnboardingTreeNode (line 47) | interface OnboardingTreeNode {
  class OnboardingTreeProvider (line 57) | class OnboardingTreeProvider
    method constructor (line 63) | constructor() {
    method dispose (line 78) | dispose() {
    method getChildren (line 82) | getChildren(element?: OnboardingTreeNode) {
    method getTreeItem (line 89) | getTreeItem(element: OnboardingTreeNode): vscode.TreeItem {

FILE: src/slack/client.ts
  type ISnoozeAPIResponse (line 6) | interface ISnoozeAPIResponse {
  constant CHANNEL_HISTORY_LIMIT (line 13) | const CHANNEL_HISTORY_LIMIT = 50;
  constant USER_LIST_LIMIT (line 15) | const USER_LIST_LIMIT = 1000;
  function notUndefined (line 19) | function notUndefined<T>(x: T | undefined): x is T {
  class SlackAPIClient (line 90) | class SlackAPIClient {
    method constructor (line 93) | constructor(private token: string) {
    method getUsers (line 146) | async getUsers(): Promise<Users> {
    method getBotInfo (line 166) | async getBotInfo(botId: string): Promise<User | undefined> {
    method getUserInfo (line 186) | async getUserInfo(userId: string): Promise<User | undefined> {
    method getChannels (line 195) | async getChannels(users: Users): Promise<Channel[]> {

FILE: src/slack/common.ts
  type IDNDStatus (line 1) | interface IDNDStatus {
  type IDNDStatusForUser (line 13) | interface IDNDStatusForUser {

FILE: src/slack/index.ts
  class SlackChatProvider (line 23) | class SlackChatProvider implements IChatProvider {
    method constructor (line 29) | constructor(private token: string, private manager: IManager) {
    method validateToken (line 40) | public validateToken(): Promise<CurrentUser | undefined> {
    method connect (line 46) | public connect(): Promise<CurrentUser> {
    method isConnected (line 50) | public isConnected(): boolean {
    method subscribePresence (line 54) | public subscribePresence(users: Users) {
    method createIMChannel (line 58) | public createIMChannel(user: User): Promise<Channel | undefined> {
    method fetchUsers (line 62) | public fetchUsers(): Promise<Users> {
    method fetchChannels (line 72) | public fetchChannels(users: Users): Promise<Channel[]> {
    method onPresenceChanged (line 78) | private onPresenceChanged(userId: string, rawPresence: "active" | "awa...
    method updateUserPresence (line 112) | private updateUserPresence(userId: string, presence: UserPresence) {
    method onDndStateChanged (line 120) | private onDndStateChanged(userId: string, dndState: IDNDStatus) {
    method updateDndTimers (line 125) | private updateDndTimers() {
    method updateDndTimerForUser (line 132) | private updateDndTimerForUser(userId: string) {
    method fetchUserInfo (line 168) | public fetchUserInfo(userId: string): Promise<User | undefined> {
    method loadChannelHistory (line 176) | public loadChannelHistory(channelId: string): Promise<ChannelMessages> {
    method getUserPreferences (line 180) | public getUserPreferences(): Promise<UserPreferences | undefined> {
    method markChannel (line 184) | public markChannel(
    method fetchThreadReplies (line 191) | public fetchThreadReplies(
    method fetchChannelInfo (line 198) | public fetchChannelInfo(channel: Channel): Promise<Channel | undefined> {
    method sendThreadReply (line 202) | public sendThreadReply(
    method sendMessage (line 212) | public async sendMessage(
    method updateSelfPresence (line 244) | public async updateSelfPresence(
    method destroy (line 275) | public destroy(): Promise<void> {
    method sendTyping (line 287) | async sendTyping(currentUserId: string, channelId: string) { }

FILE: src/slack/messenger.ts
  class SlackMessenger (line 28) | class SlackMessenger {
    method constructor (line 31) | constructor(
    method isConnected (line 185) | isConnected(): boolean {
    method disconnect (line 246) | disconnect() {

FILE: src/status/index.ts
  constant CHAT_OCTICON (line 4) | const CHAT_OCTICON = "$(comment-discussion)";
  method constructor (line 12) | constructor(baseCommand: string, commandArgs: ChatArgs, commandModifier:...
  method show (line 27) | show() {
  method hide (line 34) | hide() {
  method dispose (line 41) | dispose() {
  class UnreadsStatusItem (line 47) | class UnreadsStatusItem extends BaseStatusItem {
    method constructor (line 51) | constructor(providerName: string, team: Team) {
    method updateCount (line 64) | updateCount(unreads: number) {

FILE: src/store.ts
  constant VALUE_LENGTH_LIMIT (line 7) | const VALUE_LENGTH_LIMIT = 100;
  constant MESSAGE_HISTORY_LIMIT (line 8) | const MESSAGE_HISTORY_LIMIT = 50;
  class Store (line 20) | class Store implements IStore {
    method constructor (line 28) | constructor(private context: vscode.ExtensionContext) {
    method loadInitialState (line 32) | loadInitialState() {
    method runStateMigrations (line 42) | async runStateMigrations() {
    method migrateFor09x (line 57) | async migrateFor09x() {
    method generateInstallationId (line 83) | generateInstallationId(): string {
    method updateExtensionVersion (line 91) | updateExtensionVersion(version: string) {
    method clearProviderState (line 241) | async clearProviderState(provider: string): Promise<void> {

FILE: src/strings.ts
  constant CHANGE_CHANNEL_TITLE (line 1) | const CHANGE_CHANNEL_TITLE = "Select a channel";
  constant CHANGE_WORKSPACE_TITLE (line 3) | const CHANGE_WORKSPACE_TITLE = "Select a workspace";
  constant CHANGE_PROVIDER_TITLE (line 5) | const CHANGE_PROVIDER_TITLE = "Select a provider";
  constant RELOAD_CHANNELS (line 7) | const RELOAD_CHANNELS = "Reload Channels...";
  constant TOKEN_NOT_FOUND (line 9) | const TOKEN_NOT_FOUND = "Setup Team Chat to work for your account.";
  constant SETUP_SLACK (line 11) | const SETUP_SLACK = "Set up Slack";
  constant SETUP_DISCORD (line 13) | const SETUP_DISCORD = "Set up Discord";
  constant REPORT_ISSUE (line 15) | const REPORT_ISSUE = "Report issue";
  constant RETRY (line 17) | const RETRY = "Retry";
  constant KEYCHAIN_ERROR (line 19) | const KEYCHAIN_ERROR =
  constant TOKEN_PLACEHOLDER (line 22) | const TOKEN_PLACEHOLDER = "Paste token here";
  constant AUTH_FAILED_MESSAGE (line 24) | const AUTH_FAILED_MESSAGE =
  constant LIVE_REQUEST_MESSAGE (line 35) | const LIVE_REQUEST_MESSAGE = "wants to start a Live Share session";
  constant LIVE_SHARE_CHAT_NO_SESSION (line 40) | const LIVE_SHARE_CHAT_NO_SESSION =
  constant LIVE_SHARE_INFO_MESSAGES (line 43) | const LIVE_SHARE_INFO_MESSAGES = {
  constant SIGN_OUT (line 53) | const SIGN_OUT = "Sign out";
  constant SELECT_SELF_PRESENCE (line 55) | const SELECT_SELF_PRESENCE = "Select your presence status";
  constant SELECT_DND_DURATION (line 57) | const SELECT_DND_DURATION = "Select snooze duration for Slack";
  constant UNABLE_TO_MATCH_CONTACT (line 59) | const UNABLE_TO_MATCH_CONTACT =
  constant NO_LIVE_SHARE_CHAT_ON_HOST (line 62) | const NO_LIVE_SHARE_CHAT_ON_HOST =

FILE: src/telemetry.ts
  constant BATCH_SIZE (line 8) | const BATCH_SIZE = 10;
  constant INTERVAL_TIMEOUT (line 9) | const INTERVAL_TIMEOUT = 30 * 60 * 1000;
  class TelemetryReporter (line 11) | class TelemetryReporter implements vscode.Disposable {
    method constructor (line 20) | constructor(private manager: Manager) {
    method setUniqueId (line 42) | setUniqueId(uniqueId: string) {
    method dispose (line 46) | dispose(): Promise<any> {
    method record (line 58) | record(
    method getMxEvent (line 91) | getMxEvent(event: TelemetryEvent): Mixpanel.Event {
    method flushBatch (line 110) | flushBatch(): Promise<any> {

FILE: src/tree/base.ts
  type ISortingFunction (line 5) | interface ISortingFunction {
  type IFilterFunction (line 9) | interface IFilterFunction {
  class BaseChannelsListTreeProvider (line 13) | class BaseChannelsListTreeProvider
    method constructor (line 24) | constructor(protected providerName: string, protected viewId: string) {
    method dispose (line 30) | dispose() {
    method refresh (line 34) | async refresh(treeItem?: ChatTreeNode) {
    method getLabelsObject (line 40) | getLabelsObject(
    method updateChannels (line 51) | updateChannels(channelLabels: ChannelLabel[]) {

FILE: src/tree/index.ts
  class WorkspacesTreeProvider (line 10) | class WorkspacesTreeProvider extends BaseChannelsListTreeProvider {
    method constructor (line 15) | constructor(provider: string) {
    method updateCurrentUser (line 19) | updateCurrentUser(userInfo: CurrentUser) {
  class UnreadsTreeProvider (line 78) | class UnreadsTreeProvider extends BaseChannelsListTreeProvider {
    method constructor (line 82) | constructor(provider: string) {
  class ChannelTreeProvider (line 87) | class ChannelTreeProvider extends BaseChannelsListTreeProvider {
    method constructor (line 91) | constructor(provider: string) {
  class GroupTreeProvider (line 96) | class GroupTreeProvider extends BaseChannelsListTreeProvider {
    method constructor (line 100) | constructor(provider: string) {
  class IMsTreeProvider (line 105) | class IMsTreeProvider extends BaseChannelsListTreeProvider {
    method constructor (line 108) | constructor(provider: string) {
  class OnlineUsersTreeProvider (line 113) | class OnlineUsersTreeProvider extends BaseChannelsListTreeProvider {
    method constructor (line 119) | constructor(providerName: string) {
    method updateData (line 123) | updateData(
    method getItemForUser (line 148) | getItemForUser(user: User): ChatTreeNode {

FILE: src/tree/treeItem.ts
  constant BASE_PATH (line 6) | const BASE_PATH = path.join(selfExtension.extensionPath, "public", "icon...
  constant PRESENCE_ICONS (line 8) | const PRESENCE_ICONS = {
  class WorkspaceTreeItem (line 14) | class WorkspaceTreeItem extends vscode.TreeItem {
    method constructor (line 15) | constructor(label: string, provider: string, team: Team | undefined) {
  class ChannelTreeItem (line 28) | class ChannelTreeItem extends vscode.TreeItem {
    method constructor (line 29) | constructor(

FILE: src/types.ts
  type IChatProvider (line 1) | interface IChatProvider {
  type UserPresence (line 22) | const enum UserPresence {
  type User (line 31) | interface User {
  type UserPreferences (line 45) | interface UserPreferences {
  type Providers (line 49) | const enum Providers {
  type CurrentUser (line 55) | interface CurrentUser {
  type Team (line 63) | interface Team {
  type Users (line 69) | interface Users {
  type MessageAttachment (line 73) | interface MessageAttachment {
  type MessageContent (line 78) | interface MessageContent {
  type MessageReaction (line 89) | interface MessageReaction {
  type MessageReply (line 95) | interface MessageReply {
  type MessageReplies (line 102) | interface MessageReplies {
  type Message (line 106) | interface Message {
  type ChannelMessages (line 119) | interface ChannelMessages {
  type ChannelMessagesWithUndefined (line 123) | interface ChannelMessagesWithUndefined {
  type Messages (line 127) | interface Messages {
  type ChannelType (line 131) | const enum ChannelType {
  type IContactMetadata (line 137) | interface IContactMetadata {
  type Channel (line 142) | interface Channel {
  type ChannelLabel (line 152) | interface ChannelLabel {
  type MessageType (line 161) | const enum MessageType {
  type ExtensionMessage (line 169) | interface ExtensionMessage {
  type UIMessage (line 174) | interface UIMessage {
  type UIMessageDateGroup (line 186) | interface UIMessageDateGroup {
  type UIMessageGroup (line 191) | interface UIMessageGroup {
  type IStore (line 199) | interface IStore {
  type IManager (line 220) | interface IManager {
  type IViewsManager (line 238) | interface IViewsManager {
  type ChatArgs (line 244) | interface ChatArgs {
  type EventSource (line 251) | const enum EventSource {
  type EventType (line 261) | const enum EventType {
  type EventProperties (line 275) | interface EventProperties {
  type TelemetryEvent (line 281) | interface TelemetryEvent {
  type ChatTreeNode (line 287) | interface ChatTreeNode {
  type InitialState (line 297) | type InitialState = {

FILE: src/uriHandler.ts
  class ExtensionUriHandler (line 6) | class ExtensionUriHandler implements vscode.UriHandler {
    method handleUri (line 7) | handleUri(uri: vscode.Uri): vscode.ProviderResult<void> {
    method showIssuePrompt (line 21) | showIssuePrompt(errorMsg: string, service: string) {
    method parseQuery (line 34) | parseQuery(queryString: string): any {

FILE: src/utils/index.ts
  type Versions (line 30) | interface Versions {
  function uuidv4 (line 67) | function uuidv4(): string {
  function isSuperset (line 75) | function isSuperset(set: Set<any>, subset: Set<any>): boolean {
  function difference (line 84) | function difference(setA: Set<any>, setB: Set<any>) {
  function equals (line 92) | function equals(setA: Set<any>, setB: Set<any>) {
  function notUndefined (line 108) | function notUndefined<T>(x: T | undefined): x is T {
  function toTitleCase (line 112) | function toTitleCase(str: string) {
  function toDateString (line 118) | function toDateString(date: Date) {
  function camelCaseToTitle (line 134) | function camelCaseToTitle(text: string) {
  function titleCaseToCamel (line 139) | function titleCaseToCamel(text: string) {

FILE: src/utils/keychain.ts
  function getNodeModule (line 8) | function getNodeModule<T>(moduleName: string): T | undefined {

FILE: src/vslsSpaces/index.ts
  type IMessage (line 6) | interface IMessage {
  type IUser (line 13) | interface IUser {
  function sleep (line 27) | function sleep(ms: number) {
  class VslsSpacesProvider (line 31) | class VslsSpacesProvider implements IChatProvider {
    method constructor (line 35) | constructor() {
    method setupListeners (line 42) | setupListeners() {
    method getApi (line 64) | async getApi() {
    method connect (line 81) | async connect(): Promise<CurrentUser | undefined> {
    method onNewMessage (line 101) | onNewMessage(data: any) {
    method onNewSpace (line 115) | onNewSpace(spaceName: string) {
    method onClearMessages (line 121) | onClearMessages(spaceName: string) {
    method isConnected (line 128) | isConnected(): boolean {
    method sendMessage (line 132) | async sendMessage(text: string, currentUserId: string, channelId: stri...
    method fetchUsers (line 137) | async fetchUsers(): Promise<Users> {
    method fetchUserInfo (line 162) | async fetchUserInfo(userId: string): Promise<User | undefined> {
    method fetchChannels (line 167) | async fetchChannels(users: Users): Promise<Channel[]> {
    method loadChannelHistory (line 180) | async loadChannelHistory(channelId: string) {
    method subscribePresence (line 191) | subscribePresence(users: Users) {}
    method getUserPreferences (line 193) | getUserPreferences(): Promise<UserPreferences> {
    method validateToken (line 197) | async validateToken(): Promise<CurrentUser | undefined> {
    method fetchChannelInfo (line 201) | async fetchChannelInfo(channel: Channel): Promise<Channel | undefined> {
    method markChannel (line 205) | async markChannel(
    method fetchThreadReplies (line 212) | async fetchThreadReplies(
    method sendThreadReply (line 219) | async sendThreadReply(
    method updateSelfPresence (line 226) | async updateSelfPresence(
    method createIMChannel (line 233) | async createIMChannel(user: User): Promise<Channel | undefined> {
    method destroy (line 237) | async destroy() {}
    method sendTyping (line 239) | async sendTyping(currentUserId: string, channelId: string) { }

FILE: src/webview/index.ts
  constant SAME_GROUP_TIME (line 5) | const SAME_GROUP_TIME = 5 * 60;
  type MessageWithUnread (line 7) | interface MessageWithUnread extends Message {
  class WebviewContainer (line 11) | class WebviewContainer {
    method constructor (line 14) | constructor(
    method setMessageHandler (line 47) | setMessageHandler(msgHandler: (message: ExtensionMessage) => void) {
    method update (line 53) | update(uiMessage: UIMessage) {
    method reveal (line 61) | reveal() {
    method getAnnotatedMessages (line 65) | getAnnotatedMessages(
    method getMessageGroups (line 89) | getMessageGroups(input: ChannelMessages, users: Users): UIMessageDateG...
    method getMessageGroupsForDate (line 113) | getMessageGroupsForDate(
    method isVisible (line 163) | isVisible() {
  function getWebviewContent (line 168) | function getWebviewContent(staticPath: string) {

FILE: webview/src/utils.js
  function sendMessage (line 3) | function sendMessage(text, type) {
  function formattedTime (line 10) | function formattedTime(ts) {
  function openLink (line 15) | function openLink(href) {
Condensed preview — 111 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (355K chars).
[
  {
    "path": ".gitattributes",
    "chars": 77,
    "preview": "# Set default behavior to automatically normalize line endings.\n* text=auto\n\n"
  },
  {
    "path": ".github/main.workflow",
    "chars": 367,
    "preview": "workflow \"LSIF workflow\" {\n  resolves = [\"arjun27/lsif-action@master\"]\n  on = \"push\"\n}\n\naction \"arjun27/lsif-action@mast"
  },
  {
    "path": ".gitignore",
    "chars": 99,
    "preview": "out\nnode_modules\njspm_packages\n.vscode-test/\n.vs\n*.vsix\nstatic\ntokens\n.serverless\n.webpack\nenv.yml\n"
  },
  {
    "path": ".prettierrc",
    "chars": 44,
    "preview": "{\n    \"tabWidth\": 4,\n    \"printWidth\": 120\n}"
  },
  {
    "path": ".travis.yml",
    "chars": 366,
    "preview": "sudo: false\n\nlanguage: node_js\n\nnode_js:\n  - \"10\"\n  - \"9\"\n\nbefore_install:\n  - if [ $TRAVIS_OS_NAME == \"linux\" ]; then\n "
  },
  {
    "path": ".vscode/extensions.json",
    "chars": 156,
    "preview": "{\n\t// See http://go.microsoft.com/fwlink/?LinkId=827846\n\t// for the documentation about the extensions.json format\n\t\"rec"
  },
  {
    "path": ".vscode/launch.json",
    "chars": 1101,
    "preview": "// A launch configuration that compiles the extension and then opens it inside a new window\n// Use IntelliSense to learn"
  },
  {
    "path": ".vscode/settings.json",
    "chars": 444,
    "preview": "// Place your settings in this file to overwrite default and user settings.\n{\n    \"files.exclude\": {\n        \"out\": fals"
  },
  {
    "path": ".vscode/tasks.json",
    "chars": 444,
    "preview": "// See https://go.microsoft.com/fwlink/?LinkId=733558\n// for the documentation about the tasks.json format\n{\n  \"version\""
  },
  {
    "path": ".vscodeignore",
    "chars": 183,
    "preview": ".vs/**\n.vscode/**\n.vscode-test/**\nout/test/**\nout/**/*.map\nsrc/**\n.gitignore\ntsconfig.json\ntslint.json\ntokens\noauth-serv"
  },
  {
    "path": "CHANGELOG.md",
    "chars": 14889,
    "preview": "# Changelog\n\nAll notable changes to the Live Share Chat extension will be documented in this file. This follows the [Kee"
  },
  {
    "path": "LICENSE",
    "chars": 35150,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "README.md",
    "chars": 3372,
    "preview": "<h1 align=\"center\">Chat for VS Code</h1>\n\n<h3 align=\"center\">Chat with your Slack and Discord teams from within VS Code<"
  },
  {
    "path": "VISION.md",
    "chars": 3213,
    "preview": "# Vision\n\nThis doc outlines our vision and product roadmap. The goal is to crystallize the driving ideas: for our commun"
  },
  {
    "path": "azure-pipelines.yml",
    "chars": 308,
    "preview": "queue:\n  name: Hosted VS2017\n\nsteps:\n  - task: NodeTool@0\n    inputs:\n      versionSpec: '10.x'\n  - script: |\n      npm "
  },
  {
    "path": "docs/CONFIG.md",
    "chars": 847,
    "preview": "# Configuration\n\n## Network proxy\n\nTo use this extension behind a proxy, configure the proxy url.\n\n```json\n{\n  \"chat.pro"
  },
  {
    "path": "docs/CONTRIBUTING.md",
    "chars": 1620,
    "preview": "# Contributing\n\nThe repo is actively developed, and you are welcome to [submit feature requests](https://github.com/kari"
  },
  {
    "path": "docs/DISCORD.md",
    "chars": 1764,
    "preview": "# Discord Setup\n\n## Warning\n\nThe Discord integration involves an unofficial approach to getting the token, and is not re"
  },
  {
    "path": "docs/PROVIDERS.md",
    "chars": 3640,
    "preview": "# Chat providers\n\nThe goal of this extension is to open up support for other chat providers, in addition to Slack and Di"
  },
  {
    "path": "docs/SLACK.md",
    "chars": 1269,
    "preview": "# Slack authorization\n\nMany users have reported running into `access_denied` issues on Slack, and this doc attempts to l"
  },
  {
    "path": "oauth-service/README.md",
    "chars": 761,
    "preview": "# oauth-service\n\nThis is a serverless app to handle OAuth redirection for the Slack Chat extension, and it is deployed o"
  },
  {
    "path": "oauth-service/handler.ts",
    "chars": 4094,
    "preview": "import { APIGatewayEvent, Callback, Context, Handler } from \"aws-lambda\";\nimport * as request from \"request-promise-nati"
  },
  {
    "path": "oauth-service/html/error.template.html",
    "chars": 790,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\n<head>\n    <!-- Required meta tags -->\n    <meta charset=\"utf-8\">\n    <meta name=\"view"
  },
  {
    "path": "oauth-service/html/home.template.html",
    "chars": 1597,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\n<head>\n    <!-- Required meta tags -->\n    <meta charset=\"utf-8\">\n    <meta name=\"view"
  },
  {
    "path": "oauth-service/html/success.template.html",
    "chars": 2437,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\n<head>\n    <!-- Required meta tags -->\n    <meta charset=\"utf-8\">\n    <meta name=\"view"
  },
  {
    "path": "oauth-service/html.d.ts",
    "chars": 75,
    "preview": "declare module \"*.html\" {\n  const value: string;\n  export default value;\n}\n"
  },
  {
    "path": "oauth-service/package.json",
    "chars": 668,
    "preview": "{\n  \"name\": \"vscode-chat-oauth-service\",\n  \"description\": \"Serverless app to handle Slack OAuth for vscode-chat\",\n  \"ver"
  },
  {
    "path": "oauth-service/serverless.yml",
    "chars": 877,
    "preview": "service:\n  name: vscode-chat-oauth-service\n\nplugins:\n  - serverless-webpack\n  - serverless-offline\n  - serverless-domain"
  },
  {
    "path": "oauth-service/source-map-install.js",
    "chars": 41,
    "preview": "require('source-map-support').install();\n"
  },
  {
    "path": "oauth-service/tsconfig.json",
    "chars": 180,
    "preview": "{\n  \"compilerOptions\": {\n    \"sourceMap\": true,\n    \"target\": \"es6\",\n    \"lib\": [\n      \"esnext\"\n    ],\n    \"moduleResol"
  },
  {
    "path": "oauth-service/utils.ts",
    "chars": 1105,
    "preview": "import { APIGatewayEvent } from \"aws-lambda\";\n\nexport const parseQueryParams = (event: APIGatewayEvent) => {\n  const { q"
  },
  {
    "path": "oauth-service/webpack.config.js",
    "chars": 697,
    "preview": "const path = require(\"path\");\nconst slsw = require(\"serverless-webpack\");\n\nconst entries = {};\n\nObject.keys(slsw.lib.ent"
  },
  {
    "path": "oauth-service-2/.gcloudignore",
    "chars": 513,
    "preview": "# This file specifies files that are *not* uploaded to Google Cloud Platform\n# using gcloud. It follows the same syntax "
  },
  {
    "path": "oauth-service-2/README.md",
    "chars": 230,
    "preview": "# Oauth redirection service\n\n## Running locally\n\n```\nnpm start\n```\n\n## Deployment\n\n```\ngcloud functions deploy slackRedi"
  },
  {
    "path": "oauth-service-2/htmls.js",
    "chars": 3271,
    "preview": "exports.success = `\n<!doctype html>\n<html lang=\"en\">\n\n<head>\n    <!-- Required meta tags -->\n    <meta charset=\"utf-8\">\n"
  },
  {
    "path": "oauth-service-2/index.js",
    "chars": 1923,
    "preview": "//@ts-check\nconst utils = require('./utils');\nconst htmls = require('./htmls');\nconst request = require('request-promise"
  },
  {
    "path": "oauth-service-2/package.json",
    "chars": 379,
    "preview": "{\n  \"name\": \"oauth-service-2\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"index.js\",\n  \"scripts\": {\n    \"star"
  },
  {
    "path": "oauth-service-2/utils.js",
    "chars": 667,
    "preview": "exports.redirectUrl = (token, service, team) => {\n  return `vscode://karigari.chat/redirect?token=${token}&service=${ser"
  },
  {
    "path": "package.json",
    "chars": 9862,
    "preview": "{\n    \"name\": \"chat\",\n    \"displayName\": \"Chat\",\n    \"description\": \"Chat with your Slack and Discord teams from within "
  },
  {
    "path": "src/bots/travis.ts",
    "chars": 2044,
    "preview": "import * as vscode from \"vscode\";\nimport * as rp from \"request-promise-native\";\nimport {\n  CommandHandler,\n  CommandResp"
  },
  {
    "path": "src/config/https-proxy-agent.d.ts",
    "chars": 48,
    "preview": "// foo.d.ts\ndeclare module \"https-proxy-agent\";\n"
  },
  {
    "path": "src/config/index.ts",
    "chars": 3569,
    "preview": "import * as vscode from \"vscode\";\nimport * as https from \"https\";\nimport * as HttpsProxyAgent from \"https-proxy-agent\";\n"
  },
  {
    "path": "src/config/keychain.ts",
    "chars": 1968,
    "preview": "import * as vscode from \"vscode\";\nimport * as str from \"../strings\";\nimport { keychain } from \"../utils/keychain\";\nimpor"
  },
  {
    "path": "src/constants.ts",
    "chars": 3739,
    "preview": "export const CONFIG_ROOT = \"chat\";\nexport const EXTENSION_ID = \"karigari.chat\";\nexport const OUTPUT_CHANNEL_NAME = \"Team"
  },
  {
    "path": "src/controller/commands.ts",
    "chars": 3184,
    "preview": "import * as vscode from \"vscode\";\nimport * as vsls from \"vsls\";\nimport {\n  SLASH_COMMANDS,\n  LIVE_SHARE_BASE_URL,\n  TRAV"
  },
  {
    "path": "src/controller/emoji-js.d.ts",
    "chars": 39,
    "preview": "// foo.d.ts\ndeclare module \"emoji-js\";\n"
  },
  {
    "path": "src/controller/index.ts",
    "chars": 9200,
    "preview": "import * as vscode from \"vscode\";\nimport WebviewContainer from \"../webview\";\nimport { SLASH_COMMANDS, REVERSE_SLASH_COMM"
  },
  {
    "path": "src/controller/markdown-it-slack.d.ts",
    "chars": 48,
    "preview": "// foo.d.ts\ndeclare module \"markdown-it-slack\";\n"
  },
  {
    "path": "src/controller/markdowner.ts",
    "chars": 5005,
    "preview": "import * as EmojiConvertor from \"emoji-js\";\n\nexport const parseUsernames = (uiMessage: UIMessage): UIMessage => {\n    //"
  },
  {
    "path": "src/discord/index.ts",
    "chars": 13553,
    "preview": "import * as vscode from \"vscode\";\nimport * as Discord from \"discord.js\";\nimport * as rp from \"request-promise-native\";\ni"
  },
  {
    "path": "src/extension.ts",
    "chars": 24567,
    "preview": "import * as vscode from \"vscode\";\nimport * as vsls from \"vsls\";\nimport ViewController from \"./controller\";\nimport Manage"
  },
  {
    "path": "src/issues.ts",
    "chars": 862,
    "preview": "import { openUrl, getVersions } from \"./utils\";\n\nconst BASE_ISSUES_URL = \"https://github.com/karigari/vscode-chat/issues"
  },
  {
    "path": "src/logger.ts",
    "chars": 889,
    "preview": "import * as vscode from \"vscode\";\nimport { OUTPUT_CHANNEL_NAME } from \"./constants\";\n\nexport default class Logger {\n  st"
  },
  {
    "path": "src/manager/chatManager.ts",
    "chars": 21701,
    "preview": "import { isSuperset, difference, toTitleCase } from \"../utils\";\n\nexport class ChatProviderManager {\n    messages: Messag"
  },
  {
    "path": "src/manager/index.ts",
    "chars": 16469,
    "preview": "import * as vscode from \"vscode\";\nimport { hasVslsSpacesExtension } from \"../utils\";\nimport { DiscordChatProvider } from"
  },
  {
    "path": "src/manager/treeView.ts",
    "chars": 1426,
    "preview": "import * as vscode from \"vscode\";\nimport {\n  WorkspacesTreeProvider,\n  UnreadsTreeProvider,\n  ChannelTreeProvider,\n  Gro"
  },
  {
    "path": "src/manager/views.ts",
    "chars": 6257,
    "preview": "import * as vscode from \"vscode\";\nimport { TreeViewManager } from \"./treeView\";\nimport { BaseStatusItem, UnreadsStatusIt"
  },
  {
    "path": "src/onboarding.ts",
    "chars": 2425,
    "preview": "import * as vscode from \"vscode\";\nimport * as str from \"./strings\";\nimport { SelfCommands } from \"./constants\";\nimport {"
  },
  {
    "path": "src/slack/client.ts",
    "chars": 12331,
    "preview": "import { WebClient, WebClientOptions } from \"@slack/client\";\nimport { ConfigHelper } from \"../config\";\nimport Logger fro"
  },
  {
    "path": "src/slack/common.ts",
    "chars": 351,
    "preview": "export interface IDNDStatus {\n  dnd_enabled: boolean;\n  next_dnd_start_ts: number;\n  next_dnd_end_ts: number;\n\n  // The "
  },
  {
    "path": "src/slack/index.ts",
    "chars": 8509,
    "preview": "import * as vscode from \"vscode\";\nimport { SelfCommands } from \"../constants\";\nimport SlackAPIClient from \"./client\";\nim"
  },
  {
    "path": "src/slack/messenger.ts",
    "chars": 7765,
    "preview": "import * as vscode from \"vscode\";\nimport { RTMClient, RTMClientOptions } from \"@slack/client\";\nimport { ConfigHelper } f"
  },
  {
    "path": "src/status/index.ts",
    "chars": 2144,
    "preview": "import * as vscode from \"vscode\";\nimport { SelfCommands } from \"../constants\";\n\nconst CHAT_OCTICON = \"$(comment-discussi"
  },
  {
    "path": "src/store.ts",
    "chars": 10285,
    "preview": "import * as vscode from \"vscode\";\nimport * as semver from \"semver\";\nimport { uuidv4, getExtensionVersion } from \"./utils"
  },
  {
    "path": "src/strings.ts",
    "chars": 2122,
    "preview": "export const CHANGE_CHANNEL_TITLE = \"Select a channel\";\n\nexport const CHANGE_WORKSPACE_TITLE = \"Select a workspace\";\n\nex"
  },
  {
    "path": "src/telemetry.ts",
    "chars": 3532,
    "preview": "import * as vscode from \"vscode\";\nimport * as Mixpanel from \"mixpanel\";\nimport { MIXPANEL_TOKEN } from \"./constants\";\nim"
  },
  {
    "path": "src/test/extension.test.ts",
    "chars": 534,
    "preview": "//\n// Note: This example test is leveraging the Mocha test framework.\n// Please refer to their documentation on https://"
  },
  {
    "path": "src/test/index.ts",
    "chars": 1014,
    "preview": "//\n// PLEASE DO NOT MODIFY / DELETE UNLESS YOU KNOW WHAT YOU ARE DOING\n//\n// This file is providing the test runner to u"
  },
  {
    "path": "src/test/manager.test.ts",
    "chars": 1763,
    "preview": "import * as assert from \"assert\";\nimport { Store } from \"../store\";\nimport Manager from \"../manager\";\nimport { mock, ins"
  },
  {
    "path": "src/test/utils.test.ts",
    "chars": 379,
    "preview": "import * as assert from \"assert\";\nimport { sanitiseTokenString } from \"../utils\";\n\nsuite(\"utility function tests\", funct"
  },
  {
    "path": "src/tree/base.ts",
    "chars": 4962,
    "preview": "import * as vscode from \"vscode\";\nimport { ChannelTreeItem } from \"./treeItem\";\nimport { equals, notUndefined } from \".."
  },
  {
    "path": "src/tree/index.ts",
    "chars": 6591,
    "preview": "import * as vscode from \"vscode\";\nimport {\n  BaseChannelsListTreeProvider,\n  IFilterFunction,\n  ISortingFunction\n} from "
  },
  {
    "path": "src/tree/treeItem.ts",
    "chars": 2031,
    "preview": "import * as vscode from \"vscode\";\nimport * as path from \"path\";\nimport { SelfCommands, EXTENSION_ID } from \"../constants"
  },
  {
    "path": "src/types.ts",
    "chars": 8285,
    "preview": "interface IChatProvider {\n    validateToken: () => Promise<CurrentUser | undefined>;\n    fetchUsers: () => Promise<Users"
  },
  {
    "path": "src/uriHandler.ts",
    "chars": 1583,
    "preview": "import * as vscode from \"vscode\";\nimport * as str from \"./strings\";\nimport IssueReporter from \"./issues\";\nimport { Confi"
  },
  {
    "path": "src/utils/index.ts",
    "chars": 3484,
    "preview": "import * as vscode from \"vscode\";\nimport * as os from \"os\";\nimport {\n  VSCodeCommands,\n  EXTENSION_ID,\n  VSLS_EXTENSION_"
  },
  {
    "path": "src/utils/keychain.ts",
    "chars": 731,
    "preview": "// From https://github.com/Microsoft/vscode-pull-request-github/blob/master/src/common/keychain.ts\nimport * as vscode fr"
  },
  {
    "path": "src/vslsSpaces/gravatar-api.d.ts",
    "chars": 43,
    "preview": "// foo.d.ts\ndeclare module \"gravatar-api\";\n"
  },
  {
    "path": "src/vslsSpaces/index.ts",
    "chars": 6654,
    "preview": "import * as vscode from \"vscode\";\nimport * as gravatar from \"gravatar-api\";\nimport { VSLS_SPACES_EXTENSION_ID, SelfComma"
  },
  {
    "path": "src/webview/index.ts",
    "chars": 5593,
    "preview": "import * as vscode from \"vscode\";\nimport * as path from \"path\";\nimport { toDateString } from \"../utils\";\n\nconst SAME_GRO"
  },
  {
    "path": "tsconfig.json",
    "chars": 486,
    "preview": "{\n  \"compilerOptions\": {\n    \"module\": \"commonjs\",\n    \"target\": \"es2017\",\n    \"outDir\": \"out\",\n    \"lib\": [\"es6\", \"esne"
  },
  {
    "path": "tslint.json",
    "chars": 220,
    "preview": "{\n  \"rules\": {\n    \"no-string-throw\": true,\n    \"no-unused-expression\": true,\n    \"no-duplicate-variable\": true,\n    \"cu"
  },
  {
    "path": "webpack.config.js",
    "chars": 584,
    "preview": "//@ts-check\nconst path = require(\"path\");\nconst webpack = require(\"webpack\");\n\n/** @type webpack.Configuration */\n\nconst"
  },
  {
    "path": "webview/.gitignore",
    "chars": 214,
    "preview": ".DS_Store\nnode_modules\n/dist\n\n# local env files\n.env.local\n.env.*.local\n\n# Log files\nnpm-debug.log*\nyarn-debug.log*\nyarn"
  },
  {
    "path": "webview/README.md",
    "chars": 268,
    "preview": "# webview\n\nThe webview is built on Vue 2.x. You might need to install `@vue/cli` globally to build this.\n\n```\nyarn build"
  },
  {
    "path": "webview/babel.config.js",
    "chars": 61,
    "preview": "module.exports = {\n    presets: [\n        '@vue/app'\n    ]\n}\n"
  },
  {
    "path": "webview/package.json",
    "chars": 1091,
    "preview": "{\n  \"name\": \"webview\",\n  \"version\": \"0.1.0\",\n  \"private\": true,\n  \"scripts\": {\n    \"serve\": \"vue-cli-service serve\",\n   "
  },
  {
    "path": "webview/src/App.vue",
    "chars": 5188,
    "preview": "<template>\n    <div id=\"app\" v-bind:style=\"cssProps\">\n        <div class=\"vue-container\">\n            <messages-section\n"
  },
  {
    "path": "webview/src/components/DateSeparator.vue",
    "chars": 400,
    "preview": "<template>\n    <h3 class=\"date-heading\">{{dateString}}</h3>\n</template>\n\n<script>\nexport default {\n    name: 'date-separ"
  },
  {
    "path": "webview/src/components/FormSection.vue",
    "chars": 1063,
    "preview": "<template>\n    <div class=\"form-section\">\n        <div>\n            <message-input\n                v-bind:onSubmit=\"onSu"
  },
  {
    "path": "webview/src/components/MarkdownElement.vue",
    "chars": 750,
    "preview": "<template>\n    <div\n        v-if=\"html\"\n        v-bind:style=\"inlineStyleObject\"\n        v-html=\"html\">\n    </div>\n</tem"
  },
  {
    "path": "webview/src/components/MessageAuthor.vue",
    "chars": 243,
    "preview": "<template>\n    <div class=\"msg-author\">\n        <img v-bind:src=\"content.authorIcon\" />\n        <span>{{ content.author "
  },
  {
    "path": "webview/src/components/MessageContent.vue",
    "chars": 1264,
    "preview": "<template>\n    <div class=\"li-line\" v-bind:style=\"{ borderColor: borderColor }\">\n        <div v-if=\"content.pretext\">{{ "
  },
  {
    "path": "webview/src/components/MessageGroup.vue",
    "chars": 1226,
    "preview": "<template>\n    <div class=\"message-group\">\n        <div class=\"message-group-image\">\n            <img v-bind:src=\"user ?"
  },
  {
    "path": "webview/src/components/MessageInput.vue",
    "chars": 5142,
    "preview": "<template>\n    <vue-tribute :options=\"tributeOptions\">\n        <p\n            ref=\"messageInput\"\n            class=\"edit"
  },
  {
    "path": "webview/src/components/MessageItem.vue",
    "chars": 1176,
    "preview": "<template>\n    <li v-bind:class=\"{ unread: message.isUnread }\">\n        <markdown-element\n            v-bind:inline=\"fal"
  },
  {
    "path": "webview/src/components/MessageReaction.vue",
    "chars": 207,
    "preview": "<template>\n    <li>\n        <div>{{emoji}}</div>\n        <div>{{count}}</div>\n    </li>\n</template>\n\n<script>\nexport def"
  },
  {
    "path": "webview/src/components/MessageReactions.vue",
    "chars": 515,
    "preview": "<template>\n    <ul class=\"message-reactions\">\n        <message-reaction v-for=\"reaction in reactions\"\n            v-bind"
  },
  {
    "path": "webview/src/components/MessageReplies.vue",
    "chars": 3158,
    "preview": "<template>\n    <div class=\"replies-container\">\n        <div class=\"replies-summary\">\n            <message-replies-images"
  },
  {
    "path": "webview/src/components/MessageRepliesImages.vue",
    "chars": 259,
    "preview": "<template>\n    <div class=\"reply-images-container\">\n        <img v-for=\"url in images\" v-bind:src=\"url\" :key=\"url\" class"
  },
  {
    "path": "webview/src/components/MessageReplyItem.vue",
    "chars": 890,
    "preview": "<template>\n    <li>\n        <span>\n            <strong>{{username}}</strong>\n            &nbsp;\n            <span class="
  },
  {
    "path": "webview/src/components/MessageTitle.vue",
    "chars": 501,
    "preview": "<template>\n    <div class=\"msg-title\">\n        <a\n            v-bind:href=\"content.titleLink\"\n            v-bind:onclick"
  },
  {
    "path": "webview/src/components/MessagesDateGroup.vue",
    "chars": 707,
    "preview": "<template>\n    <div class=\"messages-date-section\">\n        <date-separator v-bind:date=\"date\"></date-separator>\n        "
  },
  {
    "path": "webview/src/components/MessagesSection.vue",
    "chars": 1150,
    "preview": "<template>\n    <div class=\"messages-section\">\n        <messages-date-group\n            v-for=\"dateGroup in messages\"\n   "
  },
  {
    "path": "webview/src/components/StatusText.vue",
    "chars": 157,
    "preview": "<template>\n    <div class=\"status-text\">{{ status }}</div>\n</template>\n\n<script>\nexport default {\n    name: 'status-text"
  },
  {
    "path": "webview/src/components/UserInfo.vue",
    "chars": 370,
    "preview": "<template>\n    <div class=\"user-info\">This is some text in a div.</div>\n</template>\n\n<script>\nexport default {\n    name:"
  },
  {
    "path": "webview/src/main.js",
    "chars": 256,
    "preview": "import Vue from 'vue'\nimport App from './App.vue'\n\nvar app = new Vue({\n    template: `<app :data=\"data\"> </app>`,\n    pr"
  },
  {
    "path": "webview/src/utils.js",
    "chars": 373,
    "preview": "export const vscode = acquireVsCodeApi();\n\nexport function sendMessage(text, type) {\n    vscode.postMessage({\n        ty"
  },
  {
    "path": "webview/vue.config.js",
    "chars": 279,
    "preview": "module.exports = {\n    publicPath: './', // This is required to serve build output w/o an HTTP server\n    runtimeCompile"
  }
]

// ... and 2 more files (download for full content)

About this extraction

This page contains the full source code of the karigari/vscode-chat GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 111 files (327.5 KB), approximately 78.4k tokens, and a symbol index with 393 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!