[
  {
    "path": ".gitattributes",
    "content": "# Set default behavior to automatically normalize line endings.\n* text=auto\n\n"
  },
  {
    "path": ".github/main.workflow",
    "content": "workflow \"LSIF workflow\" {\n  resolves = [\"arjun27/lsif-action@master\"]\n  on = \"push\"\n}\n\naction \"arjun27/lsif-action@master\" {\n  uses = \"arjun27/lsif-action@master\"\n}\n\nworkflow \"Testing fork builds\" {\n  on = \"pull_request\"\n  resolves = [\"post gif on fail\"]\n}\n\naction \"post gif on fail\" {\n  uses = \"arjun27/shaking-finger-action@patch-1\"\n  secrets = [\"GITHUB_TOKEN\"]\n}\n"
  },
  {
    "path": ".gitignore",
    "content": "out\nnode_modules\njspm_packages\n.vscode-test/\n.vs\n*.vsix\nstatic\ntokens\n.serverless\n.webpack\nenv.yml\n"
  },
  {
    "path": ".prettierrc",
    "content": "{\n    \"tabWidth\": 4,\n    \"printWidth\": 120\n}"
  },
  {
    "path": ".travis.yml",
    "content": "sudo: false\n\nlanguage: node_js\n\nnode_js:\n  - \"10\"\n  - \"9\"\n\nbefore_install:\n  - if [ $TRAVIS_OS_NAME == \"linux\" ]; then\n      export CXX=\"g++-4.9\" CC=\"gcc-4.9\" DISPLAY=:99.0;\n      sh -e /etc/init.d/xvfb start;\n      sleep 3;\n    fi\n\ninstall:\n  - yarn\n  - yarn run vscode:prepublish\n\nscript:\n  - yarn test\n\nnotifications:\n  slack: karigarihq:wyMAff0ihz5w5H2UKtrU2etP\n"
  },
  {
    "path": ".vscode/extensions.json",
    "content": "{\n\t// See http://go.microsoft.com/fwlink/?LinkId=827846\n\t// for the documentation about the extensions.json format\n\t\"recommendations\": [\n\t\t\"eg2.tslint\"\n\t]\n}"
  },
  {
    "path": ".vscode/launch.json",
    "content": "// A launch configuration that compiles the extension and then opens it inside a new window\n// Use IntelliSense to learn about possible attributes.\n// Hover to view descriptions of existing attributes.\n// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387\n{\n  \"version\": \"0.2.0\",\n  \"configurations\": [\n    {\n      \"name\": \"Extension\",\n      \"type\": \"extensionHost\",\n      \"request\": \"launch\",\n      \"runtimeExecutable\": \"${execPath}\",\n      \"args\": [\"--extensionDevelopmentPath=${workspaceFolder}\"],\n      \"outFiles\": [\"${workspaceFolder}/out/**/*.js\"],\n      \"preLaunchTask\": \"watch\",\n      \"env\": {\n        \"IS_DEBUG\": \"true\"\n      }\n    },\n    {\n      \"name\": \"Extension Tests\",\n      \"type\": \"extensionHost\",\n      \"request\": \"launch\",\n      \"runtimeExecutable\": \"${execPath}\",\n      \"args\": [\n        \"--extensionDevelopmentPath=${workspaceFolder}\",\n        \"--extensionTestsPath=${workspaceFolder}/out/test\"\n      ],\n      \"outFiles\": [\"${workspaceFolder}/out/test/**/*.js\"],\n      \"preLaunchTask\": \"watch\",\n      \"env\": {\n        \"IS_DEBUG\": \"true\"\n      }\n    }\n  ]\n}\n"
  },
  {
    "path": ".vscode/settings.json",
    "content": "// Place your settings in this file to overwrite default and user settings.\n{\n    \"files.exclude\": {\n        \"out\": false // set this to true to hide the \"out\" folder with the compiled JS files\n    },\n    \"search.exclude\": {\n        \"out\": true // set this to false to include \"out\" folder in search results\n    },\n    // Turn off tsc task auto detection since we have the necessary tasks as npm scripts\n    \"typescript.tsc.autoDetect\": \"off\"\n}"
  },
  {
    "path": ".vscode/tasks.json",
    "content": "// See https://go.microsoft.com/fwlink/?LinkId=733558\n// for the documentation about the tasks.json format\n{\n  \"version\": \"2.0.0\",\n  \"tasks\": [\n    {\n      \"type\": \"shell\",\n      \"label\": \"watch\",\n      \"command\": \"npm run watch\",\n      \"problemMatcher\": \"$tsc-watch\",\n      \"isBackground\": true,\n      \"presentation\": {\n        \"reveal\": \"never\"\n      },\n      \"group\": {\n        \"kind\": \"build\",\n        \"isDefault\": true\n      }\n    }\n  ]\n}\n"
  },
  {
    "path": ".vscodeignore",
    "content": ".vs/**\n.vscode/**\n.vscode-test/**\nout/test/**\nout/**/*.map\nsrc/**\n.gitignore\ntsconfig.json\ntslint.json\ntokens\noauth-service/**\noauth-service-2/**\nnode_modules/**\nreadme/**\nwebview/**\n"
  },
  {
    "path": "CHANGELOG.md",
    "content": "# Changelog\n\nAll notable changes to the Live Share Chat extension will be documented in this file. This follows the [Keep a Changelog](http://keepachangelog.com/) format.\n\n## [0.35.0] - 2020-06-13\n\nFixed\n\n-   Slack OAuth has been fixed. Since legacy tokens are deprecated, use the \"Sign in with Slack\" command to use Slack.\n\n## [0.34.0] - 2020-06-03\n\n-   This version removes the VS Live Share integration bits, which have been now added to the main VS Live Share extension.\n\n## [0.33.0] - 2020-03-23\t\t\n\n### Fixed\n\n-   Recovery build: Bringing back Live Share integration for now. Will revert the recovery build once the new version of Live Share is released.\n\n## [0.32.0] - 2020-03-22\n\n### Removed\n\n-   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.\n\n## [0.31.0] - 2019-12-19\n\n### Fixed\n\n-   Fixes to initialization for Live Share Spaces increase reliability of the experience.\n\n## [0.30.0] - 2019-12-19\n\n### Fixed\n\n-   Fixes to initialization for Live Share Chat that increase reliability of the experience.\n\n## [0.29.0] - 2019-11-06\n\n### Added\n\n-   You can type `/invite` in a Live Share DM chat to invite your contacts into a Live Share collaboration session.\n\n## [0.28.0] - 2019-10-30\n\n### Added\n\n-   Updated readme to reflect recent improvements and changes.\n\n## [0.27.1] - 2019-10-25\n\n### Fixed\n\n-   Fixed overflow styling for at-mentions suggestion list.\n\n## [0.27.0] - 2019-10-25\n\n### Added\n\n-   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!\n\n## [0.25.0] - 2019-10-18\n\n### Added\n\n-   Support for a `/clear` command that clears the message history in the current chat window.\n\n## [0.24.0] - 2019-10-17\n\n### Added\n\n-   Live Share Chat now supports typing events!\n\n## [0.23.0] - 2019-10-17\n\n### Added\n\n-   Live Share Chat now supports Direct Messages! You can DM your Live Share contacts—even outside Live Share sessions!\n\n## [0.22.1] - 2019-09-15\n\n### Fixed\n\n-   Fixed presence provider validation.\n\n## [0.22.0] - 2019-09-14\n\n### Added\n\n-   Renamed Live Share Communities provider to Live Share Spaces.\n\n## [0.21.1] - 2019-09-04\n\n### Fixed\n\n-   Fixed date to string conversion for message groups.\n\n## [0.21.0] - 2019-08-19\n\n### Fixed\n\n-   Add Live Share as an extension dependency to fix timing issues during activation\n\n## [0.20.2] - 2019-08-14\n\n### Added\n\n-   Live Share Communities: updated implementation for info messages\n\n## [0.20.0] - 2019-08-13\n\n### Added\n\n-   Live Share Communities: added support for info messages\n\n## [0.19.0] - 2019-08-12\n\n### Added\n\n-   Live Share Communities: added support to clear messages\n\n## [0.18.0] - 2019-08-11\n\n### Added\n\n-   Live Share: alert the guest if host does not have the extension installed.\n\n### Fixed\n\n-   Fixed a case where Live Share Chat was not initialized.\n\n## [0.17.1] - 2019-08-08\n\n### Added\n\n-   Render links correctly in Live Share and Live Share Communities chat.\n\n## [0.17.0] - 2019-08-07\n\n### Added\n\n-   Renamed the extension to Live Share Chat.\n\n## [0.16.3] - 2019-08-07\n\n### Fixed\n\n-   [Live Share Communities](https://github.com/vsls-contrib/communities) integration: Fix cases where current user is returned as undefined.\n-   [Live Share Communities](https://github.com/vsls-contrib/communities) integration: Fix a bug where new members were not recognised with an avatar and name.\n\n## [0.16.2] - 2019-08-04\n\n### Fixed\n\n-   [Live Share Communities](https://github.com/vsls-contrib/communities) integration: Fix presence provider and timing issues.\n\n## [0.16.1] - 2019-08-04\n\n### Added\n\n-   [Live Share Communities](https://github.com/vsls-contrib/communities) integration: Auto-launch community chat when a community is joined.\n\n## [0.16.0] - 2019-08-02\n\n### Added\n\n-   Adds integration with [Live Share Communities](https://github.com/vsls-contrib/communities).\n\n## [0.15.1] - 2019-05-12\n\n### Fixed\n\n-   Fixes unwanted notification for Slack/Discord login when installed alongside VS Live Share.\n\n## [0.15.0] - 2019-05-01\n\n### Removed\n\n-   Removed onboarding tree view that would show Slack icon when no chat backend was configured.\n\n## [0.14.0] - 2019-04-28\n\n### Added\n\n-   Faster installation and startup times with Webpack bundling.\n-   Updated setup instructions for Discord to call out potential ToS violation.\n\n## [0.13.0] - 2019-04-09\n\n### Fixed\n\n-   Fixes an issue where Live Share Chat would not work for guests on the collaboration session.\n\n## [0.12.0] - 2019-02-24\n\n### Added\n\n-   New configuration option to disable auto-launching the Live Share Chat window on a new Live Share session: `\"chat.autoLaunchLiveShareChat\": false`.\n\n## [0.11.0] - 2019-02-03\n\n### Added\n\n-   The VS Live Share chat window now shows up automatically for new VS Live Share sessions.\n\n## [0.10.0] - 2019-01-21\n\n### Added\n\n-   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.\n\n### Fixed\n\n-   Render attachments in Discord messages.\n-   Usability improvements in selecting which Slack channels should be shown.\n\n## [0.9.2] - 2019-01-04\n\n### Fixed\n\n-   \"Account is required\" errors while accessing the system keychain.\n\n## [0.9.1] - 2018-12-31\n\n### Fixed\n\n-   CPU load: Removed redundant extension activation events that were causing high CPU load.\n\n## [0.9.0] - 2018-12-16\n\n### Added\n\n-   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.\n-   Start chat over VS Live Share from the explorer view.\n\n## [0.8.2] - 2018-11-20\n\n### Fixed\n\n-   VS Live Share integration: Updated label for chat tree item.\n\n## [0.8.1] - 2018-11-20\n\n### Fixed\n\n-   Inviting online users to a Live Share session creates an IM channel with the user, if not already available.\n\n## [0.8.0] - 2018-11-18\n\n### Added\n\n-   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).\n-   VS Live Share integrations:\n    -   Show presence statuses for VS Live Share suggested contacts (for Slack and Discord)\n    -   Update your presence status from inside VS Live Share (for Slack and Discord)\n    -   Open VS Live Share chat from the VS Live Share explorer views\n\n## [0.7.4] - 2018-11-05\n\n### Fixed\n\n-   Fixed bad instantiation for users and channels state causing VS Live Share chat to not work.\n\n## [0.7.3] - 2018-10-16\n\n### Fixed\n\n-   Fixed channel loading for Slack workspaces that cross the user limit.\n\n## [0.7.2] - 2018-10-15\n\n### Fixed\n\n-   Fixed onboarding notification for Live Share users.\n\n## [0.7.1] - 2018-10-15\n\n### Added\n\n-   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.\n-   New status bar item to open the chat window during a VS Live Share session.\n-   Unread message notification and user joined/left info messages for Live Share chat.\n\n### Fixed\n\n-   Slack messages are sent over websocket, to not count towards http rate limits.\n-   Limit Slack channels to relevant channels only, by using the Slack conversations API.\n\n## [0.7.0] - 2018-10-11\n\n### Added\n\n-   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.\n\n## [0.6.3] - 2018-10-09\n\n### Added\n\n-   Added token validation for manual entry for Slack and Discord tokens.\n-   Keychain access operations can now be retried in case access is denied.\n-   Added workspace name to the status item notification.\n\n## [0.6.2] - 2018-09-28\n\n### Fixed\n\n-   Handle deactivated Slack users, and not show their direct messages and groups (thanks [Tristan Partin](https://github.com/tristan957)).\n-   Private channels are now shown under the Channels view, and not Groups.\n\n## [0.6.1] - 2018-09-22\n\n### Fixed\n\n-   Fixed migration condition for pre-0.6.x installations (thanks [ACharLuk](https://github.com/acharluk)).\n\n## [0.6.0] - 2018-09-21\n\n### Added\n\n-   Added support for Discord as a chat provider, in addition to Slack.\n-   [Breaking] Commands are now namespaced as \"Chat: ...\", instead of \"Slack: ...\".\n-   Updates to extension metadata and readme: the extension is now called Team Chat.\n\n## [0.5.11] - 2018-09-18\n\n### Added\n\n-   Added support for replying to thread messages.\n\n### Fixed\n\n-   Fixed rendering of duplicate thread replies.\n\n## [0.5.10] - 2018-09-17\n\n### Added\n\n-   Added new configuration `chat.rejectTlsUnauthorized` for self-signed certificate users (thanks [Seth Bromberger](https://github.com/sbromberger)).\n-   Load vue.js assets locally, removing dependency on the jsdelivr CDN.\n-   Upgraded Slack dependency to keep up with the network library improvements upstream.\n\n## [0.5.9] - 2018-09-04\n\n### Added\n\n-   Support for muted channels: new messages in muted channels do not update the unread count.\n-   Added support to expand thread messages to render replies, with text and file attachments.\n-   Consistency between Slack clients for unread counts: marking messages as read from other Slack clients will update the unread count.\n-   Unread messages are now highlighted in the webview.\n-   Added documentation for [product roadmap](VISION.md) and [adding chat providers](docs/PROVIDERS.md).\n\n### Fixed\n\n-   The unread count does not include alerts for users joining/leaving channels anymore.\n\n## [0.5.8] - 2018-08-31\n\n### Added\n\n-   Added support for the system keychain to store authentication tokens.\n-   Added a new command to sign out from Slack.\n\n### Fixed\n\n-   Fix handling of composition start/end events while composing messages (thanks [Yukai Huang](https://github.com/Yukaii)).\n-   Opening Slack or changing channel without authentication now prompts users to authenticate.\n\n## [0.5.7] - 2018-08-29\n\n### Added\n\n-   Added support for \"Sign in with Slack\" from the activity bar.\n\n### Fixed\n\n-   New line characters in messages are rendered correctly.\n-   Date separators show the correct month string.\n-   Fixed event source property for webview telemetry.\n\n## [0.5.6] - 2018-08-23\n\n### Added\n\n-   Slack webview font size now matches the font size of your editor.\n-   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.\n-   Added anonymized telemetry data collection; this respects the telemetry setting in your editor and you can opt-out by setting `telemetry.enableTelemetry` to false.\n\n### Fixed\n\n-   Updated user display names to be consistent with Slack clients.\n\n## [0.5.5] - 2018-08-20\n\n### Added\n\n-   Added a fallback for \"Sign in with Slack\" for situations where the system-level URI scheme handler fails.\n\n## [0.5.4] - 2018-08-18\n\n### Added\n\n-   Added \"Sign in with Slack\" for an easier onboarding experience\n\n## [0.5.3] - 2018-08-18\n\n### Fixed\n\n-   Fixed issues with duplicated state when configuration gets changed in the editor.\n-   Fixed unread message notifications for messages with files.\n\n## [0.5.2] - 2018-08-18\n\n### Fixed\n\n-   Fixed date separators computation for local time zones\n-   Fixed a race condition where loading channel message history would assign messages to an incorrect channel.\n\n## [0.5.1] - 2018-08-16\n\n### Fixed\n\n-   Fixed extension activation for the VS Live Share activity bar.\n\n## [0.5.0] - 2018-08-16\n\n### Added\n\n-   Sidebar view to show channels, private groups and direct messages.\n-   Support to show user presence (online/offline) in the sidebar view.\n-   Better integration with VS Live Share: one-click action to invite users or channels to your collaboration session.\n-   Minor improvements to extension setup for first-time users.\n\n### Fixed\n\n-   Fixed a case where the unread count would get updated incorrectly.\n\n## [0.4.10] - 2018-08-14\n\n### Added\n\n-   Slack username tags in messages are not cryptic anymore.\n-   Better keyboard-only support: pressing tab will focus the input text box, ignoring other selectable HTML elements in the webview.\n-   Added date separators on the messages UI\n\n### Fixed\n\n-   Fixed real-time UI updates for bot messages.\n-   Fixed select-all behaviour through the cmd+A keybinding (needs VS Code 1.26+).\n\n## [0.4.9] - 2018-08-13\n\n### Fixed\n\n-   Fixed issue where new messages were not getting updated on the UI.\n\n## [0.4.8] - 2018-08-09\n\n### Added\n\n-   Added support to render message reactions, and live update UI as reactions are added or removed\n-   The unread count now also reflects messages that were received before the extension gets activated, by calling the relevant Slack API.\n\n### Fixed\n\n-   Messages with files were not rendered correctly since the last Slack update. This has been fixed now.\n\n## [0.4.7] - 2018-08-08\n\n### Added\n\n-   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.\n\n## [0.4.6] - 2018-08-08\n\n### Added\n\n-   Added support for marking messages as read\n-   Improved how multi-party DM group name are shown in the UI\n\n## [0.4.5] - 2018-07-21\n\n### Added\n\n-   Added support for network connections via proxies. To setup, add the `chat.proxyUrl` configuration.\n\n## [0.4.4] - 2018-07-17\n\n### Fixed\n\n-   Fixed demo gif on the Visual Studio Marketplace\n\n## [0.4.3] - 2018-07-17\n\n### Added\n\n-   Open Travis CI logs inside the editor, with the new extensible Providers support. New providers can be create for other Slack bots and integrations.\n-   New demo gifs and examples in the README.\n\n### Fixed\n\n-   Fixed an issue where messages from a previously opened Slack channel would show up in the current view.\n\n## [0.4.2] - 2018-07-15\n\n### Fixed\n\n-   Fixed the change channel quick-pick prompt for workspaces that invite guest users.\n\n## [0.4.1] - 2018-07-06\n\n### Added\n\n-   Add a \"reload channels\" option to the channel switcher which refreshes the user/channels list from Slack API.\n\n## [0.4.0] - 2018-07-06\n\n### Added\n\n-   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.\n\n## [0.3.4] - 2018-07-04\n\n### Fixed\n\n-   Fixes a bug that showed new messages sent via the extension as blank\n\n## [0.3.3] - 2018-07-03\n\n### Added\n\n-   Support for rendering file attachments, code snippets, multi-line messages\n-   Support for rendering Slack app messages, with author, title, coloured border, and footer\n-   Support for rendering message edits and deletions\n\n### Fixed\n\n-   Fixed click behaviour for links inside messages\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/philosophy/why-not-lgpl.html>."
  },
  {
    "path": "README.md",
    "content": "<h1 align=\"center\">Chat for VS Code</h1>\n\n<h3 align=\"center\">Chat with your Slack and Discord teams from within VS Code</h3>\n\n<p align=\"center\"><img src=\"https://raw.githubusercontent.com/karigari/vscode-chat/master/readme/Live Share Chat.gif\" alt=\"Screenshot\" width=\"800\" /></p>\n\n<p align=\"center\">\n    <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>\n    <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>\n    <a href=\"https://aka.ms/vsls\"><img src=\"https://aka.ms/vsls-badge\" alt=\"Live Share enabled\" /></a>\n</p>\n\n> **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.\n> \n> The extension now only supports Slack, Discord and Live Share Spaces as chat providers.\n\n# Features\n\n- **Quiet notifications**: Chat apps can be painfully distracting. This extension emphasizes on making chat useful, contextual, and without distracting notifications.\n- **Rich formatting**: Share markdown code snippets, and add emojis to your chat messages.\n- **Native look-and-feel**: Use chat in your preferred theme and grid editor layout.\n\n<p align=\"center\">\n    <img src=\"https://raw.githubusercontent.com/karigari/vscode-chat/master/readme/feature-1-magnifier.png\" alt=\"Quiet notifications\" width=\"290\" />\n    <img src=\"https://raw.githubusercontent.com/karigari/vscode-chat/master/readme/feature-2.png\" alt=\"Rich formatting\" width=\"290\" />\n    <img src=\"https://raw.githubusercontent.com/karigari/vscode-chat/master/readme/feature-3.png\" alt=\"Theme and grid layout\" width=\"290\" />\n</p>\n\n# Get started with chat\n\n## Slack\n\nTo 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.\n\nStart 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.\n\n## Discord\n\nDiscord support is experimental. Please see [this doc](docs/DISCORD.md) to set it up.\n\n## Live Share Spaces\n\nTo 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).\n\n# Support\n\n- **Configuration settings**: To use behind a network proxy and other settings, see [CONFIGURATION](docs/CONFIG.md).\n- **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.\n\n# Developer docs\n\n- **Get started with contribution**: See [CONTRIBUTING](docs/CONTRIBUTING.md) to understand repo structure, building and testing.\n- **New chat integrations**: The implementation can be extended to support any chat provider, see [PROVIDERS](docs/PROVIDERS.md).\n- **Vision**: Read the [VISION](VISION.md) doc to understand the motivation behind this extension and the roadmap ahead.\n"
  },
  {
    "path": "VISION.md",
    "content": "# Vision\n\nThis 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.\n\nSuggestions 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).\n\n## The goal\n\nEditors 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.\n\nPersonified 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.\n\nThis 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.\n\n## Use-cases\n\nI 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.\n\nThis implies not focusing on teams that collaborate only asynchronously, such as open source projects with longer development cycles.\n\n### Sync collaboration\n\nChat 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.\n\n### Pseudo-sync collaboration\n\nEngineering 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.\n\nFor example, the following frequent tasks should take just a click:\n\n- Open a build log from your remote CI tool, and go to the failed tests in the code\n- Open a teammate's commit diff for a quick code review on chat\n- 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\n\nAnd 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.\n\n## Chat providers\n\nWhile 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.\n\n## Healthy notifications\n\nChat 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.\n"
  },
  {
    "path": "azure-pipelines.yml",
    "content": "queue:\n  name: Hosted VS2017\n\nsteps:\n  - task: NodeTool@0\n    inputs:\n      versionSpec: '10.x'\n  - script: |\n      npm install\n      npm run compile\n  - task: RichCodeNavIndexer@0\n    inputs:\n      serviceConnection: 'rich-code-nav'\n      githubServiceConnection: 'vsls-contrib'\n      languages: typescript\n"
  },
  {
    "path": "docs/CONFIG.md",
    "content": "# Configuration\n\n## Network proxy\n\nTo use this extension behind a proxy, configure the proxy url.\n\n```json\n{\n  \"chat.proxyUrl\": \"YOUR_PROXY_URL\"\n}\n```\n\n## Self-signed certificates\n\nIf you have overriding self-signed SSL certificates, you can set the `rejectTlsUnauthorized` config to false.\n\n```json\n{\n  \"chat.rejectTlsUnauthorized\": false\n}\n```\n\n## Telemetry\n\nThis 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`.\n\n```json\n{\n  \"telemetry.enableTelemetry\": false\n}\n```\n\n## Auto-launch Live Share Chat\n\nBy default, the extension auto-launches the Live Share Chat window every time a new Live Share session is started. This behaviour can be disabled:\n\n```json\n{\n  \"chat.autoLaunchLiveShareChat\": false\n}\n```\n"
  },
  {
    "path": "docs/CONTRIBUTING.md",
    "content": "# Contributing\n\nThe 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.\n\nIf you want to work on something, just create a discussion thread (on PRs/issues) and we will help you get started.\n\n## Repo structure\n\nThe repo has three parts:\n\n1. Main extension code in TypeScript, in `src/**`\n2. Webview UI code, written with Vue.js, in `src/webview/**`\n3. OAuth service, built with the Serverless framework, in `oauth-service/**`\n\n## Building\n\nOpen 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.\n\nWhen 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.\n\n## Known issue\n\nThe 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.\n\n## Styling\n\nThe code is styled with [Prettier](https://prettier.io).\n\n## Tests\n\n`npm run test`\n\nTests can only be run when VS Code is not running. If you want to run tests alongside development, use VS Code Insiders for development.\n"
  },
  {
    "path": "docs/DISCORD.md",
    "content": "# Discord Setup\n\n## Warning\n\nThe 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.\n\nThe 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.\n\nIf you have any suggestions to improve this flow, please [create an issue](https://github.com/karigari/vscode-chat/issues).\n\n## Obtaining the token\n\nTo 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).\n\nThis 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):\n\n> 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.\n\n## Configuring the token\n\nOnce you have the token, run the following commands from the VS Code command palette:\n\n1. 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.\n\n2. 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.\n"
  },
  {
    "path": "docs/PROVIDERS.md",
    "content": "# Chat providers\n\nThe 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`.\n\nFor reference, see the implementation [for Slack](src/slack/index.ts) and [for Discord](src/discord/index.ts).\n\n## Supported features\n\nThe extension supports the following features for Slack. Other chat providers can implement one or more features, depending on their API.\n\n1. [Authentication](#authentication): Users can sign in with chat provider's OAuth\n2. [Messaging](#messaging): Users can open a chat channel in a webview, and then send and receive messages\n3. [Channels list](#channels-list): Users can see the list of public channels, direct messages and private groups (with unread counts) in the tree view\n4. [Unreads](#unreads): Users can see the unread count in the status bar\n5. [Presence](#presence): Users can see other online users in the Live Share tree view (requires VS Live Share)\n6. [Collaboration invites](#collaboration-invites): Users can invite users or channels for a Live Share collaboration session (requires VS Live Share)\n\n## Authentication\n\nSlack 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.\n\nRequirements for providers\n\n- Provide a \"Sign in with X\" link to launch OAuth flow\n- Auth flow should return a token string that can be saved to system keychain\n\n## Messaging\n\nIn 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.\n\nRequirements for providers\n\n- API support to receive messages in real-time (Slack uses websocket)\n- API support to send messages, as the authenticated user (not a bot)\n- Optionally: thread replies, emoji reactions, file attachments\n\n## Channels list\n\nSlack 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.\n\nRequirements for providers\n\n- API support to fetch channels and users\n\n## Unreads\n\nThe unread count can be historical (unread messages before user comes online) and in real-time (new messages when the user is online).\n\nRequirements for providers\n\n- Historical unreads: API support to return unread count for every channel\n- Real-time unreads: The real-time messaging API can be used to update a running unread count for new messages\n- API support to mark messages as read (which takes the count to 0)\n- If the provider has other clients, then the API should support real-time updates to maintain unread count consistent with the other clients.\n\n## Presence\n\nUser 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.\n\nRequirements for providers\n\n- API support for real-time support for user presence updates\n\n## Collaboration invites\n\nTo start a VS Live Share collaboration session, the extension supports one-click collaboration invites. The requirements for this are similar to the messaging feature.\n\nRequirements for providers\n\n- API support to receive real-time messages in the background\n- API support to send messages\n"
  },
  {
    "path": "docs/SLACK.md",
    "content": "# Slack authorization\n\nMany users have reported running into `access_denied` issues on Slack, and this doc attempts to list potential solutions to the problem.\n\nIn case you have questions about permission levels or what this extension accesses, please report an issue with your question.\n\n## Admin approval required\n\nSome workspaces require an explicit admin approval before users can install specific apps.\n\nIf your workspace needs this, please forward [this link](https://slack.com/apps/ACB4LQKN1-slack-chat-for-vs-code) to your workspace admins.\n\n## Slack App Directory\n\nSome 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).\n\nFor 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.\n\n## Free workspace app limit\n\nIf 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.\n"
  },
  {
    "path": "oauth-service/README.md",
    "content": "# oauth-service\n\nThis is a serverless app to handle OAuth redirection for the Slack Chat extension, and it is deployed on AWS Lambda.\n\nTo deploy a new version of this service, run\n\n```\nserverless deploy --verbose\n```\n\nTo test this service locally, run\n\n```\nserverless offline start\n```\n\nThis service requires the `env.yml` file with the SLACK_CLIENT_ID and SLACK_CLIENT_SECRET keys.\n\n## Custom domain\n\nThe 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.\n\nThe following command needs to run before a new deploy if there are any changes to the yml, wrt function route definitions.\n\n```\nserverless create_domain\n```\n"
  },
  {
    "path": "oauth-service/handler.ts",
    "content": "import { APIGatewayEvent, Callback, Context, Handler } from \"aws-lambda\";\nimport * as request from \"request-promise-native\";\nimport {\n  parseQueryParams,\n  getIssueUrl,\n  getRedirect,\n  getRedirectError\n} from \"./utils\";\nimport errorHtml from \"./html/error.template.html\";\nimport successHtml from \"./html/success.template.html\";\nimport homeHtml from \"./html/home.template.html\";\n\ninterface TokenAPIResponse {\n  accessToken: string;\n  teamId?: string;\n  expiresIn?: Date;\n  refreshToken?: string;\n  error: string;\n}\n\nconst getSlackToken = async (code: string): Promise<TokenAPIResponse> => {\n  const uri = \"https://slack.com/api/oauth.access\";\n  var options = {\n    uri,\n    json: true,\n    qs: {\n      client_id: process.env.SLACK_CLIENT_ID,\n      client_secret: process.env.SLACK_CLIENT_SECRET,\n      code,\n      // When testing locally, pass the redirect_uri to slack\n      // redirect_uri: \"http://localhost:3000/slack_redirect\"\n    }\n  };\n\n  const result = await request.get(options);\n  const { ok, error, access_token, team_id } = result;\n\n  if (!ok) {\n    return { accessToken: null, error };\n  } else {\n    return { accessToken: access_token, teamId: team_id, error: null };\n  }\n};\n\nconst getDiscordToken = async (code: string): Promise<TokenAPIResponse> => {\n  const uri = \"https://discordapp.com/api/v6/oauth2/token\";\n  var options = {\n    uri,\n    method: \"POST\",\n    formData: {\n      client_id: process.env.DISCORD_CLIENT_ID,\n      client_secret: process.env.DISCORD_CLIENT_SECRET,\n      grant_type: \"authorization_code\",\n      code\n    }\n  };\n\n  try {\n    const result = await request.post(options);\n    const parsed = JSON.parse(result);\n    var t = new Date();\n    t.setSeconds(t.getSeconds() + parsed.expires_in);\n    return {\n      accessToken: parsed.access_token,\n      expiresIn: t,\n      refreshToken: parsed.refresh_token,\n      error: null\n    };\n  } catch (error) {\n    return { accessToken: null, error: error.message };\n  }\n};\n\nconst renderSuccess = (\n  token: string,\n  service: string,\n  teamId: string,\n  cb: Callback\n) => {\n  const redirect = getRedirect(token, service, teamId);\n  const response = {\n    statusCode: 200,\n    headers: {\n      \"Content-Type\": \"text/html\"\n    },\n    body: successHtml\n      .replace(/{{redirect}}/g, redirect)\n      .replace(/{{token}}/g, token)\n  };\n  cb(null, response);\n};\n\nconst renderError = (error: string, service: string, cb: Callback) => {\n  const issueUrl = getIssueUrl(error, service);\n  const redirect = getRedirectError(error, service);\n  const response = {\n    statusCode: 200,\n    headers: {\n      \"Content-Type\": \"text/html\"\n    },\n    body: errorHtml\n      .replace(/{{error}}/g, error)\n      .replace(/{{redirect}}/g, redirect)\n      .replace(/{{issues}}/g, issueUrl)\n  };\n  cb(null, response);\n};\n\nexport const slackRedirect: Handler = (\n  event: APIGatewayEvent,\n  context: Context,\n  cb: Callback\n) => {\n  const { error, code } = parseQueryParams(event);\n\n  if (!!code) {\n    const tokenPromise = getSlackToken(code);\n    tokenPromise.then(result => {\n      const { accessToken, error, teamId } = result;\n\n      if (!accessToken) {\n        renderError(error, \"slack\", cb);\n      } else {\n        renderSuccess(accessToken, \"slack\", teamId, cb);\n      }\n    });\n  }\n\n  if (!!error) {\n    renderError(error, \"slack\", cb);\n  }\n};\n\nexport const discordRedirect: Handler = (\n  event: APIGatewayEvent,\n  context: Context,\n  cb: Callback\n) => {\n  const { error, code } = parseQueryParams(event);\n\n  if (!!code) {\n    const tokenPromise = getDiscordToken(code);\n    tokenPromise.then(result => {\n      const { accessToken, error } = result;\n\n      if (!accessToken) {\n        renderError(error, \"discord\", cb);\n      } else {\n        renderSuccess(accessToken, \"discord\", \"team-id\", cb);\n      }\n    });\n  }\n\n  if (!!error) {\n    renderError(error, \"discord\", cb);\n  }\n};\n\nexport const home: Handler = (\n  event: APIGatewayEvent,\n  context: Context,\n  cb: Callback\n) => {\n  const response = {\n    statusCode: 200,\n    headers: {\n      \"Content-Type\": \"text/html\"\n    },\n    body: homeHtml\n  };\n  cb(null, response);\n};\n"
  },
  {
    "path": "oauth-service/html/error.template.html",
    "content": "<!doctype html>\n<html lang=\"en\">\n\n<head>\n    <!-- Required meta tags -->\n    <meta charset=\"utf-8\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n\n    <!-- Bootstrap CSS -->\n    <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" integrity=\"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\"\n        crossorigin=\"anonymous\">\n\n    <title>Slack Chat for VS Code</title>\n</head>\n\n<body>\n    <iframe width=\"0\" height=\"0\" src=\"{{redirect}}\"></iframe>\n    <div class=\"container my-4 text-center\">\n        <p>We have run into an error: <strong>{{error}}</strong></p>\n        <p>If this is not right, please <a href=\"{{issues}}\">report an issue</a></p>\n    </div>\n</body>\n\n</html>"
  },
  {
    "path": "oauth-service/html/home.template.html",
    "content": "<!doctype html>\n<html lang=\"en\">\n\n<head>\n    <!-- Required meta tags -->\n    <meta charset=\"utf-8\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n\n    <!-- Bootstrap CSS -->\n    <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" integrity=\"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\"\n        crossorigin=\"anonymous\">\n\n    <title>Slack Chat for VS Code</title>\n</head>\n\n<body>\n    <div class=\"container my-4 text-center\">\n        <div class=\"my-4\">\n            <img src=\"https://raw.githubusercontent.com/karigari/vscode-chat/master/readme/preview.png\" />\n        </div>\n\n        <div class=\"my-4\">\n            <img src=\"https://vsmarketplacebadge.apphb.com/installs/karigari.chat.svg\" />\n            <img src=\"https://img.shields.io/vscode-marketplace/r/karigari.chat.svg\" />\n        </div>\n\n        <div class=\"my-4\">\n            <a href=\"https://github.com/karigari/vscode-chat\">View Source</a> &#183; <a href=\"https://marketplace.visualstudio.com/items?itemName=karigari.chat\">Install\n                in VS Code</a>\n        </div>\n\n        <div class=\"my-4 alert alert-info\" role=\"alert\">\n            <h5 class=\"alert-heading\">Are you a Slack admin?</h5>\n            <div><a href=\"https://slack.com/apps/ACB4LQKN1-slack-chat-for-vs-code\">Approve for your workspace\n                </a></div>\n        </div>\n\n        <div class=\"my-4 small\">\n            <a href=\"https://github.com/karigari/vscode-chat/issues/new\">Support</a>\n        </div>\n    </div>\n</body>\n\n</html>"
  },
  {
    "path": "oauth-service/html/success.template.html",
    "content": "<!doctype html>\n<html lang=\"en\">\n\n<head>\n    <!-- Required meta tags -->\n    <meta charset=\"utf-8\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n\n    <!-- Bootstrap CSS -->\n    <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" integrity=\"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\"\n        crossorigin=\"anonymous\">\n\n    <title>Slack Chat for VS Code</title>\n</head>\n\n<body>\n    <iframe width=\"0\" height=\"0\" src=\"{{redirect}}\"></iframe>\n    <div class=\"container my-4 text-center\">\n        <p class=\"h3\">Redirecting to VS Code...</p>\n        <p class=\"my-4\">Unable to redirect? Configure manually.</p>\n        <div class=\"modal-dialog text-left\">\n            <div class=\"modal-content\">\n                <div class=\"modal-title\">\n                    <div class=\"d-flex align-items-center justify-content-center m-3\">\n                        <code id=\"code-token\" style=\"height: 0; width: 1px; opacity: 0;\">{{token}}</code>\n                        <button type=\"button\" class=\"btn btn-secondary btn-sm mx-2\" onclick=\"runCopy()\" id=\"copy-button\">Copy\n                            token\n                        </button>\n                    </div>\n                </div>\n                <div class=\"modal-body\">\n                    <ol>\n                        <li class=\"my-1\">Copy the token to clipboard.</li>\n                        <li class=\"my-1\">Inside VS Code, open the Command Palette.</li>\n                        <li class=\"my-1\">Pick <strong>Chat: Configure Slack Access Token</strong>.</li>\n                        <li class=\"my-1\">Paste the token.</li>\n                    </ol>\n                </div>\n            </div>\n        </div>\n        <p><a href=\"https://github.com/karigari/vscode-chat/issues\">Report an issue</a></p>\n    </div>\n</body>\n\n<script type=\"text/javascript\">\n    function runCopy() {\n        var code = document.getElementById(\"code-token\")\n        var range = document.createRange();\n        range.selectNode(code);\n        window.getSelection().removeAllRanges();\n        window.getSelection().addRange(range);\n        var button = document.getElementById('copy-button')\n        try {\n            document.execCommand(\"copy\");\n            button.textContent = \"Copied!\"\n        } catch (err) {\n            button.textContent = \"Failed to copy\"\n        }\n    }\n</script>\n\n</html>"
  },
  {
    "path": "oauth-service/html.d.ts",
    "content": "declare module \"*.html\" {\n  const value: string;\n  export default value;\n}\n"
  },
  {
    "path": "oauth-service/package.json",
    "content": "{\n  \"name\": \"vscode-chat-oauth-service\",\n  \"description\": \"Serverless app to handle Slack OAuth for vscode-chat\",\n  \"version\": \"1.0.0\",\n  \"main\": \"handler.js\",\n  \"scripts\": {\n    \"start\": \"npx serverless offline start\"\n  },\n  \"dependencies\": {\n    \"request\": \"^2.88.0\",\n    \"request-promise-native\": \"^1.0.5\",\n    \"source-map-support\": \"^0.5.0\"\n  },\n  \"devDependencies\": {\n    \"@types/aws-lambda\": \"8.10.1\",\n    \"@types/node\": \"^8.0.57\",\n    \"html-loader\": \"^0.5.5\",\n    \"serverless-domain-manager\": \"^2.6.0\",\n    \"serverless-offline\": \"^3.25.8\",\n    \"serverless-webpack\": \"^5.1.1\",\n    \"ts-loader\": \"^4.2.0\",\n    \"typescript\": \"^2.8.1\",\n    \"webpack\": \"^4.5.0\"\n  }\n}\n"
  },
  {
    "path": "oauth-service/serverless.yml",
    "content": "service:\n  name: vscode-chat-oauth-service\n\nplugins:\n  - serverless-webpack\n  - serverless-offline\n  - serverless-domain-manager\n\nprovider:\n  name: aws\n  runtime: nodejs8.10\n  environment: ${file(./env.yml):${opt:stage, self:provider.stage}}\n\nfunctions:\n  slack-redirect:\n    handler: handler.slackRedirect\n    timeout: 10\n    events:\n      - http:\n          method: get\n          path: slack_redirect\n  discord-redirect:\n    handler: handler.discordRedirect\n    timeout: 10\n    events:\n      - http:\n          method: get\n          path: discord_redirect\n  home:\n    handler: handler.home\n    events:\n      - http:\n          method: get\n          path: /\n\ncustom:\n  customDomain:\n    domainName: vscode.chat\n    certificateArn: arn:aws:acm:us-east-1:750374355341:certificate/dd3d7f2f-e25f-46b9-8cad-93784e9b2e9b\n    stage: ${self:provider.stage}\n    createRoute53Record: true\n"
  },
  {
    "path": "oauth-service/source-map-install.js",
    "content": "require('source-map-support').install();\n"
  },
  {
    "path": "oauth-service/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"sourceMap\": true,\n    \"target\": \"es6\",\n    \"lib\": [\n      \"esnext\"\n    ],\n    \"moduleResolution\": \"node\"\n  },\n  \"exclude\": [\n    \"node_modules\"\n  ]\n}\n"
  },
  {
    "path": "oauth-service/utils.ts",
    "content": "import { APIGatewayEvent } from \"aws-lambda\";\n\nexport const parseQueryParams = (event: APIGatewayEvent) => {\n  const { queryStringParameters } = event;\n  let error, code;\n\n  if (!!queryStringParameters) {\n    code = queryStringParameters.code;\n    error = queryStringParameters.error;\n  } else {\n    error = \"no_code_param\";\n  }\n\n  return { code, error };\n};\n\nexport const getIssueUrl = (errorMessage: string, serviceName: string) => {\n  const encode = encodeURIComponent;\n  const title = `[oauth-service] Sign in with ${serviceName} failed: ${errorMessage}`;\n  const body = `- Extension version:\\n- VS Code version:`;\n  const baseUrl = \"https://github.com/karigari/vscode-chat/issues/new/\";\n  return `${baseUrl}?title=${encode(title)}&body=${encode(body)}`;\n};\n\nexport const getRedirect = (token: string, service: string, team: string) => {\n  return `vscode://karigari.chat/redirect?token=${token}&service=${service}&team=${team}`;\n};\n\nexport const getRedirectError = (errorMessage: string, serviceName: string) => {\n  return `vscode://karigari.chat/error?msg=${errorMessage}&service=${serviceName}`;\n};\n"
  },
  {
    "path": "oauth-service/webpack.config.js",
    "content": "const path = require(\"path\");\nconst slsw = require(\"serverless-webpack\");\n\nconst entries = {};\n\nObject.keys(slsw.lib.entries).forEach(\n  key => (entries[key] = [\"./source-map-install.js\", slsw.lib.entries[key]])\n);\n\nmodule.exports = {\n  mode: slsw.lib.webpack.isLocal ? \"development\" : \"production\",\n  entry: entries,\n  devtool: \"source-map\",\n  resolve: {\n    extensions: [\".js\", \".jsx\", \".json\", \".ts\", \".tsx\", \".html\"]\n  },\n  output: {\n    libraryTarget: \"commonjs\",\n    path: path.join(__dirname, \".webpack\"),\n    filename: \"[name].js\"\n  },\n  target: \"node\",\n  module: {\n    rules: [\n      { test: /\\.tsx?$/, loader: \"ts-loader\" },\n      { test: /\\.html$/, loader: \"html-loader\" }\n    ]\n  }\n};\n"
  },
  {
    "path": "oauth-service-2/.gcloudignore",
    "content": "# This file specifies files that are *not* uploaded to Google Cloud Platform\n# using gcloud. It follows the same syntax as .gitignore, with the addition of\n# \"#!include\" directives (which insert the entries of the given .gitignore-style\n# file at that point).\n#\n# For more information, run:\n#   $ gcloud topic gcloudignore\n#\n.gcloudignore\n# If you would like to upload your .git directory, .gitignore file or files\n# from your .gitignore file, remove the corresponding line\n# below:\n.git\n.gitignore\n\nnode_modules\n"
  },
  {
    "path": "oauth-service-2/README.md",
    "content": "# Oauth redirection service\n\n## Running locally\n\n```\nnpm start\n```\n\n## Deployment\n\n```\ngcloud functions deploy slackRedirect --set-env-vars SLACK_CLIENT_ID=<VALUE>,SLACK_CLIENT_SECRET=<VALUE> --runtime nodejs10 --trigger-http\n```\n"
  },
  {
    "path": "oauth-service-2/htmls.js",
    "content": "exports.success = `\n<!doctype html>\n<html lang=\"en\">\n\n<head>\n    <!-- Required meta tags -->\n    <meta charset=\"utf-8\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n\n    <!-- Bootstrap CSS -->\n    <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" integrity=\"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\"\n        crossorigin=\"anonymous\">\n\n    <title>Slack Chat for VS Code</title>\n</head>\n\n<body>\n    <iframe width=\"0\" height=\"0\" src=\"{{redirect}}\"></iframe>\n    <div class=\"container my-4 text-center\">\n        <p class=\"h3\">Redirecting to VS Code...</p>\n        <p class=\"my-4\">Unable to redirect? Configure manually.</p>\n        <div class=\"modal-dialog text-left\">\n            <div class=\"modal-content\">\n                <div class=\"modal-title\">\n                    <div class=\"d-flex align-items-center justify-content-center m-3\">\n                        <code id=\"code-token\" style=\"height: 0; width: 1px; opacity: 0;\">{{token}}</code>\n                        <button type=\"button\" class=\"btn btn-secondary btn-sm mx-2\" onclick=\"runCopy()\" id=\"copy-button\">Copy\n                            token\n                        </button>\n                    </div>\n                </div>\n                <div class=\"modal-body\">\n                    <ol>\n                        <li class=\"my-1\">Copy the token to clipboard.</li>\n                        <li class=\"my-1\">Inside VS Code, open the Command Palette.</li>\n                        <li class=\"my-1\">Pick <strong>Chat: Configure Slack Access Token</strong>.</li>\n                        <li class=\"my-1\">Paste the token.</li>\n                    </ol>\n                </div>\n            </div>\n        </div>\n        <p><a href=\"https://github.com/karigari/vscode-chat/issues\">Report an issue</a></p>\n    </div>\n</body>\n\n<script type=\"text/javascript\">\n    function runCopy() {\n        var code = document.getElementById(\"code-token\")\n        var range = document.createRange();\n        range.selectNode(code);\n        window.getSelection().removeAllRanges();\n        window.getSelection().addRange(range);\n        var button = document.getElementById('copy-button')\n        try {\n            document.execCommand(\"copy\");\n            button.textContent = \"Copied!\"\n        } catch (err) {\n            button.textContent = \"Failed to copy\"\n        }\n    }\n</script>\n\n</html>\n`\n\nexports.error = `\n<!doctype html>\n<html lang=\"en\">\n\n<head>\n    <!-- Required meta tags -->\n    <meta charset=\"utf-8\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n\n    <!-- Bootstrap CSS -->\n    <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" integrity=\"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\"\n        crossorigin=\"anonymous\">\n\n    <title>Slack Chat for VS Code</title>\n</head>\n\n<body>\n    <iframe width=\"0\" height=\"0\" src=\"{{redirect}}\"></iframe>\n    <div class=\"container my-4 text-center\">\n        <p>We have run into an error: <strong>{{error}}</strong></p>\n        <p>If this is not right, please <a href=\"{{issues}}\">report an issue</a></p>\n    </div>\n</body>\n\n</html>\n`"
  },
  {
    "path": "oauth-service-2/index.js",
    "content": "//@ts-check\nconst utils = require('./utils');\nconst htmls = require('./htmls');\nconst request = require('request-promise-native');\n\nasync function getSlackToken(code) {\n  const uri = \"https://slack.com/api/oauth.access\";\n  var options = {\n    uri,\n    json: true,\n    qs: {\n      client_id: process.env.SLACK_CLIENT_ID,\n      client_secret: process.env.SLACK_CLIENT_SECRET,\n      code,\n      // When testing locally, pass the redirect_uri to slack\n      redirect_uri: \"https://us-central1-eco-theater-119616.cloudfunctions.net/slackRedirect\"\n    }\n  };\n\n  const result = await request.get(options);\n  const { ok, error, access_token, team_id } = result;\n\n  if (!ok) {\n    return { accessToken: null, error };\n  } else {\n    return { accessToken: access_token, teamId: team_id, error: null };\n  }\n}\n\nconst renderSuccess = (token, service, teamId, response) => {\n  const redirect = utils.redirectUrl(token, service, teamId);\n  response.set('Content-Type', 'text/html');\n  response.status(200).send(\n    htmls.success\n      .replace(/{{redirect}}/g, redirect)\n      .replace(/{{token}}/g, token)\n  );\n};\n\nconst renderError = (error, service, response) => {\n  const issueUrl = utils.issueUrl(error, service);\n  const redirect = utils.redirectError(error, service);\n  response.set('Content-Type', 'text/html');\n  response.status(200).send(\n    htmls.error\n      .replace(/{{error}}/g, error)\n      .replace(/{{redirect}}/g, redirect)\n      .replace(/{{issues}}/g, issueUrl)\n  );\n};\n\nexports.slackRedirect = async (req, res) => {\n  const { error, code } = req.query;\n  if (!!code) {\n    const tokenPromise = getSlackToken(code);\n    tokenPromise.then(result => {\n      const { accessToken, error, teamId } = result;\n\n      if (!accessToken) {\n        renderError(error, \"slack\", res);\n      } else {\n        renderSuccess(accessToken, \"slack\", teamId, res);\n      }\n    });\n  } else {\n    renderError(error, \"slack\", res);\n  }\n};"
  },
  {
    "path": "oauth-service-2/package.json",
    "content": "{\n  \"name\": \"oauth-service-2\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"index.js\",\n  \"scripts\": {\n    \"start\": \"functions-framework --target=slackRedirect\"\n  },\n  \"author\": \"\",\n  \"license\": \"ISC\",\n  \"devDependencies\": {\n    \"@google-cloud/functions-framework\": \"^1.5.1\"\n  },\n  \"dependencies\": {\n    \"request\": \"^2.88.2\",\n    \"request-promise-native\": \"^1.0.8\"\n  }\n}\n"
  },
  {
    "path": "oauth-service-2/utils.js",
    "content": "exports.redirectUrl = (token, service, team) => {\n  return `vscode://karigari.chat/redirect?token=${token}&service=${service}&team=${team}`;\n}\n\nexports.issueUrl = (errorMessage, serviceName) => {\n  const encode = encodeURIComponent;\n  const title = `[oauth-service] Sign in with ${serviceName} failed: ${errorMessage}`;\n  const body = `- Extension version:\\n- VS Code version:`;\n  const baseUrl = \"https://github.com/karigari/vscode-chat/issues/new/\";\n  return `${baseUrl}?title=${encode(title)}&body=${encode(body)}`;\n};\n\nexports.redirectError = (errorMessage, serviceName) => {\n  return `vscode://karigari.chat/error?msg=${errorMessage}&service=${serviceName}`;\n};\n"
  },
  {
    "path": "package.json",
    "content": "{\n    \"name\": \"chat\",\n    \"displayName\": \"Chat\",\n    \"description\": \"Chat with your Slack and Discord teams from within VS Code\",\n    \"version\": \"0.35.0\",\n    \"homepage\": \"https://github.com/vsls-contrib/chat\",\n    \"license\": \"SEE LICENSE IN LICENSE\",\n    \"repository\": {\n        \"type\": \"git\",\n        \"url\": \"https://github.com/vsls-contrib/chat.git\"\n    },\n    \"bugs\": {\n        \"url\": \"https://github.com/vsls-contrib/chat/issues\"\n    },\n    \"publisher\": \"karigari\",\n    \"engines\": {\n        \"vscode\": \"^1.26.0\"\n    },\n    \"icon\": \"public/icon.png\",\n    \"galleryBanner\": {\n        \"color\": \"#233f6c\",\n        \"theme\": \"dark\"\n    },\n    \"categories\": [\n        \"Other\"\n    ],\n    \"keywords\": [\n        \"slack\",\n        \"discord\",\n        \"collaboration\",\n        \"chat\",\n        \"live\"\n    ],\n    \"activationEvents\": [\n        \"*\"\n    ],\n    \"main\": \"./out/extension\",\n    \"contributes\": {\n        \"configuration\": {\n            \"type\": \"object\",\n            \"title\": \"Team Chat\",\n            \"properties\": {\n                \"chat.slack.legacyToken\": {\n                    \"type\": \"string\",\n                    \"default\": null,\n                    \"description\": \"[Deprecated] Run the \\\"Sign In with Slack\\\" command instead.\"\n                },\n                \"chat.proxyUrl\": {\n                    \"type\": \"string\",\n                    \"default\": null,\n                    \"description\": \"Proxy URL for network connections to the Slack http/websocket requests.\"\n                },\n                \"chat.rejectTlsUnauthorized\": {\n                    \"type\": \"boolean\",\n                    \"default\": true,\n                    \"description\": \"Set this to false to accept unauthorized SSL connections. Defaults to true.\"\n                },\n                \"chat.providers\": {\n                    \"type\": \"array\",\n                    \"default\": null,\n                    \"description\": \"[Experimental] Open bot links inside VS Code. For travis-ci.org, set configuration [\\\"travis\\\"].\"\n                },\n                \"chat.autoLaunchLiveShareChat\": {\n                    \"type\": \"boolean\",\n                    \"default\": true,\n                    \"description\": \"If enabled, the Live Share Chat window will auto-launch when a collaboration session is started.\"\n                }\n            }\n        },\n        \"commands\": [\n            {\n                \"command\": \"extension.chat.openChatPanel\",\n                \"title\": \"Open\",\n                \"category\": \"Chat\"\n            },\n            {\n                \"command\": \"extension.chat.changeChannel\",\n                \"title\": \"Change Channel\",\n                \"category\": \"Chat\",\n                \"icon\": {\n                    \"light\": \"public/icons/light/search.svg\",\n                    \"dark\": \"public/icons/dark/search.svg\"\n                }\n            },\n            {\n                \"command\": \"extension.chat.changeWorkspace\",\n                \"title\": \"Change Workspace\",\n                \"category\": \"Chat\"\n            },\n            {\n                \"command\": \"extension.chat.authenticate\",\n                \"title\": \"Sign In with Slack\",\n                \"category\": \"Chat\"\n            },\n            {\n                \"command\": \"extension.chat.signout\",\n                \"title\": \"Sign Out\",\n                \"category\": \"Chat\"\n            },\n            {\n                \"command\": \"extension.chat.configureToken\",\n                \"title\": \"Configure Access Token\",\n                \"category\": \"Chat\"\n            },\n            {\n                \"command\": \"extension.chat.updateSelfPresence\",\n                \"title\": \"Update your presence status\",\n                \"category\": \"Chat\"\n            },\n            {\n                \"command\": \"extension.chat.startLiveShare\",\n                \"title\": \"Invite to Live Share\",\n                \"category\": \"Chat\",\n                \"icon\": {\n                    \"light\": \"public/icons/light/share.svg\",\n                    \"dark\": \"public/icons/dark/share.svg\"\n                }\n            },\n            {\n                \"command\": \"extension.chat.chatWithSpace\",\n                \"title\": \"Open Chat\",\n                \"category\": \"Chat\",\n                \"icon\": {\n                    \"light\": \"public/icons/light/chat.svg\",\n                    \"dark\": \"public/icons/dark/chat.svg\"\n                }\n            }\n        ],\n        \"views\": {\n            \"chatActivityViewSlack\": [\n                {\n                    \"id\": \"chat.treeView.workspaces.slack\",\n                    \"name\": \"Workspaces\",\n                    \"when\": \"chat:slack\"\n                },\n                {\n                    \"id\": \"chat.treeView.unreads.slack\",\n                    \"name\": \"Unreads\",\n                    \"when\": \"chat:slack\"\n                },\n                {\n                    \"id\": \"chat.treeView.channels.slack\",\n                    \"name\": \"Channels\",\n                    \"when\": \"chat:slack\"\n                },\n                {\n                    \"id\": \"chat.treeView.groups.slack\",\n                    \"name\": \"Groups\",\n                    \"when\": \"chat:slack\"\n                },\n                {\n                    \"id\": \"chat.treeView.ims.slack\",\n                    \"name\": \"Direct Messages\",\n                    \"when\": \"chat:slack\"\n                }\n            ],\n            \"chatActivityViewDiscord\": [\n                {\n                    \"id\": \"chat.treeView.workspaces.discord\",\n                    \"name\": \"Workspaces\",\n                    \"when\": \"chat:discord\"\n                },\n                {\n                    \"id\": \"chat.treeView.unreads.discord\",\n                    \"name\": \"Unreads\",\n                    \"when\": \"chat:discord\"\n                },\n                {\n                    \"id\": \"chat.treeView.channels.discord\",\n                    \"name\": \"Channels\",\n                    \"when\": \"chat:discord\"\n                },\n                {\n                    \"id\": \"chat.treeView.groups.discord\",\n                    \"name\": \"Groups\",\n                    \"when\": \"chat:discord\"\n                },\n                {\n                    \"id\": \"chat.treeView.ims.discord\",\n                    \"name\": \"Direct Messages\",\n                    \"when\": \"chat:discord\"\n                }\n            ]\n        },\n        \"viewsContainers\": {\n            \"activitybar\": [\n                {\n                    \"id\": \"chatActivityViewSlack\",\n                    \"title\": \"Slack\",\n                    \"icon\": \"public/icons/activity-bar-slack-icon.svg\",\n                    \"when\": \"chat:slack\"\n                },\n                {\n                    \"id\": \"chatActivityViewDiscord\",\n                    \"title\": \"Discord\",\n                    \"icon\": \"public/icons/activity-bar-discord-icon.svg\",\n                    \"when\": \"chat:discord\"\n                }\n            ]\n        },\n        \"menus\": {\n            \"view/item/context\": [\n                {\n                    \"command\": \"extension.chat.startLiveShare\",\n                    \"when\": \"chat:vslsEnabled && viewItem == channel\",\n                    \"group\": \"inline\"\n                },\n                {\n                    \"command\": \"extension.chat.chatWithSpace\",\n                    \"when\": \"view == liveshare.spaces && viewItem =~ /^space/\",\n                    \"group\": \"chat@1\"\n                },\n                {\n                    \"command\": \"extension.chat.chatWithSpace\",\n                    \"when\": \"view == liveshare.spaces && viewItem =~ /^space/\",\n                    \"group\": \"inline@1\"\n                }\n            ],\n            \"view/title\": [\n                {\n                    \"command\": \"extension.chat.changeChannel\",\n                    \"when\": \"view =~ /^chat.treeView(?!.onboarding)/\",\n                    \"group\": \"navigation@1\"\n                }\n            ],\n            \"commandPalette\": [\n                {\n                    \"command\": \"extension.chat.openChatPanel\",\n                    \"when\": \"false\"\n                },\n                {\n                    \"command\": \"extension.chat.updateSelfPresence\",\n                    \"when\": \"false\"\n                },\n                {\n                    \"command\": \"extension.chat.startLiveShare\",\n                    \"when\": \"false\"\n                },\n                {\n                    \"command\": \"extension.chat.chatWithSpace\",\n                    \"when\": \"false\"\n                }\n            ]\n        }\n    },\n    \"scripts\": {\n        \"compile\": \"webpack\",\n        \"compile:tsc\": \"tsc -p ./\",\n        \"postcompile\": \"npm run webview\",\n        \"watch\": \"tsc-watch -p ./\",\n        \"postinstall\": \"node ./node_modules/vscode/bin/install\",\n        \"test\": \"npm run compile:tsc && node ./node_modules/vscode/bin/test\",\n        \"webview\": \"cd webview && npm run build\",\n        \"vscode:prepublish\": \"npm run compile\"\n    },\n    \"devDependencies\": {\n        \"@types/http-proxy-agent\": \"^2.0.0\",\n        \"@types/keytar\": \"^4.0.1\",\n        \"@types/markdown-it\": \"^0.0.7\",\n        \"@types/mixpanel\": \"^2.14.0\",\n        \"@types/mocha\": \"^2.2.42\",\n        \"@types/node\": \"*\",\n        \"@types/request-promise-native\": \"^1.0.15\",\n        \"@types/semver\": \"^5.5.0\",\n        \"@types/webpack\": \"^4.4.10\",\n        \"native-modules\": \"^1.1.0\",\n        \"shx\": \"^0.3.2\",\n        \"ts-loader\": \"^5.3.3\",\n        \"ts-mockito\": \"^2.3.1\",\n        \"tsc-watch\": \"^1.0.22\",\n        \"tslint\": \"^5.8.0\",\n        \"typescript\": \"^3.1.4\",\n        \"vscode\": \"^1.1.6\",\n        \"webpack\": \"^4.28.3\",\n        \"webpack-cli\": \"^3.2.0\"\n    },\n    \"dependencies\": {\n        \"@slack/client\": \"^4.6.0\",\n        \"discord.js\": \"^11.4.2\",\n        \"emoji-js\": \"^3.4.1\",\n        \"gravatar-api\": \"^1.5.0\",\n        \"https-proxy-agent\": \"^2.2.1\",\n        \"mixpanel\": \"^0.9.2\",\n        \"request\": \"^2.88.0\",\n        \"request-promise-native\": \"^1.0.5\",\n        \"semver\": \"^5.5.1\",\n        \"vsls\": \"^0.3.1291\"\n    }\n}\n"
  },
  {
    "path": "src/bots/travis.ts",
    "content": "import * as vscode from \"vscode\";\nimport * as rp from \"request-promise-native\";\nimport {\n  CommandHandler,\n  CommandResponse,\n  MessageCommand\n} from \"../controller/commands\";\nimport { TRAVIS_SCHEME } from \"../constants\";\n\nfunction getTravisBuild(username: string, reponame: string, build: string) {\n  return rp({\n    baseUrl: \"https://api.travis-ci.org/\",\n    uri: `repos/${username}/${reponame}/builds/${build}`,\n    json: true,\n    headers: {\n      Accept: \"application/vnd.travis-ci.2.1+json\"\n    }\n  }).then(response => {\n    const { jobs } = response;\n\n    if (jobs) {\n      return rp({\n        baseUrl: \"https://api.travis-ci.org/\",\n        uri: `jobs/${jobs[0].id}/log`\n      });\n    }\n  });\n}\n\nfunction stripAnsiEscapes(input: string) {\n  // Credits: https://stackoverflow.com/a/29497680/1469222\n  return input.replace(\n    /[\\u001b\\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,\n    \"\"\n  );\n}\n\nexport class TravisLinkHandler implements CommandHandler {\n  handle(cmd: MessageCommand): Promise<CommandResponse> {\n    const { subcommand } = cmd;\n    const { path } = vscode.Uri.parse(subcommand);\n    const matched = path.match(/^\\/(.+)\\/(.+)\\/(.+)\\/(.+)$/);\n\n    if (!!matched && matched.length) {\n      const user = matched[1];\n      const repo = matched[2];\n      const buildId = matched[4];\n      vscode.window.showTextDocument(\n        vscode.Uri.parse(`${TRAVIS_SCHEME}://${user}/${repo}/${buildId}`),\n        { viewColumn: vscode.ViewColumn.One }\n      );\n    }\n\n    const response: CommandResponse = { sendToSlack: false, response: \"\" };\n    return Promise.resolve(response);\n  }\n}\n\nclass TravisDocumentContentProvider\n  implements vscode.TextDocumentContentProvider {\n  provideTextDocumentContent(uri: vscode.Uri): vscode.ProviderResult<string> {\n    const { authority, path } = uri;\n    const splitPath = path.split(\"/\");\n    return getTravisBuild(authority, splitPath[1], splitPath[2]).then(\n      response => stripAnsiEscapes(response)\n    );\n  }\n}\n\nexport default new TravisDocumentContentProvider();\n"
  },
  {
    "path": "src/config/https-proxy-agent.d.ts",
    "content": "// foo.d.ts\ndeclare module \"https-proxy-agent\";\n"
  },
  {
    "path": "src/config/index.ts",
    "content": "import * as vscode from \"vscode\";\nimport * as https from \"https\";\nimport * as HttpsProxyAgent from \"https-proxy-agent\";\nimport { CONFIG_ROOT, SelfCommands } from \"../constants\";\nimport { KeychainHelper } from \"./keychain\";\n\nconst TOKEN_CONFIG_KEY = \"slack.legacyToken\";\nconst TELEMETRY_CONFIG_ROOT = \"telemetry\";\nconst TELEMETRY_CONFIG_KEY = \"enableTelemetry\";\nconst CREDENTIAL_SERVICE_NAME = \"vscode-chat\";\nconst VSLS_CHAT_TOKEN = \"vsls-placeholder-token\";\n\nconst getAccountName = (provider: string, teamId?: string) => {\n  return !!teamId ? `${provider} (${teamId})` : provider;\n};\n\nexport class ConfigHelper {\n  static getRootConfig() {\n    return vscode.workspace.getConfiguration(CONFIG_ROOT);\n  }\n\n  static updateRootConfig(section: string, value: any): Promise<void> {\n    // Convert Thenable to Promise to be able to use Promise.all\n    const rootConfig = this.getRootConfig();\n    return new Promise((resolve, reject) => {\n      rootConfig.update(section, value, vscode.ConfigurationTarget.Global).then(\n        result => {\n          return resolve(result);\n        },\n        error => {\n          return reject(error);\n        }\n      );\n    });\n  }\n\n  static async getToken(\n    service: string,\n    teamId?: string\n  ): Promise<string | null> {\n    if (service === \"vslsSpaces\") {\n      return VSLS_CHAT_TOKEN;\n    }\n\n    const accountName = getAccountName(service, teamId);\n    const keychainToken: string | null = await KeychainHelper.get(\n      CREDENTIAL_SERVICE_NAME,\n      accountName\n    );\n    return keychainToken;\n  }\n\n  static clearTokenFromSettings() {\n    this.updateRootConfig(TOKEN_CONFIG_KEY, undefined);\n  }\n\n  static async setToken(\n    token: string,\n    providerName: string,\n    teamId?: string\n  ): Promise<void> {\n    // TODO: it is possible that the keychain will fail\n    // See https://github.com/Microsoft/vscode-pull-request-github/commit/306dc5d27460599f3402f4b9e01d97bf638c639f\n    const accountName = getAccountName(providerName, teamId);\n    await KeychainHelper.set(CREDENTIAL_SERVICE_NAME, accountName, token);\n\n    // When token is set, we need to call reset\n    vscode.commands.executeCommand(SelfCommands.SETUP_NEW_PROVIDER, {\n      newInitialState: { provider: providerName, teamId }\n    });\n  }\n\n  static async clearToken(provider: string, teamId?: string): Promise<void> {\n    await KeychainHelper.clear(\n      CREDENTIAL_SERVICE_NAME,\n      getAccountName(provider, teamId)\n    );\n  }\n\n  static getProxyUrl() {\n    // Stored under CONFIG_ROOT.proxyUrl\n    const { proxyUrl } = this.getRootConfig();\n    return proxyUrl;\n  }\n\n  static getTlsRejectUnauthorized() {\n    const { rejectTlsUnauthorized } = this.getRootConfig();\n    return rejectTlsUnauthorized;\n  }\n\n  static getAutoLaunchLiveShareChat() {\n    const { autoLaunchLiveShareChat } = this.getRootConfig();\n    return autoLaunchLiveShareChat;\n  }\n\n  static hasTelemetry(): boolean {\n    const config = vscode.workspace.getConfiguration(TELEMETRY_CONFIG_ROOT);\n    return !!config.get<boolean>(TELEMETRY_CONFIG_KEY);\n  }\n\n  static hasTravisProvider(): boolean {\n    // Stored under CONFIG_ROOT.providers, which is string[]\n    const { providers } = this.getRootConfig();\n    return providers && providers.indexOf(\"travis\") >= 0;\n  }\n\n  static getCustomAgent() {\n    const proxyUrl = this.getProxyUrl();\n\n    if (!!proxyUrl) {\n      return new HttpsProxyAgent(proxyUrl);\n    }\n\n    const rejectUnauthorized = this.getTlsRejectUnauthorized();\n\n    if (!rejectUnauthorized) {\n      return new https.Agent({\n        rejectUnauthorized: false\n      });\n    }\n  }\n}\n"
  },
  {
    "path": "src/config/keychain.ts",
    "content": "import * as vscode from \"vscode\";\nimport * as str from \"../strings\";\nimport { keychain } from \"../utils/keychain\";\nimport IssueReporter from \"../issues\";\nimport Logger from \"../logger\";\n\nconst UNDEFINED_ERROR = \"System keychain is undefined\";\n\nexport class KeychainHelper {\n  // Adds retry to keychain operations if we are denied access\n  static async handleException(error: Error, retryCall: Function) {\n    Logger.log(`Keychain access: ${error}`);\n    const actionItems = [str.RETRY, str.REPORT_ISSUE];\n    const action = await vscode.window.showInformationMessage(\n      str.KEYCHAIN_ERROR,\n      ...actionItems\n    );\n\n    switch (action) {\n      case str.RETRY:\n        return retryCall();\n      case str.REPORT_ISSUE:\n        const title = \"Unable to access keychain\";\n        return IssueReporter.openNewIssue(title, `${error}`);\n    }\n  }\n\n  static async get(service: string, account: string) {\n    try {\n      if (!keychain) {\n        throw new Error(UNDEFINED_ERROR);\n      }\n\n      const password = await keychain.getPassword(service, account);\n      return password;\n    } catch (error) {\n      // If user denies, we can catch the error\n      // On Mac, this looks like `Error: User canceled the operation.`\n      return this.handleException(error, () => this.get(service, account));\n    }\n  }\n\n  static async set(service: string, account: string, password: string) {\n    try {\n      if (!keychain) {\n        throw new Error(UNDEFINED_ERROR);\n      }\n\n      await keychain.setPassword(service, account, password);\n    } catch (error) {\n      return this.handleException(error, () =>\n        this.set(service, account, password)\n      );\n    }\n  }\n\n  static async clear(service: string, account: string) {\n    try {\n      if (!keychain) {\n        throw new Error(UNDEFINED_ERROR);\n      }\n\n      await keychain.deletePassword(service, account);\n    } catch (error) {\n      return this.handleException(error, () => this.clear(service, account));\n    }\n  }\n}\n"
  },
  {
    "path": "src/constants.ts",
    "content": "export const CONFIG_ROOT = \"chat\";\nexport const EXTENSION_ID = \"karigari.chat\";\nexport const OUTPUT_CHANNEL_NAME = \"Team Chat\";\nexport const CONFIG_AUTO_LAUNCH = \"chat.autoLaunchLiveShareChat\";\n\n// Is there a way to get this url from the vsls extension?\nexport const LIVE_SHARE_BASE_URL = `insiders.liveshare.vsengsaas.visualstudio.com`;\nexport const VSLS_EXTENSION_ID = `ms-vsliveshare.vsliveshare`;\nexport const VSLS_EXTENSION_PACK_ID = `ms-vsliveshare.vsliveshare-pack`;\nexport const VSLS_SPACES_EXTENSION_ID = `vsls-contrib.spaces`;\n\nexport const LiveShareCommands = {\n    START: \"liveshare.start\",\n    END: \"liveshare.end\",\n    JOIN: \"liveshare.join\"\n};\n\nexport const VSCodeCommands = {\n    OPEN: \"vscode.open\",\n    OPEN_SETTINGS: \"workbench.action.openSettings\"\n};\n\nexport const SelfCommands = {\n    OPEN_WEBVIEW: \"extension.chat.openChatPanel\",\n    CHANGE_WORKSPACE: \"extension.chat.changeWorkspace\",\n    CHANGE_CHANNEL: \"extension.chat.changeChannel\",\n    SIGN_IN: \"extension.chat.authenticate\",\n    SIGN_OUT: \"extension.chat.signout\",\n    CONFIGURE_TOKEN: \"extension.chat.configureToken\",\n    LIVE_SHARE_FROM_MENU: \"extension.chat.startLiveShare\",\n    LIVE_SHARE_SLASH: \"extension.chat.slashLiveShare\",\n    LIVE_SHARE_SESSION_CHANGED: \"extension.chat.vslsSessionChanged\",\n    RESET_STORE: \"extension.chat.reset\",\n    SETUP_NEW_PROVIDER: \"extension.chat.setupNewProvider\",\n    FETCH_REPLIES: \"extension.chat.fetchReplies\",\n    UPDATE_MESSAGES: \"extension.chat.updateMessages\",\n    CLEAR_MESSAGES: \"extension.chat.clearMessages\",\n    UPDATE_MESSAGE_REPLIES: \"extension.chat.updateReplies\",\n    UPDATE_PRESENCE_STATUSES: \"extension.chat.updatePresenceStatuses\",\n    UPDATE_SELF_PRESENCE: \"extension.chat.updateSelfPresence\",\n    UPDATE_SELF_PRESENCE_VIA_VSLS: \"extension.chat.updateSelfPresenceVsls\",\n    ADD_MESSAGE_REACTION: \"extension.chat.addMessageReaction\",\n    REMOVE_MESSAGE_REACTION: \"extension.chat.removeMessageReaction\",\n    SEND_MESSAGE: \"extension.chat.sendMessage\",\n    SEND_THREAD_REPLY: \"extension.chat.sendThreadReply\",\n    SEND_TYPING: \"extension.chat.sendTypingMessage\",\n    SHOW_TYPING: \"extension.chat.showTypingMessage\",\n    INVITE_LIVE_SHARE_CONTACT: \"extension.chat.inviteLiveShareContact\",\n    CHANNEL_MARKED: \"extension.chat.updateChannelMark\",\n    HANDLE_INCOMING_LINKS: \"extension.chat.handleIncomingLinks\",\n    SEND_TO_WEBVIEW: \"extension.chat.sendToWebview\",\n    CHAT_WITH_VSLS_SPACE: \"extension.chat.chatWithSpace\",\n    VSLS_SPACE_JOINED: \"extension.chat.vslsSpaceJoined\"\n};\n\nexport const SLASH_COMMANDS: any = {\n    live: {\n        share: {\n            action: LiveShareCommands.START,\n            options: { suppressNotification: true }\n        },\n        end: { action: LiveShareCommands.END, options: {} }\n    }\n};\n\n// Reverse commands are acted on when received from Slack\nexport const REVERSE_SLASH_COMMANDS = {\n    live: {\n        request: {}\n    }\n};\n\n// Internal uri schemes\nexport const TRAVIS_BASE_URL = `travis-ci.org`;\nexport const TRAVIS_SCHEME = \"chat-travis-ci\";\n\n// Slack App\nconst REDIRECT_URI = `https://us-central1-eco-theater-119616.cloudfunctions.net/slackRedirect`\nconst SLACK_OAUTH_BASE = `https://slack.com/oauth/authorize?scope=client&client_id=282186700213.419156835749`;\nexport const SLACK_OAUTH = `${SLACK_OAUTH_BASE}&redirect_uri=${REDIRECT_URI}`\n\n// Discord\nconst DISCORD_SCOPES = [\"identify\", \"rpc.api\", \"messages.read\", \"guilds\"];\nconst DISCORD_SCOPE_STRING = DISCORD_SCOPES.join(\"%20\");\nconst DISCORD_CLIENT_ID = \"486416707951394817\";\nexport const DISCORD_OAUTH = `https://discordapp.com/oauth2/authorize?client_id=${DISCORD_CLIENT_ID}&response_type=code&scope=${DISCORD_SCOPE_STRING}`;\n\n// Telemetry\nexport const MIXPANEL_TOKEN = \"14c9fea2bf4e06ba766e16eca1bce728\";\n"
  },
  {
    "path": "src/controller/commands.ts",
    "content": "import * as vscode from \"vscode\";\nimport * as vsls from \"vsls\";\nimport {\n  SLASH_COMMANDS,\n  LIVE_SHARE_BASE_URL,\n  TRAVIS_BASE_URL,\n  VSCodeCommands\n} from \"../constants\";\nimport { TravisLinkHandler } from \"../bots/travis\";\nimport { ConfigHelper } from \"../config\";\n\nexport interface MessageCommand {\n  namespace: string;\n  subcommand: string;\n}\n\nexport interface CommandResponse {\n  sendToSlack: Boolean;\n  response: string;\n}\n\nexport interface CommandHandler {\n  handle: (cmd: MessageCommand) => Promise<CommandResponse>;\n}\n\nclass VscodeCommandHandler implements CommandHandler {\n  execute = (command: string, ...rest: any[]): Promise<any> => {\n    // Wraps the executeCommand thenable into a promise\n    // https://github.com/Microsoft/vscode/issues/11693#issuecomment-247495996\n    return new Promise((resolve, reject) => {\n      vscode.commands.executeCommand(command, ...rest).then(\n        result => {\n          return resolve(result);\n        },\n        error => {\n          vscode.window.showErrorMessage(error.toString());\n          return reject(error);\n        }\n      );\n    });\n  };\n\n  handle = (cmd: MessageCommand): Promise<CommandResponse> => {\n    const { namespace, subcommand } = cmd;\n    const commands = SLASH_COMMANDS[namespace];\n    const { action, options } = commands[subcommand];\n    return this.execute(action, options).then((response: vscode.Uri) => {\n      // We append </> to the URL so our link parsing works\n      // TODO(arjun) Uri is only valid for `/live share` command\n      const responseString = response ? `<${response.toString()}>` : \"\";\n      const sendToSlack = namespace === \"live\" && subcommand === \"share\";\n      return { sendToSlack, response: responseString };\n    });\n  };\n}\n\nclass OpenCommandHandler extends VscodeCommandHandler {\n  handle = async (cmd: MessageCommand): Promise<any> => {\n    const { subcommand } = cmd;\n    let uri: vscode.Uri | undefined;\n\n    try {\n      uri = vscode.Uri.parse(subcommand);\n\n      switch (uri.authority) {\n        case LIVE_SHARE_BASE_URL:\n          const liveshare = await vsls.getApi();\n          const opts: vsls.JoinOptions = { newWindow: false };\n\n          if (liveshare) {\n            await liveshare.join(uri, opts);\n          }\n\n          break;\n        case TRAVIS_BASE_URL:\n          if (ConfigHelper.hasTravisProvider()) {\n            const travisHandler = new TravisLinkHandler();\n            return travisHandler.handle(cmd);\n          }\n        default:\n          return this.execute(VSCodeCommands.OPEN, uri);\n      }\n    } catch (err) {\n      // return new Promise((_, reject) => reject());\n    }\n  };\n}\n\n/**\n * Finds the correct command handler for the given command\n * and runs it\n */\nexport default class CommandDispatch {\n  handle = (message: MessageCommand): Promise<CommandResponse> => {\n    const { namespace, subcommand } = message;\n\n    if (namespace === \"open\") {\n      // We might have to convert this into\n      const openHandler = new OpenCommandHandler();\n      return openHandler.handle(message);\n    } else {\n      // Others are all vs code commands\n      const vscodeHandler = new VscodeCommandHandler();\n      return vscodeHandler.handle(message);\n    }\n  };\n}\n"
  },
  {
    "path": "src/controller/emoji-js.d.ts",
    "content": "// foo.d.ts\ndeclare module \"emoji-js\";\n"
  },
  {
    "path": "src/controller/index.ts",
    "content": "import * as vscode from \"vscode\";\nimport WebviewContainer from \"../webview\";\nimport { SLASH_COMMANDS, REVERSE_SLASH_COMMANDS, SelfCommands } from \"../constants\";\nimport Logger from \"../logger\";\nimport CommandDispatch, { MessageCommand } from \"./commands\";\nimport markdownTransform from \"./markdowner\";\n\nexport const getCommand = (text: string): MessageCommand | undefined => {\n    const pattern = /^\\/(\\w+) (\\w+)$/;\n    const trimmed = text.trim();\n    const matched = trimmed.match(pattern);\n\n    if (matched) {\n        return { namespace: matched[1], subcommand: matched[2] };\n    }\n};\n\nclass ViewController {\n    ui: WebviewContainer | undefined;\n    isUIReady: Boolean = false; // Vuejs loaded\n    pendingMessage: UIMessage | undefined = undefined;\n\n    currentSource: EventSource | undefined;\n    currentProvider: string | undefined;\n    currentChannelId: string | undefined;\n\n    constructor(\n        private context: vscode.ExtensionContext,\n        private onUIDispose: (provider: string | undefined, source: EventSource | undefined) => void,\n        private onUIVisible: (provider: string | undefined) => void,\n        private onUIFocus: (provider: string | undefined) => void\n    ) {}\n\n    isUILoaded = () => !!this.ui;\n\n    loadUi = () => {\n        if (this.ui) {\n            this.ui.reveal();\n        } else {\n            const { extensionPath } = this.context;\n            this.ui = new WebviewContainer(\n                extensionPath,\n                () => {\n                    this.ui = undefined;\n                    this.isUIReady = false;\n                    this.onUIDispose(this.currentProvider, this.currentSource);\n                },\n                isVisible => (isVisible ? this.onUIVisible(this.currentProvider) : null)\n            );\n            this.ui.setMessageHandler(this.sendToExtension);\n        }\n    };\n\n    dispatchCommand(command: MessageCommand) {\n        const handler = new CommandDispatch();\n\n        handler.handle(command).then(result => {\n            if (!!result) {\n                const { sendToSlack, response } = result;\n                if (sendToSlack && response) {\n                    this.sendTextMessage(response);\n                }\n            }\n        });\n    }\n\n    isValidCommand = (text: string, commandList: { [name: string]: any }) => {\n        const parsed = getCommand(text);\n\n        if (parsed) {\n            const { namespace, subcommand } = parsed;\n\n            if (namespace in commandList) {\n                const subcommands = Object.keys(commandList[namespace]);\n                return subcommands.indexOf(subcommand) >= 0;\n            }\n        }\n\n        return false;\n    };\n\n    isValidReverseCommand = (text: string) => {\n        return this.isValidCommand(text, REVERSE_SLASH_COMMANDS);\n    };\n\n    handleCommand = (text: string) => {\n        if (this.isValidCommand(text, SLASH_COMMANDS)) {\n            const parsed = getCommand(text);\n\n            if (!!parsed) {\n                const { namespace, subcommand } = parsed;\n\n                if (namespace === \"live\" && subcommand === \"share\") {\n                    // Temporary bypass for \"/live share\" till we move\n                    // all of this to the common command handlers\n                    return vscode.commands.executeCommand(SelfCommands.LIVE_SHARE_SLASH, {\n                        provider: this.currentProvider\n                    });\n                } else {\n                    return this.dispatchCommand(parsed);\n                }\n            }\n        }\n\n        if (text === \"/clear\") {\n            return vscode.commands.executeCommand(SelfCommands.CLEAR_MESSAGES, {\n                channelId: this.currentChannelId,\n                provider: this.currentProvider\n            });\n        }\n\n        if (text === \"/invite\") {\n            return vscode.commands.executeCommand(SelfCommands.INVITE_LIVE_SHARE_CONTACT, {\n                channelId: this.currentChannelId,\n                provider: this.currentProvider\n            });\n        }\n\n        if (this.isValidReverseCommand(text)) {\n            return this.sendTextMessage(text);\n        }\n\n        // TODO(arjun): if not valid, then we need to parse and make a chat.command\n        // API call, instead of sending it as a simple text message.\n        // Docs: https://github.com/ErikKalkoken/slackApiDoc/blob/master/chat.command.md\n        return this.sendTextMessage(text);\n    };\n\n    handleInternal = (message: any) => {\n        const { text } = message;\n\n        if (text === \"is_ready\") {\n            this.isUIReady = true;\n            return this.pendingMessage ? this.sendToUI(this.pendingMessage) : null;\n        }\n\n        if (text === \"is_focused\") {\n            this.onUIFocus(this.currentProvider);\n        }\n\n        if (text === \"fetch_replies\") {\n            const { parentTimestamp } = message;\n            vscode.commands.executeCommand(SelfCommands.FETCH_REPLIES, {\n                parentTimestamp,\n                provider: this.currentProvider\n            });\n        }\n\n        if (text === \"is_typing\") {\n            vscode.commands.executeCommand(SelfCommands.SEND_TYPING, {\n                channelId: this.currentChannelId,\n                provider: this.currentProvider\n            });\n        }\n    };\n\n    sendTextMessage = (text: string) => {\n        return vscode.commands.executeCommand(SelfCommands.SEND_MESSAGE, {\n            text,\n            provider: this.currentProvider\n        });\n    };\n\n    sendThreadReply = (payload: any) => {\n        const { text, parentTimestamp } = payload;\n        return vscode.commands.executeCommand(SelfCommands.SEND_THREAD_REPLY, {\n            text,\n            parentTimestamp,\n            provider: this.currentProvider\n        });\n    };\n\n    sendToExtension = (message: ExtensionMessage) => {\n        const { type, text } = message;\n        Logger.log(`Sending to extension (${type}) ${text}`);\n\n        switch (type) {\n            case \"internal\":\n                return this.handleInternal(message);\n            case \"link\":\n                return this.dispatchCommand({ namespace: \"open\", subcommand: text });\n            case \"command\":\n                return this.handleCommand(text);\n            case \"text\":\n                return text ? this.sendTextMessage(text) : null;\n            case \"thread_reply\":\n                return this.sendThreadReply(text);\n        }\n    };\n\n    handleReverseCommands = (uiMessage: UIMessage) => {\n        // TODO: Reverse commands are disabled, until we fix this\n\n        // Reverse commands are slash commands fired by other Slack users\n        // For example, `/live request` requests someone to host a session\n        const { currentUser, messages } = uiMessage;\n        let handledMessages: ChannelMessages = {};\n\n        Object.keys(messages).forEach(ts => {\n            // Any of these messages might be reverse commands\n            const { text, userId } = messages[ts];\n            const notCurrentUser = currentUser.id !== userId;\n            // let textHTML = messages[ts].textHTML;\n\n            if (this.isValidReverseCommand(text) && notCurrentUser) {\n                if (text === \"/live request\") {\n                    const confirmation = `<a href=\"#\" onclick=\"sendCommand('/live share'); return false;\">Accept</a>`;\n                    // textHTML = `${str.LIVE_REQUEST_MESSAGE} ${confirmation}`;\n                }\n            }\n\n            handledMessages[ts] = {\n                ...messages[ts]\n                // textHTML\n            };\n        });\n\n        return {\n            ...uiMessage,\n            messages: handledMessages\n        };\n    };\n\n    updateCurrentState = (provider: string, channelId: string, source: EventSource) => {\n        this.currentProvider = provider;\n        this.currentChannelId = channelId;\n        this.currentSource = source;\n    };\n\n    sendToUI = (uiMessage: UIMessage) => {\n        const { provider: incomingProvider, channel: incomingChannel } = uiMessage;\n\n        if (!!this.ui && this.ui.isVisible()) {\n            // The webview is visible => we check if the incoming message is valid.\n            const isSameProvider = !this.currentProvider || incomingProvider === this.currentProvider;\n            const isSameChannel = !this.currentChannelId || incomingChannel.id === this.currentChannelId;\n\n            if (!isSameChannel || !isSameProvider) {\n                return; // Ignore this message.\n            }\n        }\n\n        if (!this.isUIReady) {\n            this.pendingMessage = uiMessage;\n        } else {\n            const { messages } = uiMessage;\n            const size = Object.keys(messages).length;\n            Logger.log(`Sending to webview: ${size} messages`);\n\n            // Handle markdown\n            const mdMessages = markdownTransform(uiMessage);\n\n            // Handle reverse slash commands\n            // Since this overwrites the textHTML field, it should happen\n            // after the markdown\n            const message = this.handleReverseCommands(mdMessages);\n\n            // Send to UI after markdown\n            if (this.ui) {\n                this.ui.update(message);\n                this.pendingMessage = undefined;\n            }\n        }\n    };\n}\n\nexport default ViewController;\n"
  },
  {
    "path": "src/controller/markdown-it-slack.d.ts",
    "content": "// foo.d.ts\ndeclare module \"markdown-it-slack\";\n"
  },
  {
    "path": "src/controller/markdowner.ts",
    "content": "import * as EmojiConvertor from \"emoji-js\";\n\nexport const parseUsernames = (uiMessage: UIMessage): UIMessage => {\n    // Find and replace names like <@UBCQ8LF28>\n    // TODO: fix this for channel names, which show up as <#C8A187ZRQ|general>\n    const { messages, users } = uiMessage;\n    let newMessages: ChannelMessages = {};\n\n    Object.keys(messages).map(ts => {\n        const message = messages[ts];\n        let { text } = message;\n        const matched = text.match(/<@([A-Z0-9]+)>/);\n\n        if (matched && matched.length > 0) {\n            const userId = matched[1];\n            if (userId in users) {\n                const { name } = users[userId];\n                text = text.replace(matched[0], `@${name}`);\n            }\n        }\n\n        newMessages[ts] = {\n            ...message,\n            text\n        };\n    });\n    return {\n        ...uiMessage,\n        messages: newMessages\n    };\n};\n\nexport const emojify = (messages: ChannelMessages): ChannelMessages => {\n    // Even though we are using markdown-it-slack, it does not support\n    // emoji skin tones. If that changes, we can remove this method.\n    const emoji = new EmojiConvertor();\n    emoji.allow_native = true;\n\n    // We have added node_modules/emoji-datasource to vscodeignore since we use\n    // allow_native. If this changes, we might have to use emoji sheets (through CDN?)\n    emoji.replace_mode = \"unified\";\n    let emojifiedMessages: ChannelMessages = {};\n\n    Object.keys(messages).forEach(key => {\n        const message = messages[key];\n        const { text, reactions } = message;\n\n        emojifiedMessages[key] = {\n            ...message,\n            reactions: reactions\n            ? reactions.map(reaction => ({\n                ...reaction,\n                name: emoji.replace_colons(reaction.name)\n            }))\n            : [],\n            text: emoji.replace_colons(text ? text : \"\")\n        };\n    });\n\n    return emojifiedMessages;\n};\n\nconst parseSimpleLinks = (messages: ChannelMessages): ChannelMessages => {\n    let parsed: ChannelMessages = {};\n\n    Object.keys(messages).forEach(key => {\n        const { content, text } = messages[key];\n        let newContent: MessageContent | undefined = undefined;\n        const URL_REGEX = /https?:\\/\\/(www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{2,256}\\.[a-z]{2,6}\\b([-a-zA-Z0-9@:%_\\+.~#?&//=;\\^]*)/;\n        const re = new RegExp(`${URL_REGEX.source}`, \"g\");\n\n        if (!!content) {\n            newContent = {\n                ...content,\n                text: content.text\n                ? content.text.replace(re, function(a, b, c, d, e) {\n                    return `[${a}](${a})`;\n                })\n                : \"\",\n                footer: content.footer\n                ? content.footer.replace(re, function(a, b, c, d, e) {\n                    return `[${a}](${a})`;\n                })\n                : \"\"\n            };\n        }\n\n        parsed[key] = {\n            ...messages[key],\n            text: text\n            ? text.replace(re, function(a, b, c, d, e) {\n                return `[${a}](${a})`;\n            })\n            : \"\",\n            content: newContent\n        };\n    });\n    return parsed;\n}\n\nexport const parseSlackLinks = (messages: ChannelMessages): ChannelMessages => {\n    // Looks for <url|title> pattern, and replaces them with normal markdown\n    // The |pattern can be optional\n    let parsed: ChannelMessages = {};\n\n    Object.keys(messages).forEach(key => {\n        const { content, text } = messages[key];\n        let newContent: MessageContent | undefined = undefined;\n        const URL_REGEX = /https?:\\/\\/(www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{2,256}\\.[a-z]{2,6}\\b([-a-zA-Z0-9@:%_\\+.~#?&//=;\\^]*)/;\n        const SLACK_MODIFIER = /(|.[^><]+)/;\n        const re = new RegExp(`<(${URL_REGEX.source})(${SLACK_MODIFIER.source})>`, \"g\");\n\n        if (!!content) {\n            newContent = {\n                ...content,\n                text: content.text\n                ? content.text.replace(re, function(a, b, c, d, e) {\n                    return e ? `[${e.substr(1)}](${b})` : `[${b}](${b})`;\n                })\n                : \"\",\n                footer: content.footer\n                ? content.footer.replace(re, function(a, b, c, d, e) {\n                    return e ? `[${e.substr(1)}](${b})` : `[${b}](${b})`;\n                })\n                : \"\"\n            };\n        }\n\n        parsed[key] = {\n            ...messages[key],\n            text: text\n            ? text.replace(re, function(a, b, c, d, e) {\n                return e ? `[${e.substr(1)}](${b})` : `[${b}](${b})`;\n            })\n            : \"\",\n            content: newContent\n        };\n    });\n    return parsed;\n};\n\nconst transformChain = (uiMessage: UIMessage): UIMessage => {\n    const { messages } = parseUsernames(uiMessage);\n    const linkParser = uiMessage.provider === \"vslsSpaces\" ? parseSimpleLinks : parseSlackLinks;\n    return {\n        ...uiMessage,\n        messages: linkParser(emojify(messages))\n    };\n};\n\nexport default transformChain;\n"
  },
  {
    "path": "src/discord/index.ts",
    "content": "import * as vscode from \"vscode\";\nimport * as Discord from \"discord.js\";\nimport * as rp from \"request-promise-native\";\nimport { SelfCommands } from \"../constants\";\nimport { toTitleCase } from \"../utils\";\nimport Logger from \"../logger\";\n\nconst HISTORY_LIMIT = 50;\nconst MEMBER_LIMIT = 500;\n\nconst getPresence = (presence: Discord.Presence): UserPresence => {\n  const { status } = presence;\n\n  switch (status) {\n    case \"online\":\n      return UserPresence.available;\n    case \"dnd\":\n      return UserPresence.doNotDisturb;\n    case \"idle\":\n      return UserPresence.idle;\n    case \"offline\":\n      return UserPresence.offline;\n  }\n};\n\nconst getMessageContent = (\n  raw: Discord.Message\n): MessageContent | undefined => {\n  const { embeds } = raw;\n  if (!!embeds && embeds.length > 0) {\n    const firstEmbed = embeds[0];\n    return {\n      author: ``,\n      pretext: ``,\n      title: firstEmbed.title,\n      titleLink: firstEmbed.url,\n      text: firstEmbed.description,\n      footer: ``\n    };\n  }\n};\n\nconst getMessage = (raw: Discord.Message): Message => {\n  const { author, createdTimestamp, content, reactions, editedTimestamp } = raw;\n  const timestamp = (createdTimestamp / 1000).toString();\n  let attachment = undefined;\n  const attachments = raw.attachments.array();\n\n  if (attachments.length > 0) {\n    // This only shows the first attachment\n    const selected = attachments[0];\n    attachment = {\n      name: selected.filename,\n      permalink: selected.url\n    };\n  }\n\n  return {\n    timestamp,\n    userId: author.id,\n    text: content,\n    isEdited: !!editedTimestamp,\n    content: getMessageContent(raw),\n    replies: {},\n    attachment,\n    reactions: reactions.map(rxn => ({\n      name: rxn.emoji.name,\n      count: rxn.count,\n      userIds: rxn.users.map(user => user.id)\n    }))\n  };\n};\n\nconst getUser = (raw: Discord.User): User => {\n  const { id: userId, username, avatar, presence } = raw;\n  return {\n    id: userId,\n    name: username,\n    fullName: username,\n    imageUrl: getImageUrl(userId, avatar),\n    smallImageUrl: getSmallImageUrl(userId, avatar),\n    presence: getPresence(presence)\n  };\n};\n\nconst DEFAULT_AVATARS = [\n  \"https://discordapp.com/assets/dd4dbc0016779df1378e7812eabaa04d.png\",\n  \"https://discordapp.com/assets/0e291f67c9274a1abdddeb3fd919cbaa.png\",\n  \"https://discordapp.com/assets/6debd47ed13483642cf09e832ed0bc1b.png\",\n  \"https://discordapp.com/assets/322c936a8c8be1b803cd94861bdfa868.png\",\n  \"https://discordapp.com/assets/1cbd08c76f8af6dddce02c5138971129.png\"\n];\n\nconst getAvatarUrl = (userId: string, avatar: string, size: number) => {\n  if (!avatar) {\n    return DEFAULT_AVATARS[Math.floor(Math.random() * DEFAULT_AVATARS.length)];\n  } else {\n    // size can be any power of two between 16 and 2048\n    return `https://cdn.discordapp.com/avatars/${userId}/${avatar}.png?size=${size}`;\n  }\n};\n\nconst getImageUrl = (userId: string, avatar: string) =>\n  getAvatarUrl(userId, avatar, 128);\n\nconst getSmallImageUrl = (userId: string, avatar: string) =>\n  getAvatarUrl(userId, avatar, 32);\n\nexport class DiscordChatProvider implements IChatProvider {\n  client: Discord.Client;\n  mutedChannels: Set<string> = new Set([]);\n  imChannels: Channel[] = [];\n\n  constructor(private token: string, private manager: IManager) {\n    this.client = new Discord.Client();\n  }\n\n  async validateToken(): Promise<CurrentUser | undefined> {\n    const response = await rp({\n      baseUrl: `https://discordapp.com/api/v6`,\n      uri: `/users/@me`,\n      json: true,\n      headers: {\n        Authorization: `${this.token}`\n      }\n    });\n    const { id, username: name } = response;\n    return {\n      id,\n      name,\n      teams: [],\n      currentTeamId: undefined,\n      provider: Providers.discord\n    };\n  }\n\n  connect(): Promise<CurrentUser> {\n    return new Promise(resolve => {\n      this.client.on(\"ready\", () => {\n        const { id, username: name } = this.client.user;\n        const teams = this.client.guilds.array().map(guild => ({\n          id: guild.id,\n          name: guild.name\n        }));\n        const currentUser: CurrentUser = {\n          id,\n          name,\n          teams,\n          currentTeamId: undefined,\n          provider: Providers.discord\n        };\n        resolve(currentUser);\n      });\n\n      if (process.env.IS_DEBUG === \"true\") {\n        // Debug logs for local testing\n        this.client.on(\"debug\", info =>\n          console.log(\"Discord client log:\", info)\n        );\n      }\n\n      this.client.on(\"presenceUpdate\", (_, newMember: Discord.GuildMember) => {\n        const { id: userId, presence } = newMember;\n        vscode.commands.executeCommand(SelfCommands.UPDATE_PRESENCE_STATUSES, {\n          userId,\n          presence: getPresence(presence),\n          provider: \"discord\"\n        });\n      });\n\n      this.client.on(\"message\", msg => {\n        this.handleIncomingMessage(msg);\n        this.handleIncomingLinks(msg);\n      });\n\n      this.client.on(\"messageUpdate\", (_, msg: Discord.Message) => {\n        this.handleIncomingMessage(msg);\n      });\n\n      this.client.on(\"error\", error => {\n        Logger.log(`[ERROR] Discord: ${error.message}`);\n      });\n\n      this.client.login(this.token);\n    });\n  }\n\n  handleIncomingMessage(msg: Discord.Message) {\n    // If message has guild, we check for current guild\n    // Else, message is from a DM or group DM\n    const currentGuild = this.getCurrentGuild();\n    const { guild } = msg;\n\n    if (!currentGuild) {\n      return;\n    }\n\n    if (!guild || guild.id === currentGuild.id) {\n      let newMessages: ChannelMessages = {};\n      const channelId = msg.channel.id;\n      const parsed = getMessage(msg);\n      const { timestamp } = parsed;\n      newMessages[timestamp] = parsed;\n      vscode.commands.executeCommand(SelfCommands.UPDATE_MESSAGES, {\n        channelId,\n        messages: newMessages,\n        provider: \"discord\"\n      });\n    }\n  }\n\n  handleIncomingLinks(msg: Discord.Message) {\n    // For vsls invitations\n    const currentGuild = this.getCurrentGuild();\n    const { guild } = msg;\n\n    if (!currentGuild) {\n      return;\n    }\n\n    if (!guild || guild.id === currentGuild.id) {\n      const parsed = getMessage(msg);\n      let uri: vscode.Uri | undefined;\n      try {\n        const { text } = parsed;\n        if (text.startsWith(\"http\")) {\n          uri = vscode.Uri.parse(parsed.text);\n          vscode.commands.executeCommand(SelfCommands.HANDLE_INCOMING_LINKS, {\n            provider: \"discord\",\n            senderId: parsed.userId,\n            uri\n          });\n        }\n      } catch (e) {}\n    }\n  }\n\n  isConnected(): boolean {\n    return !!this.client && !!this.client.readyTimestamp;\n  }\n\n  getUserPreferences(): Promise<UserPreferences> {\n    const mutedChannels = Array.from(this.mutedChannels);\n    return Promise.resolve({ mutedChannels });\n  }\n\n  getCurrentGuild(): Discord.Guild | undefined {\n    const currentUserInfo = this.manager.store.getCurrentUser(\"discord\");\n\n    if (!!currentUserInfo) {\n      const { currentTeamId } = currentUserInfo;\n      return this.client.guilds.find(guild => guild.id === currentTeamId);\n    }\n  }\n\n  async fetchUsers(): Promise<Users> {\n    const guild = this.getCurrentGuild();\n    const readyTimestamp = (this.client.readyTimestamp / 1000.0).toString();\n    let users: Users = {};\n\n    // We first build users from IM channels, and then from the guild members\n    this.imChannels = this.client.channels\n      .filter(channel => channel.type === \"dm\")\n      .map(channel => {\n        const dmChannel = <Discord.DMChannel>channel;\n        const { id, recipient } = dmChannel;\n        const user = getUser(recipient);\n        users[user.id] = user;\n        return {\n          id,\n          name: recipient.username,\n          type: ChannelType.im,\n          readTimestamp: readyTimestamp,\n          unreadCount: 0\n        };\n      });\n\n    if (!!guild) {\n      // Getting guild members requires knowing the guild\n      const response = await guild.fetchMembers(\"\", MEMBER_LIMIT);\n      response.members.forEach(member => {\n        const { user: discordUser, roles } = member;\n        const hoistedRole = roles.find(role => role.hoist);\n        let roleName = undefined;\n\n        if (!!hoistedRole) {\n          roleName = toTitleCase(hoistedRole.name);\n        }\n\n        const user = getUser(discordUser);\n        users[user.id] = { ...user, roleName };\n      });\n    }\n\n    return users;\n  }\n\n  async fetchUserInfo(userId: string): Promise<User> {\n    const discordUser = await this.client.fetchUser(userId);\n    return getUser(discordUser);\n  }\n\n  fetchChannels(users: Users): Promise<Channel[]> {\n    // This fetches channels of the current guild, and (group) DMs.\n    // For unreads, we are not retrieving historical unreads, not clear if API supports that.\n    const readyTimestamp = (this.client.readyTimestamp / 1000.0).toString();\n    const guild = this.getCurrentGuild();\n    let categories: { [id: string]: string } = {};\n\n    if (!!guild) {\n      guild.channels\n        .filter(channel => channel.type === \"category\")\n        .forEach(channel => {\n          const { id: channelId, name, muted } = channel;\n          categories[channelId] = name;\n\n          if (muted) {\n            this.mutedChannels.add(channelId);\n          }\n        });\n\n      const currentUserInfo = this.manager.store.getCurrentUser(\"discord\");\n      const guildChannels: Channel[] = guild.channels\n        .filter(channel => channel.type !== \"category\")\n        .filter(channel => {\n          if (!!currentUserInfo) {\n            const userId = currentUserInfo.id;\n            const permissions = channel.permissionsFor(userId);\n            const permissionFlag = Discord.Permissions.FLAGS.VIEW_CHANNEL;\n\n            if (!!permissions && permissionFlag) {\n              return permissions.has(permissionFlag);\n            }\n          }\n\n          return false;\n        })\n        .map(channel => {\n          const { name, id, parentID } = channel;\n          return {\n            id,\n            name,\n            categoryName: categories[parentID],\n            type: ChannelType.channel,\n            readTimestamp: readyTimestamp,\n            unreadCount: 0\n          };\n        });\n\n      const groupChannels = this.client.channels\n        .filter(channel => channel.type === \"group\")\n        .map(channel => {\n          const groupChannel = <Discord.GroupDMChannel>channel;\n          const { id, recipients } = groupChannel;\n          return {\n            id,\n            name: recipients.map(recipient => recipient.username).join(\", \"),\n            type: ChannelType.group,\n            readTimestamp: readyTimestamp,\n            unreadCount: 0\n          };\n        });\n\n      return Promise.resolve([\n        ...guildChannels,\n        ...this.imChannels,\n        ...groupChannels\n      ]);\n    }\n\n    return Promise.resolve([]);\n  }\n\n  async loadChannelHistory(channelId: string): Promise<ChannelMessages> {\n    const channel: any = this.client.channels.find(\n      channel => channel.id === channelId\n    );\n\n    // channel.fetchMessages will break for voice channels\n    const messages: Discord.Message[] = await channel.fetchMessages({\n      limit: HISTORY_LIMIT\n    });\n\n    let result: ChannelMessages = {};\n    messages.forEach(message => {\n      const parsed = getMessage(message);\n      const { timestamp } = parsed;\n      result[timestamp] = parsed;\n    });\n    return result;\n  }\n\n  sendMessage(\n    text: string,\n    currentUserId: string,\n    channelId: string\n  ): Promise<void> {\n    const channel: any = this.client.channels.find(\n      channel => channel.id === channelId\n    );\n    return channel.send(text);\n  }\n\n  fetchChannelInfo(channel: Channel): Promise<Channel> {\n    return Promise.resolve(channel);\n  }\n\n  subscribePresence(users: Users): void {}\n\n  sendThreadReply() {\n    return Promise.resolve();\n  }\n\n  async updateSelfPresence(\n    presence: UserPresence\n  ): Promise<UserPresence | undefined> {\n    let status: Discord.PresenceStatus;\n\n    switch (presence) {\n      case UserPresence.available:\n        status = \"online\";\n        break;\n      case UserPresence.doNotDisturb:\n        status = \"dnd\";\n        break;\n      case UserPresence.idle:\n        status = \"idle\";\n        break;\n      case UserPresence.invisible:\n        status = \"invisible\";\n        break;\n      default:\n        throw new Error(\"status not supported by discord\");\n    }\n\n    const response = await this.client.user.setPresence({ status });\n    // response.presence.status is always `invisible`\n    // Hence we return the original presence input as success\n    return presence;\n  }\n\n  destroy(): Promise<void> {\n    if (!!this.client) {\n      return this.client.destroy();\n    }\n\n    return Promise.resolve();\n  }\n\n  async markChannel(channel: Channel, ts: string): Promise<Channel> {\n    // Discord does not have a concept of timestamp, it will acknowledge everything\n    // return Promise.resolve(channel);\n    const { id: channelId } = channel;\n    const discordChannel: any = this.client.channels.find(\n      channel => channel.id === channelId\n    );\n    await discordChannel.acknowledge();\n    return { ...channel, readTimestamp: ts };\n  }\n\n  fetchThreadReplies(channelId: string, ts: string): Promise<any> {\n    // Never called. Discord has no threads.\n    return Promise.resolve();\n  }\n\n  createIMChannel(user: User): Promise<Channel | undefined> {\n    // This is required to share vsls links with users that\n    // do not have corresponding DM channels\n    return Promise.resolve(undefined);\n  }\n\n  async sendTyping(currentUserId: string, channelId: string) { }\n}\n"
  },
  {
    "path": "src/extension.ts",
    "content": "import * as vscode from \"vscode\";\nimport * as vsls from \"vsls\";\nimport ViewController from \"./controller\";\nimport Manager from \"./manager\";\nimport Logger from \"./logger\";\nimport { Store } from \"./store\";\nimport * as str from \"./strings\";\nimport {\n    SelfCommands,\n    SLACK_OAUTH,\n    DISCORD_OAUTH,\n    CONFIG_ROOT,\n    CONFIG_AUTO_LAUNCH,\n    TRAVIS_SCHEME,\n    VSLS_SPACES_EXTENSION_ID\n} from \"./constants\";\nimport travis from \"./bots/travis\";\nimport { ExtensionUriHandler } from \"./uriHandler\";\nimport * as utils from \"./utils\";\nimport { askForAuth } from \"./onboarding\";\nimport { ConfigHelper } from \"./config\";\nimport TelemetryReporter from \"./telemetry\";\nimport IssueReporter from \"./issues\";\n\nlet store: Store;\nlet manager: Manager;\nlet controller: ViewController;\nlet telemetry: TelemetryReporter;\nlet typingTimers: { [key: string]: NodeJS.Timer | undefined } = {};\n\nexport function activate(context: vscode.ExtensionContext) {\n    Logger.log(\"Activating vscode-chat\");\n    store = new Store(context);\n    manager = new Manager(store);\n    telemetry = new TelemetryReporter(manager);\n    // telemetry.record(\n    //     EventType.activationStarted,\n    //     undefined,\n    //     undefined,\n    //     undefined\n    // );\n\n    controller = new ViewController(\n        context,\n        (provider, source) => onUIDispose(provider, source),\n        provider => {\n            if (provider) {\n                const lastChannelId = manager.store.getLastChannelId(provider);\n\n                if (lastChannelId) {\n                    return manager.loadChannelHistory(provider, lastChannelId);\n                }\n            }\n        },\n        provider => (!!provider ? manager.updateReadMarker(provider) : undefined)\n    );\n\n    const setupFreshInstall = () => {\n        const installationId = manager.store.generateInstallationId();\n        telemetry.setUniqueId(installationId);\n        telemetry.record(EventType.extensionInstalled, undefined, undefined, undefined);\n    };\n\n    const handleNoToken = (canPromptForAuth: boolean) => {\n        const hasVsls = utils.hasVslsExtension() || utils.hasVslsExtensionPack();\n\n        if (canPromptForAuth && !hasVsls) {\n            askForAuth();\n        }\n\n        throw new Error(str.TOKEN_NOT_FOUND);\n    };\n\n    const initializeToken = async (canPromptForAuth: boolean, newInitialState: InitialState | undefined) => {\n        await manager.initializeToken(newInitialState);\n\n        if (!manager.isTokenInitialized) {\n            setTimeout(() => handleNoToken(canPromptForAuth), 5 * 1000);\n        }\n    };\n\n    const setup = async (canPromptForAuth: boolean, newInitialState: InitialState | undefined): Promise<any> => {\n        await store.runStateMigrations();\n        const isFreshInstall = !manager.store.installationId;\n\n        if (isFreshInstall) {\n            setupFreshInstall();\n        }\n\n        if (!manager.isTokenInitialized || !!newInitialState) {\n            // We force initialization if we are provided a newInitialState\n            await initializeToken(canPromptForAuth, newInitialState);\n        }\n\n        await manager.initializeProviders();\n\n        if (manager.isProviderEnabled(\"discord\")) {\n            if (!manager.getCurrentTeamIdFor(\"discord\")) {\n                await askForWorkspace(\"discord\");\n            }\n        }\n\n        // TODO: In discord, user preferences are available after channels are fetched\n        manager.updateUserPrefsForAll(); // async update\n        await manager.initializeStateForAll();\n        manager.subscribePresenceForAll();\n    };\n\n    const sendMessage = (providerName: string, text: string, parentTimestamp: string | undefined) => {\n        const lastChannelId = manager.store.getLastChannelId(providerName);\n        telemetry.record(EventType.messageSent, undefined, lastChannelId, providerName);\n        manager.updateReadMarker(providerName);\n\n        if (!!lastChannelId) {\n            // lastChannelId should always exist since this will only be\n            // called after loading the webview (which requires lastChannelId)\n            return manager.sendMessage(providerName, text, lastChannelId, parentTimestamp);\n        }\n    };\n\n    const askForChannel = async (\n        providerName: string | undefined\n    ): Promise<{ channel: Channel; providerName: string } | undefined> => {\n        // This can be called with an undefined providerName, in which\n        // case we show channels from all available providers.\n        let channelList = manager.getChannelLabels(providerName).sort((a, b) => b.unread - a.unread);\n\n        const quickpickItems: vscode.QuickPickItem[] = channelList.map(channelLabel => {\n            const description = `${channelLabel.providerName} · ${channelLabel.teamName}`;\n            return {\n                label: channelLabel.label,\n                detail: channelLabel.channel.categoryName,\n                description\n            };\n        });\n        const finalList = [...quickpickItems, { label: str.RELOAD_CHANNELS }];\n        const selected = await vscode.window.showQuickPick(finalList, {\n            placeHolder: str.CHANGE_CHANNEL_TITLE,\n            matchOnDetail: true,\n            matchOnDescription: true\n        });\n\n        if (!!selected) {\n            if (selected.label === str.RELOAD_CHANNELS) {\n                let currentProvider = providerName;\n\n                if (!currentProvider) {\n                    const providers = manager.store.getCurrentUserForAll().map(userInfo => userInfo.provider);\n                    currentProvider = await askForProvider(providers);\n                }\n\n                if (!!currentProvider) {\n                    await manager.fetchUsers(currentProvider);\n                    await manager.fetchChannels(currentProvider);\n                    return askForChannel(providerName);\n                }\n            }\n\n            const selectedChannelLabel = channelList.find(\n                x => x.label === selected.label && x.channel.categoryName === selected.detail\n            );\n\n            if (!!selectedChannelLabel) {\n                const { channel, providerName } = selectedChannelLabel;\n                return { channel, providerName: providerName.toLowerCase() };\n            }\n        }\n    };\n\n    const openChatWebview = async (chatArgs?: ChatArgs) => {\n        let provider = !!chatArgs ? chatArgs.providerName : undefined;\n        let channelId = !!chatArgs ? chatArgs.channelId : undefined;\n        const source = !!chatArgs ? chatArgs.source : EventSource.command;\n\n        if (!chatArgs) {\n            const selected = await askForChannel(undefined);\n\n            if (!!selected) {\n                provider = selected.providerName;\n                channelId = selected.channel.id;\n            }\n        }\n\n        if (!!provider && !!channelId) {\n            controller.updateCurrentState(provider, channelId, source);\n            controller.loadUi();\n\n            await setup(true, undefined);\n            await manager.updateWebviewForProvider(provider, channelId);\n            telemetry.record(EventType.viewOpened, source, channelId, provider);\n            manager.loadChannelHistory(provider, channelId);\n        }\n    };\n\n    const onUIDispose = (provider: string | undefined, openSource: EventSource | undefined) => {\n    };\n\n    const askForWorkspace = async (provider: string): Promise<Team | undefined> => {\n        const currentUserInfo = manager.store.getCurrentUser(provider);\n\n        if (!!currentUserInfo) {\n            const { teams } = currentUserInfo;\n            const labels = teams.map(team => team.name);\n\n            const selected = await vscode.window.showQuickPick([...labels], {\n                placeHolder: str.CHANGE_WORKSPACE_TITLE\n            });\n\n            if (!!selected) {\n                return teams.find(team => team.name === selected);\n            }\n        }\n    };\n\n    const changeWorkspace = async (providerAndTeam?: any) => {\n        let provider: string | undefined, team;\n\n        if (!providerAndTeam) {\n            const currentUsers = manager.store.getCurrentUserForAll();\n            const withMultipleTeams = currentUsers.filter(userInfo => userInfo.teams.length > 1);\n            provider = await askForProvider(withMultipleTeams.map(userInfo => userInfo.provider));\n\n            if (!provider) {\n                return;\n            }\n\n            const userInfo = withMultipleTeams.find(userInfo => userInfo.provider === provider);\n\n            if (!!userInfo) {\n                const teamNames = userInfo.teams.map(team => team.name);\n                const selection = await vscode.window.showQuickPick(teamNames, {\n                    placeHolder: str.CHANGE_PROVIDER_TITLE\n                });\n\n                if (selection) {\n                    team = userInfo.teams.find(team => team.name === selection);\n                }\n            }\n        } else {\n            provider = providerAndTeam.provider;\n            team = providerAndTeam.team;\n        }\n\n        if (provider && team) {\n            const isDifferentTeam = team.id !== manager.getCurrentTeamIdFor(provider);\n\n            if (isDifferentTeam) {\n                manager.updateCurrentWorkspace(provider, team);\n                await manager.clearOldWorkspace(provider);\n                await setup(false, { provider, teamId: team.id });\n            }\n        }\n    };\n\n    const changeChannel = async (args?: ChatArgs) => {\n        const provider = args ? args.providerName : undefined;\n        telemetry.record(EventType.channelChanged, !!args ? args.source : EventSource.command, undefined, provider);\n\n        const selected = await askForChannel(provider);\n\n        if (!!selected) {\n            let chatArgs: any = { ...args };\n            chatArgs.channelId = selected.channel.id;\n            chatArgs.providerName = selected.providerName;\n            return openChatWebview(chatArgs);\n        }\n    };\n\n    const shareVslsLink = async (chatArgs: ChatArgs) => {\n        // This method can assume chatArgs to have one of channel and user\n        const { providerName } = chatArgs;\n        const liveshare = await vsls.getApi();\n\n        if (!!liveshare) {\n            const vslsUri = await liveshare.share({\n                suppressNotification: true\n            });\n            let channelId = chatArgs.channelId;\n            const user = chatArgs.user;\n\n            if (!channelId && user) {\n                const newChannel = await manager.createIMChannel(chatArgs.providerName, user);\n\n                if (!!newChannel) {\n                    channelId = newChannel.id;\n                }\n            }\n\n            telemetry.record(EventType.vslsShared, EventSource.activity, channelId, providerName);\n\n            if (vslsUri && channelId) {\n                manager.sendMessage(providerName, vslsUri.toString(), channelId, undefined);\n            }\n        }\n    };\n\n    const startOAuth = (args?: any) => {\n        const hasArgs = !!args && !!args.source;\n        const provider = \"slack\"; // Only Slack OAuth is supported\n        const urls = {\n            slack: SLACK_OAUTH,\n            discord: DISCORD_OAUTH\n        };\n        telemetry.record(EventType.authStarted, hasArgs ? args.source : EventSource.command, undefined, provider);\n        return utils.openUrl(urls[provider]);\n    };\n\n    const reset = async () => {\n        // Reset clears all state from local storage (except for vsls chat\n        // related state, since that does not get affected via call paths to reset)\n        manager.clearAll();\n        manager.updateAllUI();\n        await setup(false, undefined);\n    };\n\n    const signout = async () => {\n        await manager.signout();\n    };\n\n    const updateSelfPresence = async (provider: string, presence: UserPresence) => {\n        const isSlack = provider === \"slack\";\n        let durationInMinutes = 0;\n\n        if (presence === UserPresence.doNotDisturb && isSlack) {\n            // Ask for duration for dnd.snooze for slack implementation\n            const options: { [label: string]: number } = {\n                \"20 minutes\": 20,\n                \"1 hour\": 60,\n                \"2 hours\": 120,\n                \"4 hours\": 240,\n                \"8 hours\": 480,\n                \"24 hours\": 1440\n            };\n            const selected = await vscode.window.showQuickPick(Object.keys(options), {\n                placeHolder: str.SELECT_DND_DURATION\n            });\n            durationInMinutes = !!selected ? options[selected] : 0;\n        }\n\n        manager.updateSelfPresence(provider, presence, durationInMinutes);\n    };\n\n    const askForSelfPresence = async () => {\n        // Called when user triggers a change for self presence\n        // using manual command.\n        const enabledProviders = manager.getEnabledProviders();\n        const providerNames = enabledProviders.map(element => element.provider);\n        const provider = providerNames.find(provider => provider !== \"vsls\");\n\n        if (!!provider) {\n            const isSlack = provider === \"slack\";\n            const currentPresence = manager.getCurrentUserPresence(provider);\n            const presenceChoices = [UserPresence.available, UserPresence.doNotDisturb, UserPresence.invisible];\n\n            if (!isSlack) {\n                // Slack does not have the idle option\n                presenceChoices.push(UserPresence.idle);\n            }\n\n            const items: vscode.QuickPickItem[] = presenceChoices.map(choice => {\n                const isCurrent = currentPresence === choice;\n                return {\n                    label: utils.camelCaseToTitle(choice),\n                    description: isCurrent ? \"current\" : \"\"\n                };\n            });\n            const status = await vscode.window.showQuickPick(items, {\n                placeHolder: str.SELECT_SELF_PRESENCE\n            });\n\n            if (!!status) {\n                const presence = utils.titleCaseToCamel(status.label) as UserPresence;\n                updateSelfPresence(provider, presence);\n            }\n        }\n    };\n\n    const fetchReplies = (provider: string, parentTimestamp: string) => {\n        manager.fetchThreadReplies(provider, parentTimestamp);\n    };\n\n    const resetConfiguration = (event: vscode.ConfigurationChangeEvent) => {\n        const affectsExtension = event.affectsConfiguration(CONFIG_ROOT);\n\n        if (affectsExtension) {\n            // We can have a tighter check here to prevent losing slack/discord setup\n            // whenever the config changes.\n            const needsReset = !event.affectsConfiguration(CONFIG_AUTO_LAUNCH);\n\n            if (needsReset) {\n                reset();\n            }\n        }\n    };\n\n    const setVslsContext = () => {\n        const isEnabled = utils.hasVslsExtension();\n        utils.setVsContext(\"chat:vslsEnabled\", isEnabled);\n    };\n\n    const askForProvider = async (enabledProviders: string[]) => {\n        // VSLS providers are no longer supported. The user can still have these in their store.\n        // Remove these from the list.\n        const values = (enabledProviders.map(name => utils.toTitleCase(name))).filter(p => p !== 'Vsls');\n        const selection = await vscode.window.showQuickPick(values, {\n            placeHolder: str.CHANGE_PROVIDER_TITLE\n        });\n        return !!selection ? selection.toLowerCase() : undefined;\n    };\n\n    const configureToken = async () => {\n        const provider = await askForProvider([\"slack\", \"discord\"]);\n        telemetry.record(EventType.tokenConfigured, EventSource.command, undefined, provider);\n\n        if (!!provider) {\n            const inputToken = await vscode.window.showInputBox({\n                placeHolder: str.TOKEN_PLACEHOLDER,\n                password: true\n            });\n\n            if (!!inputToken) {\n                const sanitisedToken = utils.sanitiseTokenString(inputToken);\n\n                try {\n                    const tokenUser = await manager.validateToken(provider, sanitisedToken);\n\n                    if (!!tokenUser) {\n                        const teamId = provider === \"slack\" ? tokenUser.currentTeamId : undefined;\n                        return ConfigHelper.setToken(sanitisedToken, provider, teamId);\n                    }\n                } catch (error) {\n                    const actionItems = [str.REPORT_ISSUE];\n                    const messageResult = await vscode.window.showErrorMessage(\n                        str.INVALID_TOKEN(utils.toTitleCase(provider)),\n                        ...actionItems\n                    );\n\n                    if (!!messageResult && messageResult === str.REPORT_ISSUE) {\n                        const issue = `[${provider}] Invalid token`;\n                        IssueReporter.openNewIssue(issue, \"\");\n                    }\n\n                    return;\n                }\n            }\n        }\n    };\n\n    const getContactFromItem = async (item: any) => {\n        let contact: vsls.Contact | undefined;\n\n        if (!!item.space) {\n            // This is a space member, we need to convert to an LS contact\n            const { email } = item;\n            const api = (await vsls.getApi())!;\n            const { contacts } = await api.getContacts([email]);\n            contact = contacts[email];\n        } else {\n            contact = item.contactModel.contact;\n        }\n\n        return contact;\n    };\n\n    const openVslsSpaceChat = async (spaceName: string) => {\n        const api = utils.getExtension(VSLS_SPACES_EXTENSION_ID)!.exports;\n        const { name, email } = api.getUserInfo();\n        await manager.store.updateCurrentUser(\"vslsSpaces\", {\n            id: email,\n            name,\n            teams: [],\n            currentTeamId: undefined,\n            provider: Providers.vslsSpaces\n        });\n        return openChatWebview({\n            providerName: \"vslsSpaces\",\n            channelId: spaceName,\n            source: EventSource.command\n        });\n    };\n\n    // Setup real-time messenger and updated local state\n    setup(true, undefined);\n\n    // Setup context for conditional views\n    setVslsContext();\n\n    const uriHandler = new ExtensionUriHandler();\n    context.subscriptions.push(\n        vscode.commands.registerCommand(SelfCommands.OPEN_WEBVIEW, openChatWebview),\n        vscode.commands.registerCommand(SelfCommands.CHANGE_WORKSPACE, changeWorkspace),\n        vscode.commands.registerCommand(SelfCommands.CHANGE_CHANNEL, changeChannel),\n        vscode.commands.registerCommand(SelfCommands.SIGN_IN, startOAuth),\n        vscode.commands.registerCommand(SelfCommands.SIGN_OUT, signout),\n        vscode.commands.registerCommand(SelfCommands.RESET_STORE, reset),\n        vscode.commands.registerCommand(SelfCommands.SETUP_NEW_PROVIDER, ({ newInitialState }) =>\n            setup(false, newInitialState)\n        ),\n        vscode.commands.registerCommand(SelfCommands.CONFIGURE_TOKEN, configureToken),\n        vscode.commands.registerCommand(SelfCommands.SEND_MESSAGE, ({ text, provider }) =>\n            sendMessage(provider, text, undefined)\n        ),\n        vscode.commands.registerCommand(SelfCommands.SEND_THREAD_REPLY, ({ text, parentTimestamp, provider }) =>\n            sendMessage(provider, text, parentTimestamp)\n        ),\n        vscode.commands.registerCommand(SelfCommands.LIVE_SHARE_FROM_MENU, (item: ChatTreeNode) => {\n            return shareVslsLink({\n                channelId: item.channel ? item.channel.id : undefined,\n                user: item.user,\n                providerName: item.providerName,\n                source: EventSource.activity\n            });\n        }),\n        vscode.commands.registerCommand(SelfCommands.LIVE_SHARE_SLASH, ({ provider }) => {\n            const channelId = manager.store.getLastChannelId(provider);\n            shareVslsLink({\n                channelId,\n                user: undefined,\n                providerName: provider,\n                source: EventSource.slash\n            });\n        }),\n        vscode.commands.registerCommand(\n            SelfCommands.LIVE_SHARE_SESSION_CHANGED,\n            async ({ isSessionActive, currentUser }) => {\n                if (!currentUser) {\n                    // If the currentUser is undefined, don't launch the window\n                    return;\n                }\n\n                const enabledProviders = manager.getEnabledProviders().map(e => e.provider);\n\n                const eventType = isSessionActive ? EventType.vslsStarted : EventType.vslsEnded;\n                telemetry.record(eventType, undefined, undefined, undefined);\n            }\n        ),\n        vscode.commands.registerCommand(SelfCommands.FETCH_REPLIES, ({ parentTimestamp, provider }) =>\n            fetchReplies(provider, parentTimestamp)\n        ),\n        vscode.commands.registerCommand(SelfCommands.UPDATE_MESSAGES, ({ channelId, messages, provider }) => {\n            manager.updateMessages(provider, channelId, messages);\n        }),\n        vscode.commands.registerCommand(SelfCommands.CLEAR_MESSAGES, ({ channelId, provider }) => {\n            manager.clearMessages(provider, channelId);\n        }),\n        vscode.commands.registerCommand(\n            SelfCommands.ADD_MESSAGE_REACTION,\n            ({ userId, msgTimestamp, channelId, reactionName, provider }) => {\n                manager.addReaction(provider, channelId, msgTimestamp, userId, reactionName);\n            }\n        ),\n        vscode.commands.registerCommand(\n            SelfCommands.REMOVE_MESSAGE_REACTION,\n            ({ userId, msgTimestamp, channelId, reactionName, provider }) => {\n                manager.removeReaction(provider, channelId, msgTimestamp, userId, reactionName);\n            }\n        ),\n        vscode.commands.registerCommand(SelfCommands.UPDATE_PRESENCE_STATUSES, ({ userId, presence, provider }) => {\n            manager.updatePresenceForUser(provider, userId, presence);\n        }),\n        vscode.commands.registerCommand(SelfCommands.UPDATE_SELF_PRESENCE, askForSelfPresence),\n        vscode.commands.registerCommand(SelfCommands.UPDATE_SELF_PRESENCE_VIA_VSLS, ({ presence, provider }) => {\n            // Disabled to test auto-away fix\n            // updateSelfPresence(provider, presence)\n        }),\n        vscode.commands.registerCommand(\n            SelfCommands.CHANNEL_MARKED,\n            ({ channelId, readTimestamp, unreadCount, provider }) => {\n                return manager.updateChannelMarked(provider, channelId, readTimestamp, unreadCount);\n            }\n        ),\n        vscode.commands.registerCommand(\n            SelfCommands.UPDATE_MESSAGE_REPLIES,\n            ({ provider, channelId, parentTimestamp, reply }) => {\n                manager.updateMessageReply(provider, parentTimestamp, channelId, reply);\n            }\n        ),\n        vscode.commands.registerCommand(SelfCommands.SHOW_TYPING, ({ provider, typingUserId, channelId }) => {\n            manager.updateWebviewForProvider(provider, channelId, typingUserId);\n            const key = `${channelId}:${typingUserId}`;\n\n            if (typingTimers[key]) {\n                clearTimeout(typingTimers[key] as NodeJS.Timer);\n                typingTimers[key] = undefined;\n            }\n\n            const newTimer = setTimeout(() => {\n                // This removes typing status --> this timeout should be larger than\n                // the time period between typing events sent from the wire + the time\n                // it takes to transfer them over the wire.\n                manager.updateWebviewForProvider(provider, channelId, undefined);\n            }, 5000);\n\n            typingTimers[key] = newTimer;\n        }),\n        vscode.commands.registerCommand(SelfCommands.SEND_TO_WEBVIEW, ({ uiMessage }) =>\n            controller.sendToUI(uiMessage)\n        ),\n        vscode.commands.registerCommand(SelfCommands.CHAT_WITH_VSLS_SPACE, ({ space }) => {\n            const { name: spaceName } = space;\n            return openVslsSpaceChat(spaceName);\n        }),\n        vscode.commands.registerCommand(SelfCommands.VSLS_SPACE_JOINED, async ({ name }) => {\n            // Update store and launch the webview\n            await manager.fetchUsers(\"vslsSpaces\");\n            await manager.fetchChannels(\"vslsSpaces\");\n            return openVslsSpaceChat(name);\n        }),\n        vscode.workspace.onDidChangeConfiguration(resetConfiguration),\n        vscode.workspace.registerTextDocumentContentProvider(TRAVIS_SCHEME, travis),\n        vscode.window.registerUriHandler(uriHandler),\n        manager,\n        telemetry\n    );\n\n    // telemetry.record(\n    //     EventType.activationEnded,\n    //     undefined,\n    //     undefined,\n    //     undefined\n    // );\n}\n\nexport function deactivate() {}\n"
  },
  {
    "path": "src/issues.ts",
    "content": "import { openUrl, getVersions } from \"./utils\";\n\nconst BASE_ISSUES_URL = \"https://github.com/karigari/vscode-chat/issues/new\";\n\nexport default class IssueReporter {\n  static getVersionString() {\n    const { extension, os, editor } = getVersions();\n    return `- Extension Version: ${extension}\\n- OS Version: ${os}\\n- VSCode version: ${editor}`;\n  }\n\n  static getUrl(query: object) {\n    const getParams = (p: object) =>\n      Object.entries(p)\n        .map(kv => kv.map(encodeURIComponent).join(\"=\"))\n        .join(\"&\");\n    return `${BASE_ISSUES_URL}?${getParams(query)}`;\n  }\n\n  static openNewIssue(title: string, body: string) {\n    const versions = this.getVersionString();\n    const bodyText = `${body}\\n\\n${versions}`.replace(/\\n/g, \"%0A\");\n    const params = { title: `[vscode] ${title}`, body: bodyText };\n    return openUrl(this.getUrl(params));\n  }\n}\n"
  },
  {
    "path": "src/logger.ts",
    "content": "import * as vscode from \"vscode\";\nimport { OUTPUT_CHANNEL_NAME } from \"./constants\";\n\nexport default class Logger {\n  static output: vscode.OutputChannel | undefined;\n\n  static setup() {\n    this.output =\n      this.output || vscode.window.createOutputChannel(OUTPUT_CHANNEL_NAME);\n  }\n\n  private static get timestamp(): string {\n    const now = new Date();\n    return now.toLocaleString();\n  }\n\n  private static logOnConsole(message: string): void {\n    console.log(message);\n  }\n\n  private static logOnOutput(message: string): void {\n    if (this.output === undefined) {\n      this.setup();\n    }\n\n    if (!!this.output) {\n      this.output.appendLine(message);\n    }\n  }\n\n  static log(message: any): void {\n    const logLine = `[${this.timestamp}] Chat: ${message}`;\n    return process.env.IS_DEBUG === \"true\"\n      ? this.logOnConsole(logLine)\n      : this.logOnOutput(logLine);\n  }\n}\n"
  },
  {
    "path": "src/manager/chatManager.ts",
    "content": "import { isSuperset, difference, toTitleCase } from \"../utils\";\n\nexport class ChatProviderManager {\n    messages: Messages = {};\n    currentUserPrefs: UserPreferences = {};\n    stateFetchedAt: Date | undefined;\n\n    constructor(\n        private store: IStore,\n        public providerName: string,\n        public teamId: string | undefined,\n        private chatProvider: IChatProvider,\n        private parentManager: IManager\n    ) {}\n\n    getTeams(): Team[] {\n        // Due to design limitation we can only work with one team at a time,\n        // and so this only returns the current team. (or else, Discord shows\n        // multiple status items for unread messages.)\n        const currentTeam = this.getCurrentTeam();\n        return !!currentTeam ? [currentTeam] : [];\n    }\n\n    getCurrentTeam(): Team | undefined {\n        const currentUser = this.store.getCurrentUser(this.providerName);\n        return !!currentUser ? currentUser.teams.find(team => team.id === currentUser.currentTeamId) : undefined;\n    }\n\n    initializeProvider = async (): Promise<any> => {\n        const isConnected = this.chatProvider.isConnected();\n        const isAuthenticated = this.isAuthenticated();\n        let currentUser = this.store.getCurrentUser(this.providerName);\n\n        if (!(isConnected && isAuthenticated)) {\n            if (!!this.chatProvider) {\n                currentUser = await this.chatProvider.connect();\n                this.store.updateCurrentUser(this.providerName, currentUser);\n            }\n        }\n\n        return currentUser;\n    };\n\n    isAuthenticated() {\n        const currentUserInfo = this.store.getCurrentUser(this.providerName);\n        return !!currentUserInfo && !!currentUserInfo.id;\n    }\n\n    destroy() {\n        this.chatProvider.destroy();\n    }\n\n    updateWebviewForLastChannel() {\n        const lastChannelId = this.store.getLastChannelId(this.providerName);\n\n        if (!!lastChannelId) {\n            this.parentManager.updateWebviewForProvider(this.providerName, lastChannelId);\n        }\n    }\n\n    async fetchThreadReplies(parentTimestamp: string) {\n        const currentChannelId = this.store.getLastChannelId(this.providerName);\n\n        if (!!currentChannelId) {\n            const message = await this.chatProvider.fetchThreadReplies(currentChannelId, parentTimestamp);\n\n            if (!!message) {\n                let messages: ChannelMessages = {};\n                messages[parentTimestamp] = message;\n                this.updateMessages(currentChannelId, messages);\n            }\n        }\n    }\n\n    updateSelfPresence = async (presence: UserPresence, durationInMinutes: number) => {\n        const currentUserInfo = this.store.getCurrentUser(this.providerName);\n\n        if (!!currentUserInfo) {\n            const presenceResult = await this.chatProvider.updateSelfPresence(presence, durationInMinutes);\n\n            if (!!presenceResult) {\n                this.updatePresenceForUser(currentUserInfo.id, presenceResult);\n            }\n        }\n    };\n\n    updatePresenceForUser = (userId: string, presence: UserPresence) => {\n        const users = this.store.getUsers(this.providerName);\n\n        if (userId in users) {\n            const existingPresence = users[userId].presence;\n\n            if (existingPresence === UserPresence.invisible && presence === UserPresence.offline) {\n                // If we know user is `invisible`, then `offline` presence change\n                // should be ignored. This will only happen for self.\n                return;\n            }\n\n            this.store.updateUser(this.providerName, userId, {\n                ...users[userId],\n                presence\n            });\n\n            if (presence !== existingPresence) {\n                this.parentManager.updateTreeViewsForProvider(this.providerName);\n            }\n        }\n    };\n\n    sendMessage = (text: string, channelId: string, parentTimestamp: string | undefined): Promise<void> => {\n        const currentUserInfo = this.store.getCurrentUser(this.providerName);\n\n        if (!!currentUserInfo) {\n            if (!!parentTimestamp) {\n                // This is a thread reply\n                return this.chatProvider.sendThreadReply(text, currentUserInfo.id, channelId, parentTimestamp);\n            } else {\n                // THis is a normal message\n                return this.chatProvider.sendMessage(text, currentUserInfo.id, channelId);\n            }\n        }\n\n        return Promise.resolve();\n    };\n\n    clearMessages = (channelId: string) => {\n        const existingMessages = channelId in this.messages ? this.messages[channelId] : {};\n        const deletedMessages: any = {};\n        Object.keys(existingMessages).forEach((ts: string) => {\n            deletedMessages[ts] = undefined;\n        });\n\n        return this.updateMessages(channelId, deletedMessages);\n    };\n\n    updateMessages = (channelId: string, messages: ChannelMessagesWithUndefined) => {\n        const existingMessages = channelId in this.messages ? this.messages[channelId] : {};\n        const deletedTimestamps = Object.keys(messages).filter(ts => typeof messages[ts] === \"undefined\");\n\n        const newMessages: ChannelMessages = {};\n        Object.keys(existingMessages).forEach(ts => {\n            const isDeleted = deletedTimestamps.indexOf(ts) >= 0;\n            if (!isDeleted) {\n                newMessages[ts] = existingMessages[ts];\n            }\n        });\n        Object.keys(messages).forEach(ts => {\n            const message = messages[ts];\n            if (!!message) {\n                newMessages[ts] = message;\n            }\n        });\n        this.messages[channelId] = newMessages;\n\n        // Remove undefined, after message deleted\n        Object.keys(this.messages[channelId]).forEach(key => {\n            if (typeof this.messages[channelId][key] === \"undefined\") {\n                delete this.messages[channelId][key];\n            }\n        });\n\n        // Check if we have all users. Since there is no `bots.list` Slack API\n        // method, it is possible that a bot user is not in our store\n        const users = this.store.getUsers(this.providerName);\n        const knownUserIds = new Set(Object.keys(users));\n        const channelMessages = this.messages[channelId];\n        const entries = Object.entries(channelMessages);\n        const userIds = new Set(entries.map(([_, message]) => message.userId));\n\n        if (!isSuperset(knownUserIds, userIds)) {\n            this.fillUpUsers(difference(userIds, knownUserIds));\n        }\n\n        this.updateWebviewForLastChannel();\n        this.parentManager.updateStatusItemsForProvider(this.providerName);\n        this.parentManager.updateTreeViewsForProvider(this.providerName);\n    };\n\n    sendTyping = (channelId: string) => {\n        const currentUser = this.store.getCurrentUser(this.providerName);\n\n        if (currentUser) {\n            return this.chatProvider.sendTyping(currentUser.id, channelId)\n        }\n    };\n\n    private async fillUpUsers(missingIds: Set<any>): Promise<void> {\n        // missingIds are user/bot ids that we don't have in the store. We will\n        // fetch their details, and then update the UI.\n        const users = this.store.getUsers(this.providerName);\n        const usersCopy: Users = { ...users };\n        let ids = Array.from(missingIds);\n\n        await Promise.all(\n            ids.map(async userId => {\n                let user = await this.chatProvider.fetchUserInfo(userId);\n\n                if (!!user) {\n                    const { id } = user;\n                    usersCopy[id] = user;\n                }\n            })\n        );\n\n        this.store.updateUsers(this.providerName, usersCopy);\n        this.updateWebviewForLastChannel();\n    }\n\n    updateMessageReply(parentTimestamp: string, channelId: string, reply: MessageReply) {\n        // We need to have the message in our store, else we\n        // ignore this reply\n        const messages = channelId in this.messages ? this.messages[channelId] : {};\n        const message = parentTimestamp in messages ? messages[parentTimestamp] : undefined;\n\n        if (!!message) {\n            let newMessages: ChannelMessages = {};\n            const replyTs = reply.timestamp;\n            let replies: MessageReplies = { ...message.replies };\n            replies[replyTs] = { ...reply };\n            newMessages[parentTimestamp] = {\n                ...message,\n                replies\n            };\n            this.updateMessages(channelId, newMessages);\n        }\n    }\n\n    removeReaction(channelId: string, msgTimestamp: string, userId: string, reactionName: string) {\n        if (channelId in this.messages) {\n            const channelMessages = this.messages[channelId];\n\n            if (msgTimestamp in channelMessages) {\n                const message = channelMessages[msgTimestamp];\n                let { reactions } = message;\n                reactions = reactions\n                    .map(r => {\n                        if (r.name === reactionName) {\n                            return {\n                                ...r,\n                                count: r.count - 1,\n                                userIds: r.userIds.filter(u => u !== userId)\n                            };\n                        } else {\n                            return { ...r };\n                        }\n                    })\n                    .filter(r => r.count > 0);\n\n                const newMessage = {\n                    ...message,\n                    reactions\n                };\n                const newMessages: ChannelMessages = {};\n                newMessages[msgTimestamp] = newMessage;\n                this.updateMessages(channelId, newMessages);\n            }\n        }\n    }\n\n    addReaction(channelId: string, msgTimestamp: string, userId: string, reactionName: string) {\n        if (channelId in this.messages) {\n            const channelMessages = this.messages[channelId];\n\n            if (msgTimestamp in channelMessages) {\n                const message = channelMessages[msgTimestamp];\n                let { reactions } = message;\n                const existing = reactions.find(r => r.name === reactionName);\n\n                if (existing) {\n                    reactions = reactions.map(r => {\n                        if (r.name === reactionName) {\n                            return {\n                                ...existing,\n                                count: existing.count + 1,\n                                userIds: [...existing.userIds, userId]\n                            };\n                        } else {\n                            return { ...r };\n                        }\n                    });\n                } else {\n                    reactions = [...reactions, { name: reactionName, userIds: [userId], count: 1 }];\n                }\n\n                const newMessage = {\n                    ...message,\n                    reactions\n                };\n                const newMessages: ChannelMessages = {};\n                newMessages[msgTimestamp] = newMessage;\n                this.updateMessages(channelId, newMessages);\n            }\n        }\n    }\n\n    async loadChannelHistory(channelId: string): Promise<void> {\n        try {\n            const messages = await this.chatProvider.loadChannelHistory(channelId);\n            return this.updateMessages(channelId, messages);\n        } catch (error) {\n            return console.error(error);\n        }\n    }\n\n    async updateUserPrefs() {\n        const response = await this.chatProvider.getUserPreferences();\n\n        if (!!response) {\n            // We could also save the muted channels to local storage\n            this.currentUserPrefs = response;\n            this.parentManager.updateStatusItemsForProvider(this.providerName);\n        }\n    }\n\n    async createIMChannel(user: User): Promise<Channel | undefined> {\n        const channel = await this.chatProvider.createIMChannel(user);\n\n        if (!!channel) {\n            await this.updateChannel(channel);\n            return channel;\n        }\n    }\n\n    subscribeForPresence() {\n        const users = this.store.getUsers(this.providerName);\n\n        if (!!this.chatProvider) {\n            this.chatProvider.subscribePresence(users);\n        }\n    }\n\n    updateChannel = async (newChannel: Channel) => {\n        // Adds/updates channel in this.channels\n        let found = false;\n        const channels = this.store.getChannels(this.providerName);\n        let updatedChannels = channels.map(channel => {\n            const { id } = channel;\n\n            if (id === newChannel.id) {\n                found = true;\n                return {\n                    ...channel,\n                    ...newChannel\n                };\n            } else {\n                return channel;\n            }\n        });\n\n        if (!found) {\n            updatedChannels = [...updatedChannels, newChannel];\n        }\n\n        await this.store.updateChannels(this.providerName, updatedChannels);\n        this.parentManager.updateTreeViewsForProvider(this.providerName);\n    };\n\n    updateChannelMarked(channelId: string, readTimestamp: string, unreadCount: number) {\n        const channel = this.getChannel(channelId);\n\n        if (!!channel) {\n            this.updateChannel({ ...channel, readTimestamp, unreadCount });\n            this.updateWebviewForLastChannel();\n            this.parentManager.updateStatusItemsForProvider(this.providerName);\n            this.parentManager.updateTreeViewsForProvider(this.providerName);\n        }\n    }\n\n    fetchUnreadCounts = async (channels: Channel[]) => {\n        // We have to fetch twice here because Slack does not return the\n        // historical unread counts for channels in the list API.\n        const promises = channels.map(async channel => {\n            const newChannel = await this.chatProvider.fetchChannelInfo(channel);\n\n            if (!!newChannel && newChannel.unreadCount !== channel.unreadCount) {\n                return this.updateChannel(newChannel);\n            }\n        });\n\n        await Promise.all(promises);\n        this.parentManager.updateStatusItemsForProvider(this.providerName);\n    };\n\n    fetchUsers = async (): Promise<Users> => {\n        const users = await this.chatProvider.fetchUsers();\n        let usersWithPresence: Users = {};\n        const existingUsers = this.store.getUsers(this.providerName);\n\n        Object.keys(users).forEach(userId => {\n            // This handles two different chat providers:\n            // In slack, we will get isOnline as undefined, because this API\n            //    does not know about user presence\n            // In discord, we will get true/false\n            const existingUser = userId in existingUsers ? existingUsers[userId] : null;\n            const newUser = users[userId];\n            let calculatedPresence: UserPresence;\n\n            if (newUser.presence !== UserPresence.unknown) {\n                calculatedPresence = newUser.presence;\n            } else {\n                calculatedPresence = !!existingUser ? existingUser.presence : UserPresence.unknown;\n            }\n\n            usersWithPresence[userId] = {\n                ...users[userId],\n                presence: calculatedPresence\n            };\n        });\n\n        this.store.updateUsers(this.providerName, usersWithPresence);\n        return usersWithPresence;\n    };\n\n    fetchChannels = async (): Promise<Channel[]> => {\n        const users = this.store.getUsers(this.providerName);\n        const channels = await this.chatProvider.fetchChannels(users);\n        await this.store.updateChannels(this.providerName, channels);\n        this.parentManager.updateTreeViewsForProvider(this.providerName);\n        this.fetchUnreadCounts(channels);\n        return channels;\n    };\n\n    private shouldFetchNew = (lastFetchedAt: Date | undefined): boolean => {\n        if (!lastFetchedAt) {\n            return true;\n        }\n\n        const now = new Date();\n        const difference = now.valueOf() - lastFetchedAt.valueOf();\n        const FETCH_THRESHOLD = 15 * 60 * 1000; // 15-mins\n        return difference > FETCH_THRESHOLD;\n    };\n\n    async initializeState(): Promise<void> {\n        const users = this.store.getUsers(this.providerName);\n        const hasCachedUsers = Object.keys(users).length !== 0;\n\n        if (!hasCachedUsers) {\n            await this.fetchUsers();\n            const channels = this.store.getChannels(this.providerName);\n            const hasCachedChannels = channels.length !== 0;\n\n            if (!hasCachedChannels) {\n                await this.fetchChannels();\n                this.stateFetchedAt = new Date();\n            }\n\n            return;\n        }\n\n        // We already have a copy of the state, but if it's old, we run an async update\n        if (this.shouldFetchNew(this.stateFetchedAt)) {\n            this.fetchUsers().then(users => {\n                this.fetchChannels();\n                this.stateFetchedAt = new Date();\n            });\n        }\n    }\n\n    getChannel(channelId: string | undefined): Channel | undefined {\n        if (!!channelId) {\n            const channels = this.store.getChannels(this.providerName);\n            return channels.find(channel => channel.id === channelId);\n        }\n    }\n\n    getLastTimestamp(): string | undefined {\n        const channelId = this.store.getLastChannelId(this.providerName);\n        const channelMessages = !!channelId && channelId in this.messages ? this.messages[channelId] : {};\n        const timestamps = Object.keys(channelMessages).map(tsString => +tsString);\n\n        if (timestamps.length > 0) {\n            return Math.max(...timestamps).toString();\n        }\n    }\n\n    async updateReadMarker(): Promise<void> {\n        const channelId = this.store.getLastChannelId(this.providerName);\n        const channel = this.getChannel(channelId);\n        const lastTs = this.getLastTimestamp();\n\n        if (channel && lastTs) {\n            const { readTimestamp } = channel;\n            const hasNewerMsgs = !!readTimestamp ? +readTimestamp < +lastTs : true;\n\n            if (hasNewerMsgs) {\n                const incremented = (+lastTs + 1).toString(); // Slack API workaround\n                const updatedChannel = await this.chatProvider.markChannel(channel, incremented);\n\n                if (!!updatedChannel) {\n                    this.updateChannel(updatedChannel);\n                    this.updateWebviewForLastChannel();\n                    this.parentManager.updateStatusItemsForProvider(this.providerName);\n                    this.parentManager.updateTreeViewsForProvider(this.providerName);\n                }\n            }\n        }\n    }\n\n    private isChannelMuted(channelId: string): boolean {\n        const { mutedChannels } = this.currentUserPrefs;\n        return !!mutedChannels && mutedChannels.indexOf(channelId) >= 0;\n    }\n\n    getUnreadCount(channel: Channel): number {\n        const { id, readTimestamp, unreadCount } = channel;\n\n        if (this.isChannelMuted(id)) {\n            // This channel is muted, so return 0\n            return 0;\n        }\n\n        const currentUserInfo = this.store.getCurrentUser(this.providerName);\n\n        if (!currentUserInfo) {\n            // Can be undefined during async update on vsls chat\n            return 0;\n        }\n\n        const messages = id in this.messages ? this.messages[id] : {};\n\n        const unreadMessages = Object.keys(messages).filter(ts => {\n            const isDifferentUser = messages[ts].userId !== currentUserInfo.id;\n            const isNewTimestamp = !!readTimestamp ? +ts > +readTimestamp : false;\n            return isDifferentUser && isNewTimestamp;\n        });\n\n        return unreadCount ? unreadCount : unreadMessages.length;\n    }\n\n    getChannelLabels(): ChannelLabel[] {\n        const channels = this.store.getChannels(this.providerName);\n        const users = this.store.getUsers(this.providerName);\n        const providerName = toTitleCase(this.providerName);\n        const currentTeam = this.getCurrentTeam();\n        const teamName = !!currentTeam ? currentTeam.name : \"\";\n\n        return channels.map(channel => {\n            const unread = this.getUnreadCount(channel);\n            const { name, type, id } = channel;\n            const isMuted = this.isChannelMuted(id);\n            let presence: UserPresence = UserPresence.unknown;\n\n            if (type === ChannelType.im) {\n                const relatedUserId = Object.keys(users).find(value => {\n                    const user = users[value];\n                    const { name: username } = user;\n                    // Same issue as getIMChannel(), so we handle both\n                    return `@${username}` === name || username === name;\n                });\n\n                if (!!relatedUserId) {\n                    const relatedUser = users[relatedUserId];\n                    presence = relatedUser.presence;\n                }\n            }\n\n            let label;\n\n            if (unread > 0) {\n                label = `${name} ${unread > 0 ? `(${unread} new)` : \"\"}`;\n            } else if (isMuted) {\n                label = `${name} (muted)`;\n            } else {\n                label = `${name}`;\n            }\n\n            return {\n                channel,\n                unread,\n                label,\n                presence,\n                providerName,\n                teamName\n            };\n        });\n    }\n\n    getUserPresence(userId: string) {\n        const user = this.store.getUser(this.providerName, userId);\n        return !!user ? user.presence : undefined;\n    }\n\n    getCurrentUserPresence = () => {\n        const currentUser = this.store.getCurrentUser(this.providerName);\n        return !!currentUser ? this.getUserPresence(currentUser.id) : undefined;\n    };\n}\n"
  },
  {
    "path": "src/manager/index.ts",
    "content": "import * as vscode from \"vscode\";\nimport { hasVslsSpacesExtension } from \"../utils\";\nimport { DiscordChatProvider } from \"../discord\";\nimport { SlackChatProvider } from \"../slack\";\nimport { ViewsManager } from \"./views\";\nimport { ConfigHelper } from \"../config\";\nimport { ChatProviderManager } from \"./chatManager\";\nimport { SelfCommands } from \"../constants\";\nimport { VslsSpacesProvider } from \"../vslsSpaces\";\n\nexport default class Manager implements IManager, vscode.Disposable {\n    isTokenInitialized: boolean = false;\n    viewsManager: ViewsManager;\n    chatProviders = new Map<Providers, ChatProviderManager>();\n\n    constructor(public store: IStore) {\n        this.viewsManager = new ViewsManager(this);\n    }\n\n    getEnabledProviders(newInitialState?: InitialState): InitialState[] {\n        // if newInitialState is specified, enabled list must include it\n        let currentUserInfos = this.store.getCurrentUserForAll();\n        let providerTeamIds: { [provider: string]: string | undefined } = {};\n\n        currentUserInfos.forEach(currentUser => {\n            const { provider } = currentUser;\n\n            if (provider !== \"vslsSpaces\") {\n                // This provider is dependent on installed extensions, not the user state\n                providerTeamIds[currentUser.provider] = currentUser.currentTeamId;\n            }\n        });\n\n        const hasVslsSpaces = hasVslsSpacesExtension();\n\n        if (hasVslsSpaces) {\n            providerTeamIds[Providers.vslsSpaces] = undefined;\n        }\n\n        if (!!newInitialState) {\n            providerTeamIds[newInitialState.provider] = newInitialState.teamId;\n        }\n\n        if (!!providerTeamIds[Providers.discord]) {\n            providerTeamIds[Providers.discord] = undefined;\n        }\n\n        return Object.keys(providerTeamIds).map(provider => ({\n            provider,\n            teamId: providerTeamIds[provider]\n        }));\n    }\n\n    isProviderEnabled(provider: string): boolean {\n        const cp = this.chatProviders.get(provider as Providers);\n        return !!cp;\n    }\n\n    getCurrentTeamIdFor(provider: string) {\n        const currentUser = this.store.getCurrentUser(provider);\n        return !!currentUser ? currentUser.currentTeamId : undefined;\n    }\n\n    getCurrentUserFor(provider: string) {\n        return this.store.getCurrentUser(provider);\n    }\n\n    getChatProvider(providerName: Providers) {\n        return this.chatProviders.get(providerName);\n    }\n\n    instantiateChatProvider(token: string, provider: string): IChatProvider {\n        switch (provider) {\n            case \"discord\":\n                return new DiscordChatProvider(token, this);\n            case \"slack\":\n                return new SlackChatProvider(token, this);\n            case \"vslsSpaces\":\n                return new VslsSpacesProvider();\n            default:\n                throw new Error(`unsupport chat provider: ${provider}`);\n        }\n    }\n\n    async validateToken(provider: string, token: string) {\n        const chatProvider = this.instantiateChatProvider(token, provider);\n        const currentUser = await chatProvider.validateToken();\n        return currentUser;\n    }\n\n    isAuthenticated(providerName: string | undefined): boolean {\n        const cp = this.chatProviders.get(providerName as Providers);\n        return !!cp ? cp.isAuthenticated() : false;\n    }\n\n    migrateTokenForSlack = async (teamId: string) => {\n        // Migration for 0.10.x\n        const teamToken = await ConfigHelper.getToken(\"slack\", teamId);\n\n        if (!teamToken) {\n            const slackToken = await ConfigHelper.getToken(\"slack\");\n\n            if (!!slackToken) {\n                await ConfigHelper.setToken(slackToken, \"slack\", teamId);\n                await ConfigHelper.clearToken(\"slack\");\n            }\n        }\n    };\n\n    initializeToken = async (newInitialState?: InitialState) => {\n        let enabledProviderStates = this.getEnabledProviders(newInitialState);\n\n        if (Object.keys(enabledProviderStates).length === 0) {\n            // Do this to ensure we load vsls, need to delay for vscode.getExtension\n            // to work properly right after installation (and no restart).\n            const delay = (ms: number) => new Promise(res => setTimeout(res, ms));\n            await delay(5 * 1000);\n            enabledProviderStates = this.getEnabledProviders(newInitialState);\n        }\n\n        for (const initialState of enabledProviderStates) {\n            const { provider: stateProvider, teamId } = initialState;\n            const provider = stateProvider as Providers;\n\n            if (!!provider) {\n                if (provider === Providers.slack && !!teamId) {\n                    this.migrateTokenForSlack(teamId);\n                }\n\n                const token = await ConfigHelper.getToken(provider, teamId);\n\n                if (!!token) {\n                    const existingProvider = this.chatProviders.get(provider);\n\n                    if (!existingProvider || existingProvider.teamId !== teamId) {\n                        const chatProvider = this.instantiateChatProvider(token, provider);\n                        const chatManager = new ChatProviderManager(this.store, provider, teamId, chatProvider, this);\n                        this.chatProviders.set(provider, chatManager);\n                    }\n\n                    this.isTokenInitialized = true;\n                }\n            }\n        }\n\n        this.initializeViewsManager();\n    };\n\n    initializeViewsManager = () => {\n        const enabledProviders = Array.from(this.chatProviders.keys());\n        let providerTeams: { [provider: string]: Team[] } = {};\n\n        enabledProviders.forEach(provider => {\n            const chatProvider = this.chatProviders.get(provider);\n\n            if (!!chatProvider) {\n                providerTeams[provider] = chatProvider.getTeams();\n            }\n        });\n\n        this.viewsManager.initialize(enabledProviders, providerTeams);\n    };\n\n    initializeProviders = async (): Promise<any> => {\n        for (let entry of Array.from(this.chatProviders.entries())) {\n            let chatProvider = entry[1];\n\n            try {\n                await chatProvider.initializeProvider();\n            } catch (err) {\n                // try-catch will save vsls in case vslsSpaces crashes because\n                // it cannot find exports for the vslsSpaces extension.\n                console.log(err);\n            }\n        }\n    };\n\n    async initializeStateForAll() {\n        for (let entry of Array.from(this.chatProviders.entries())) {\n            let chatProvider = entry[1];\n            await chatProvider.initializeState();\n        }\n    }\n\n    subscribePresenceForAll() {\n        for (let entry of Array.from(this.chatProviders.entries())) {\n            let chatProvider = entry[1];\n            chatProvider.subscribeForPresence();\n        }\n    }\n\n    async updateUserPrefsForAll() {\n        for (let entry of Array.from(this.chatProviders.entries())) {\n            let chatProvider = entry[1];\n            await chatProvider.updateUserPrefs();\n        }\n    }\n\n    async signout() {\n        // This will sign out of slack and discord. vsls depends only on whether\n        // the vsls extension has been installed.\n        let hasSignedOut = false;\n\n        for (let entry of Array.from(this.chatProviders.entries())) {\n            let providerName = entry[0];\n            await ConfigHelper.clearToken(providerName);\n            hasSignedOut = true;\n        }\n\n        if (hasSignedOut) {\n            // When token state is cleared, we need to call reset\n            vscode.commands.executeCommand(SelfCommands.RESET_STORE, {\n                newProvider: undefined\n            });\n        }\n    }\n\n    clearAll() {\n        // This method clears local storage for slack/discord, but not vsls\n        const enabledProviders = Array.from(this.chatProviders.keys());\n\n        enabledProviders.forEach(provider => {\n            this.store.clearProviderState(provider);\n            const chatProvider = this.chatProviders.get(provider);\n\n            if (!!chatProvider) {\n                chatProvider.destroy();\n                this.chatProviders.delete(provider);\n            }\n        });\n\n        this.isTokenInitialized = false;\n    }\n\n    async clearOldWorkspace(provider: string) {\n        // Clears users and channels so that we are loading them again\n        await this.store.updateUsers(provider, {});\n        await this.store.updateChannels(provider, []);\n        await this.store.updateLastChannelId(provider, undefined);\n    }\n\n    async updateWebviewForProvider(provider: string, channelId: string, typingUserId?: string) {\n        const currentUser = this.store.getCurrentUser(provider);\n        const channels = this.store.getChannels(provider);\n        const channel = channels.find(channel => channel.id === channelId);\n\n        if (!!currentUser && !!channel) {\n            await this.store.updateLastChannelId(provider, channelId);\n            const users = this.store.getUsers(provider);\n            const allMessages = this.getMessages(provider);\n            const messages = allMessages[channel.id] || {};\n            let typingUser: User | undefined;\n\n            if (typingUserId) {\n                typingUser = users[typingUserId];\n            }\n\n            this.viewsManager.updateWebview(currentUser, provider, users, channel, messages, typingUser);\n        }\n    }\n\n    updateStatusItemsForProvider(provider: string) {\n        const cp = this.chatProviders.get(provider as Providers);\n\n        if (!!cp) {\n            const teams = cp.getTeams();\n            teams.forEach(team => {\n                this.viewsManager.updateStatusItem(provider, team);\n            });\n        }\n    }\n\n    updateTreeViewsForProvider(provider: string) {\n        this.viewsManager.updateTreeViews(provider);\n    }\n\n    updateAllUI() {\n        const providers = Array.from(this.chatProviders.keys());\n\n        providers.forEach(provider => {\n            const lastChannelId = this.store.getLastChannelId(provider);\n\n            if (!!lastChannelId) {\n                this.updateWebviewForProvider(provider, lastChannelId);\n            }\n\n            this.updateStatusItemsForProvider(provider);\n            this.updateTreeViewsForProvider(provider);\n        });\n    }\n\n    dispose() {\n        this.viewsManager.dispose();\n    }\n\n    getChannelLabels(provider: string | undefined): ChannelLabel[] {\n        // Return channel labels from all providers if input provider is undefined\n        let channelLabels: ChannelLabel[] = [];\n\n        for (let entry of Array.from(this.chatProviders.entries())) {\n            const cp = entry[1];\n            const providerName = entry[0];\n\n            if (!provider || provider === providerName) {\n                channelLabels = [...channelLabels, ...cp.getChannelLabels()];\n            }\n        }\n\n        return channelLabels;\n    }\n\n    getUserForId(provider: string, userId: string) {\n        const cachedUser = this.store.getUser(provider, userId);\n        return cachedUser;\n    }\n\n    getIMChannel(provider: string, user: User): Channel | undefined {\n        // DM channels look like `name`\n        const channels = this.store.getChannels(provider);\n        const { name } = user;\n        return channels.find(channel => channel.name === name);\n    }\n\n    async createIMChannel(providerName: string, user: User): Promise<Channel | undefined> {\n        const cp = this.chatProviders.get(providerName as Providers);\n        return !!cp ? await cp.createIMChannel(user) : undefined;\n    }\n\n    getUserPresence(provider: string, userId: string) {\n        const cp = this.chatProviders.get(provider as Providers);\n        return !!cp ? cp.getUserPresence(userId) : undefined;\n    }\n\n    getCurrentUserPresence = (provider: string) => {\n        const cp = this.chatProviders.get(provider as Providers);\n        return !!cp ? cp.getCurrentUserPresence() : undefined;\n    };\n\n    updateCurrentWorkspace = async (provider: string, team: Team): Promise<void> => {\n        const existingUserInfo = this.getCurrentUserFor(provider);\n\n        if (!!existingUserInfo) {\n            const newCurrentUser: CurrentUser = {\n                ...existingUserInfo,\n                currentTeamId: team.id\n            };\n            return this.store.updateCurrentUser(provider, newCurrentUser);\n        }\n    };\n\n    async loadChannelHistory(providerName: string, channelId: string): Promise<void> {\n        const cp = this.chatProviders.get(providerName as Providers);\n        return !!cp ? cp.loadChannelHistory(channelId) : undefined;\n    }\n\n    async updateReadMarker(providerName: string): Promise<void> {\n        const cp = this.chatProviders.get(providerName as Providers);\n        return !!cp ? cp.updateReadMarker() : undefined;\n    }\n\n    sendMessage = async (\n        providerName: string,\n        text: string,\n        channelId: string,\n        parentTimestamp: string | undefined\n    ): Promise<void> => {\n        const cp = this.chatProviders.get(providerName as Providers);\n        return !!cp ? cp.sendMessage(text, channelId, parentTimestamp) : undefined;\n    };\n\n    updateSelfPresence = async (providerName: string, presence: UserPresence, durationInMinutes: number) => {\n        const cp = this.chatProviders.get(providerName as Providers);\n        return !!cp ? cp.updateSelfPresence(presence, durationInMinutes) : undefined;\n    };\n\n    addReaction(providerName: string, channelId: string, msgTimestamp: string, userId: string, reactionName: string) {\n        const cp = this.chatProviders.get(providerName as Providers);\n        return !!cp ? cp.addReaction(channelId, msgTimestamp, userId, reactionName) : undefined;\n    }\n\n    removeReaction(\n        providerName: string,\n        channelId: string,\n        msgTimestamp: string,\n        userId: string,\n        reactionName: string\n    ) {\n        const cp = this.chatProviders.get(providerName as Providers);\n        return !!cp ? cp.removeReaction(channelId, msgTimestamp, userId, reactionName) : undefined;\n    }\n\n    async fetchThreadReplies(providerName: string, parentTimestamp: string) {\n        const cp = this.chatProviders.get(providerName as Providers);\n        return !!cp ? cp.fetchThreadReplies(parentTimestamp) : undefined;\n    }\n\n    updateMessageReply(providerName: string, parentTimestamp: string, channelId: string, reply: MessageReply) {\n        const cp = this.chatProviders.get(providerName as Providers);\n        return !!cp ? cp.updateMessageReply(parentTimestamp, channelId, reply) : undefined;\n    }\n\n    updateMessages(providerName: string, channelId: string, messages: ChannelMessagesWithUndefined) {\n        const cp = this.chatProviders.get(providerName as Providers);\n        return !!cp ? cp.updateMessages(channelId, messages) : undefined;\n    }\n\n    clearMessages(providerName: string, channelId: string) {\n        const cp = this.chatProviders.get(providerName as Providers);\n        return !!cp ? cp.clearMessages(channelId) : undefined;\n    }\n\n    updateChannelMarked(provider: string, channelId: string, readTimestamp: string, unreadCount: number) {\n        const cp = this.chatProviders.get(provider as Providers);\n        return !!cp ? cp.updateChannelMarked(channelId, readTimestamp, unreadCount) : undefined;\n    }\n\n    updatePresenceForUser = (providerName: string, userId: string, presence: UserPresence) => {\n        const cp = this.chatProviders.get(providerName as Providers);\n        return !!cp ? cp.updatePresenceForUser(userId, presence) : undefined;\n    };\n\n    getChannel = (provider: string, channelId: string | undefined): Channel | undefined => {\n        const cp = this.chatProviders.get(provider as Providers);\n        return !!cp ? cp.getChannel(channelId) : undefined;\n    };\n\n    fetchUsers = (providerName: string) => {\n        const cp = this.chatProviders.get(providerName as Providers);\n        return !!cp ? cp.fetchUsers() : undefined;\n    };\n\n    fetchChannels = (providerName: string) => {\n        const cp = this.chatProviders.get(providerName as Providers);\n        return !!cp ? cp.fetchChannels() : undefined;\n    };\n\n    getMessages = (providerName: string): Messages => {\n        const cp = this.chatProviders.get(providerName as Providers);\n        return !!cp ? cp.messages : {};\n    };\n\n    getUnreadCount = (provider: string, channel: Channel) => {\n        const cp = this.chatProviders.get(provider as Providers);\n        return !!cp ? cp.getUnreadCount(channel) : 0;\n    };\n}\n"
  },
  {
    "path": "src/manager/treeView.ts",
    "content": "import * as vscode from \"vscode\";\nimport {\n  WorkspacesTreeProvider,\n  UnreadsTreeProvider,\n  ChannelTreeProvider,\n  GroupTreeProvider,\n  IMsTreeProvider\n} from \"../tree\";\n\nexport class TreeViewManager implements vscode.Disposable {\n  workspacesTreeProvider: WorkspacesTreeProvider;\n  unreadsTreeProvider: UnreadsTreeProvider;\n  channelsTreeProvider: ChannelTreeProvider;\n  imsTreeProvider: IMsTreeProvider;\n  groupsTreeProvider: GroupTreeProvider;\n\n  constructor(public provider: string) {\n    this.workspacesTreeProvider = new WorkspacesTreeProvider(provider);\n    this.unreadsTreeProvider = new UnreadsTreeProvider(provider);\n    this.channelsTreeProvider = new ChannelTreeProvider(provider);\n    this.groupsTreeProvider = new GroupTreeProvider(provider);\n    this.imsTreeProvider = new IMsTreeProvider(provider);\n  }\n\n  updateData(currentUserInfo: CurrentUser, channelLabels: ChannelLabel[]) {\n    this.workspacesTreeProvider.updateCurrentUser(currentUserInfo);\n    this.unreadsTreeProvider.updateChannels(channelLabels);\n    this.channelsTreeProvider.updateChannels(channelLabels);\n    this.groupsTreeProvider.updateChannels(channelLabels);\n    this.imsTreeProvider.updateChannels(channelLabels);\n  }\n\n  dispose() {\n    this.workspacesTreeProvider.dispose();\n    this.unreadsTreeProvider.dispose();\n    this.channelsTreeProvider.dispose();\n    this.groupsTreeProvider.dispose();\n    this.imsTreeProvider.dispose();\n  }\n}\n"
  },
  {
    "path": "src/manager/views.ts",
    "content": "import * as vscode from \"vscode\";\nimport { TreeViewManager } from \"./treeView\";\nimport { BaseStatusItem, UnreadsStatusItem } from \"../status\";\nimport { OnboardingTreeProvider } from \"../onboarding\";\nimport { SelfCommands } from \"../constants\";\nimport { setVsContext, difference } from \"../utils\";\n\nconst PROVIDERS_WITH_TREE = [\"slack\", \"discord\"];\n\nconst getStatusItemKey = (provider: string, team: Team) => {\n    return `${provider}:${team.id}`;\n};\n\nexport class ViewsManager implements vscode.Disposable {\n    statusItems: Map<string, BaseStatusItem> = new Map();\n    treeViews: Map<string, TreeViewManager> = new Map();\n    onboardingTree: OnboardingTreeProvider | undefined;\n\n    constructor(private parentManager: IManager) {}\n\n    initialize(enabledProviders: string[], providerTeams: { [providerName: string]: Team[] }) {\n        const statusItemKeys = new Map<string, { provider: string; team: Team }>();\n        enabledProviders.forEach(provider => {\n            const teams = providerTeams[provider];\n            teams.forEach(team => {\n                statusItemKeys.set(getStatusItemKey(provider, team), {\n                    provider,\n                    team\n                });\n            });\n        });\n        this.initializeStatusItems(statusItemKeys);\n        this.initializeTreeViews(enabledProviders);\n\n        const showOnboarding = false;\n        // Overriding showOnboarding to be always false, so that vsls extension\n        // pack users don't see a slack icon in the activity bar.\n        // const showOnboarding = nonVslsProviders.length === 0;\n\n        if (showOnboarding && !this.onboardingTree) {\n            // We need to initialize the tree here\n            this.onboardingTree = new OnboardingTreeProvider();\n        } else if (!showOnboarding && !!this.onboardingTree) {\n            // Dispose the tree as we don't need it anymore\n            this.onboardingTree.dispose();\n            this.onboardingTree = undefined;\n        }\n    }\n\n    initializeStatusItems(newKeyMap: Map<string, { provider: string; team: Team }>) {\n        // Ensure new keys have status items in the map and\n        // no longer used keys are removed.\n        const existingKeysSet = new Set(Array.from(this.statusItems.keys()));\n        const newKeysSet = new Set(Array.from(newKeyMap.keys()));\n        const keysToRemove = difference(existingKeysSet, newKeysSet);\n        const keysToAdd = difference(newKeysSet, existingKeysSet);\n\n        keysToRemove.forEach(key => {\n            const statusItem = this.statusItems.get(key);\n\n            if (!!statusItem) {\n                statusItem.dispose();\n                this.statusItems.delete(key);\n            }\n        });\n\n        keysToAdd.forEach(key => {\n            const providerAndTeam = newKeyMap.get(key);\n\n            if (!!providerAndTeam) {\n                const { provider, team } = providerAndTeam;\n                this.statusItems.set(key, new UnreadsStatusItem(provider, team));\n            }\n        });\n    }\n\n    initializeTreeViews(enabledProviders: string[]) {\n        PROVIDERS_WITH_TREE.forEach(provider => {\n            const hasProviderEnabled = enabledProviders.indexOf(provider) >= 0;\n            setVsContext(`chat:${provider}`, hasProviderEnabled);\n        });\n\n        const enabledTreeProviders = new Set(enabledProviders.filter(p => PROVIDERS_WITH_TREE.indexOf(p) >= 0));\n        const existingTreeProviders = new Set(Array.from(this.treeViews.keys()));\n        const treesToAdd = difference(enabledTreeProviders, existingTreeProviders);\n        const treesToRemove = difference(existingTreeProviders, enabledTreeProviders);\n\n        treesToRemove.forEach(treeProvider => {\n            const treeView = this.treeViews.get(treeProvider);\n            if (!!treeView) {\n                treeView.dispose();\n                this.treeViews.delete(treeProvider);\n            }\n        });\n\n        treesToAdd.forEach(treeProvider => {\n            this.treeViews.set(treeProvider, new TreeViewManager(treeProvider));\n        });\n    }\n\n    updateStatusItem(provider: string, team: Team) {\n        const statusItem = this.statusItems.get(getStatusItemKey(provider, team));\n\n        if (statusItem) {\n            const channels = this.parentManager.store.getChannels(provider);\n            const unreads = channels.map(channel => {\n                return this.parentManager.getUnreadCount(provider, channel);\n            });\n            const totalUnreads = unreads.reduce((a, b) => a + b, 0);\n            statusItem.updateCount(totalUnreads);\n        }\n    }\n\n    updateTreeViews(provider: string) {\n        const treeViewForProvider = this.treeViews.get(provider);\n\n        if (!!treeViewForProvider && this.parentManager.isAuthenticated(provider)) {\n            const channelLabels = this.parentManager.getChannelLabels(provider);\n            const currentUserInfo = this.parentManager.getCurrentUserFor(provider);\n\n            if (!!currentUserInfo) {\n                treeViewForProvider.updateData(currentUserInfo, channelLabels);\n            }\n        }\n    }\n\n    updateWebview(\n        currentUser: CurrentUser,\n        provider: string,\n        users: Users,\n        channel: Channel,\n        messages: ChannelMessages,\n        typingUser?: User\n    ) {\n        const { fontFamily, fontSize } = vscode.workspace.getConfiguration(\"editor\");\n        let statusText = ``;\n\n        if (typingUser) {\n            statusText = `${typingUser.name} is typing...`\n        }\n\n        let uiMessage: UIMessage = {\n            fontFamily,\n            fontSize,\n            provider,\n            messages,\n            users,\n            currentUser,\n            channel,\n            statusText\n            // atMentions: Object.values(users)\n        };\n\n        vscode.commands.executeCommand(SelfCommands.SEND_TO_WEBVIEW, {\n            uiMessage\n        });\n    }\n\n    dispose() {\n        for (let entry of Array.from(this.statusItems.entries())) {\n            let statusItem = entry[1];\n            statusItem.dispose();\n        }\n\n        for (let entry of Array.from(this.treeViews.entries())) {\n            let treeView = entry[1];\n            treeView.dispose();\n        }\n\n        if (!!this.onboardingTree) {\n            this.onboardingTree.dispose();\n        }\n    }\n}\n"
  },
  {
    "path": "src/onboarding.ts",
    "content": "import * as vscode from \"vscode\";\nimport * as str from \"./strings\";\nimport { SelfCommands } from \"./constants\";\nimport { openUrl } from \"./utils\";\n\nexport const setupSlack = () => {\n  vscode.commands.executeCommand(SelfCommands.SIGN_IN, {\n    source: EventSource.info,\n    service: \"slack\"\n  });\n};\n\nexport const setupDiscord = () => {\n  openUrl(\n    \"https://github.com/karigari/vscode-chat/blob/master/docs/DISCORD.md\"\n  );\n};\n\nexport const askForAuth = async () => {\n  const actionItems = [str.SETUP_SLACK, str.SETUP_DISCORD];\n  const selected = await vscode.window.showInformationMessage(\n    str.TOKEN_NOT_FOUND,\n    ...actionItems\n  );\n\n  switch (selected) {\n    case str.SETUP_SLACK:\n      setupSlack();\n      break;\n    case str.SETUP_DISCORD:\n      setupDiscord();\n      break;\n  }\n};\n\nclass CustomOnboardingTreeItem extends vscode.TreeItem {\n  constructor(label: string, command: string) {\n    super(label);\n    this.command = {\n      command,\n      title: \"\",\n      arguments: [{ source: EventSource.activity }]\n    };\n  }\n}\n\ninterface OnboardingTreeNode {\n  label: string;\n  command: string;\n}\n\nconst OnboardingCommands = {\n  SETUP_SLACK: \"extension.chat.onboarding.slack\",\n  SETUP_DISCORD: \"extension.chat.onboarding.discord\"\n};\n\nexport class OnboardingTreeProvider\n  implements vscode.TreeDataProvider<OnboardingTreeNode>, vscode.Disposable {\n  // private vslsViewId = \"chat.treeView.onboarding.vsls\";\n  private mainViewId = \"chat.treeView.onboarding.main\";\n  private _disposables: vscode.Disposable[] = [];\n\n  constructor() {\n    this._disposables.push(\n      // vscode.window.registerTreeDataProvider(this.vslsViewId, this),\n      vscode.window.registerTreeDataProvider(this.mainViewId, this),\n      vscode.commands.registerCommand(\n        OnboardingCommands.SETUP_SLACK,\n        setupSlack\n      ),\n      vscode.commands.registerCommand(\n        OnboardingCommands.SETUP_DISCORD,\n        setupDiscord\n      )\n    );\n  }\n\n  dispose() {\n    this._disposables.forEach(dispose => dispose.dispose());\n  }\n\n  getChildren(element?: OnboardingTreeNode) {\n    return Promise.resolve([\n      { label: str.SETUP_SLACK, command: OnboardingCommands.SETUP_SLACK },\n      { label: str.SETUP_DISCORD, command: OnboardingCommands.SETUP_DISCORD }\n    ]);\n  }\n\n  getTreeItem(element: OnboardingTreeNode): vscode.TreeItem {\n    const { label, command } = element;\n    return new CustomOnboardingTreeItem(label, command);\n  }\n}\n"
  },
  {
    "path": "src/slack/client.ts",
    "content": "import { WebClient, WebClientOptions } from \"@slack/client\";\nimport { ConfigHelper } from \"../config\";\nimport Logger from \"../logger\";\nimport { IDNDStatusForUser } from \"./common\";\n\ninterface ISnoozeAPIResponse {\n  ok: boolean;\n  snooze_enabled: boolean;\n  snooze_endtime: number;\n  snooze_remaining: number;\n}\n\nconst CHANNEL_HISTORY_LIMIT = 50;\n\nconst USER_LIST_LIMIT = 1000;\n\n// User-defined type guard\n// https://github.com/Microsoft/TypeScript/issues/20707#issuecomment-351874491\nfunction notUndefined<T>(x: T | undefined): x is T {\n  return x !== undefined;\n}\n\nconst getFile = (rawFile: any) => {\n  return { name: rawFile.name, permalink: rawFile.permalink };\n};\n\nconst getContent = (attachment: any) => {\n  return {\n    author: attachment.author_name,\n    authorIcon: attachment.author_icon,\n    pretext: attachment.pretext,\n    title: attachment.title,\n    titleLink: attachment.title_link,\n    text: attachment.text,\n    footer: attachment.footer,\n    borderColor: attachment.color\n  };\n};\n\nconst getReaction = (reaction: any) => ({\n  name: `:${reaction.name}:`,\n  count: reaction.count,\n  userIds: reaction.users\n});\n\nconst getUser = (member: any): User => {\n  const { id, profile, real_name, name, deleted } = member;\n  const { display_name, image_72, image_24 } = profile;\n\n  return {\n    id,\n    // Conditional required for bots like @paperbot\n    name: display_name ? display_name : name,\n    email: profile.email,\n    fullName: real_name,\n    internalName: name,\n    imageUrl: image_72,\n    smallImageUrl: image_24,\n    presence: UserPresence.unknown,\n    isDeleted: deleted\n  };\n};\n\nexport const getMessage = (raw: any): ChannelMessages => {\n  const { files, ts, user, text, edited, bot_id } = raw;\n  const { attachments, reactions, replies } = raw;\n  let parsed: ChannelMessages = {};\n\n  parsed[ts] = {\n    userId: user ? user : bot_id,\n    timestamp: ts,\n    isEdited: !!edited,\n    text: text,\n    attachment: files ? getFile(files[0]) : undefined,\n    reactions: reactions\n      ? reactions.map((reaction: any) => getReaction(reaction))\n      : [],\n    content: attachments ? getContent(attachments[0]) : undefined,\n    replies: replies\n      ? replies.map((reply: any) => ({\n          userId: reply.user,\n          timestamp: reply.ts\n        }))\n      : []\n  };\n\n  return parsed;\n};\n\nexport default class SlackAPIClient {\n  client: WebClient;\n\n  constructor(private token: string) {\n    let options: WebClientOptions = { retryConfig: { retries: 1 } };\n    const customAgent = ConfigHelper.getCustomAgent();\n\n    if (!!customAgent) {\n      options.agent = customAgent;\n    }\n\n    this.client = new WebClient(token, options);\n\n    this.client.on(\"rate_limited\", retryAfter => {\n      Logger.log(`Slack client rate limited: paused for ${retryAfter} seconds`);\n    });\n  }\n\n  authTest = async (): Promise<CurrentUser | undefined> => {\n    const response: any = await this.client.auth.test();\n    const { ok } = response;\n\n    if (ok) {\n      const { team, user, user_id, team_id } = response;\n      return {\n        id: user_id,\n        name: user,\n        teams: [{ id: team_id, name: team }],\n        currentTeamId: team_id,\n        provider: Providers.slack\n      };\n    }\n  };\n\n  getConversationHistory = async (\n    channel: string\n  ): Promise<ChannelMessages> => {\n    const response: any = await this.client.apiCall(\"conversations.history\", {\n      channel,\n      limit: CHANNEL_HISTORY_LIMIT\n    });\n    const { messages, ok } = response;\n    let result = {};\n\n    if (ok) {\n      messages.forEach((rawMessage: any) => {\n        result = {\n          ...result,\n          ...getMessage(rawMessage)\n        };\n      });\n    }\n\n    return result;\n  };\n\n  async getUsers(): Promise<Users> {\n    const response: any = await this.client.apiCall(\"users.list\", {\n      limit: USER_LIST_LIMIT\n    });\n    const { members, ok } = response;\n    let users: Users = {};\n\n    if (ok) {\n      members.forEach((member: any) => {\n        const user = getUser(member);\n        const { id } = user;\n        users[id] = user;\n      });\n\n      return users;\n    }\n\n    return {};\n  }\n\n  async getBotInfo(botId: string): Promise<User | undefined> {\n    const response: any = await this.client.bots.info({\n      bot: botId\n    });\n    const { bot, ok } = response;\n\n    if (ok) {\n      const { id, name, icons } = bot;\n      return {\n        id,\n        name,\n        fullName: name,\n        imageUrl: icons.image_72,\n        smallImageUrl: icons.image_24,\n        presence: UserPresence.unknown,\n        isBot: true\n      };\n    }\n  }\n\n  async getUserInfo(userId: string): Promise<User | undefined> {\n    const response: any = await this.client.users.info({ user: userId });\n    const { ok, user } = response;\n\n    if (ok) {\n      return getUser(user);\n    }\n  }\n\n  async getChannels(users: Users): Promise<Channel[]> {\n    const response: any = await this.client.conversations.list({\n      exclude_archived: true,\n      types: \"public_channel, private_channel, mpim, im\"\n    });\n    const { ok, channels } = response;\n    const userValues = Object.keys(users).map(key => users[key]);\n\n    if (ok) {\n      return channels\n        .map((channel: any) => {\n          const { is_channel, is_mpim, is_im, is_group, is_member } = channel;\n\n          if (is_channel && is_member) {\n            // Public channels\n            return {\n              id: channel.id,\n              name: channel.name,\n              type: ChannelType.channel\n            };\n          }\n\n          if (is_group && !is_mpim) {\n            // Private channels\n            return {\n              id: channel.id,\n              name: channel.name,\n              type: ChannelType.channel\n            };\n          }\n\n          if (is_group && is_mpim) {\n            // Groups (multi-party direct messages)\n            // Example name: mpdm-user.name--username2--user3-1\n            let { id, name } = channel;\n            const matched = name.match(/mpdm-([^-]+)((--[^-]+)*)-\\d+/);\n\n            if (matched) {\n              const first = matched[1];\n              const rest = matched[2]\n                .split(\"--\")\n                .filter((element: string) => !!element);\n              const members = [first, ...rest];\n              const memberUsers = members\n                .map(memberName =>\n                  userValues.find(\n                    ({ internalName }) => internalName === memberName\n                  )\n                )\n                .filter(notUndefined);\n              const isAnyUserDeleted = memberUsers.filter(\n                ({ isDeleted }) => isDeleted\n              );\n\n              if (isAnyUserDeleted.length > 0) {\n                return null;\n              } else {\n                name = memberUsers.map(({ name }) => name).join(\", \");\n                return {\n                  id: id,\n                  name: name,\n                  type: ChannelType.group\n                };\n              }\n            }\n          }\n\n          if (is_im) {\n            // Direct messages\n            const { id, user: userId } = channel;\n\n            if (userId in users) {\n              const user = users[userId];\n\n              if (!user.isDeleted) {\n                const name = user.name;\n                return {\n                  id,\n                  name,\n                  type: ChannelType.im\n                };\n              }\n            }\n          }\n        })\n        .filter(Boolean);\n    }\n\n    return [];\n  }\n\n  getChannelInfo = async (\n    originalChannel: Channel\n  ): Promise<Channel | undefined> => {\n    const { id, type } = originalChannel;\n    let response: any;\n    let channel;\n\n    try {\n      switch (type) {\n        case \"group\":\n          response = await this.client.groups.info({ channel: id });\n          channel = response.group;\n          break;\n        case \"channel\":\n          response = await this.client.channels.info({ channel: id });\n          channel = response.channel;\n          break;\n        case \"im\":\n          response = await this.client.conversations.info({\n            channel: id\n          });\n          channel = response.channel;\n          break;\n      }\n\n      const { unread_count_display, last_read } = channel;\n      return {\n        ...originalChannel,\n        unreadCount: unread_count_display,\n        readTimestamp: last_read\n      };\n    } catch (error) {\n      // TODO: this is failing for private groups -> need to investigate why\n      console.log(\"Error fetching channel:\", originalChannel.name);\n    }\n  };\n\n  sendMessage = (\n    channelId: string,\n    text: string,\n    threadTs: string\n  ): Promise<any> => {\n    return this.client.chat.postMessage({\n      channel: channelId,\n      text,\n      thread_ts: threadTs,\n      as_user: true\n    });\n  };\n\n  markChannel = async (\n    channel: Channel,\n    ts: string\n  ): Promise<Channel | undefined> => {\n    const { id, type } = channel;\n    let response: any;\n\n    switch (type) {\n      case ChannelType.channel:\n        response = await this.client.channels.mark({ channel: id, ts });\n        break;\n      case ChannelType.group:\n        response = await this.client.groups.mark({ channel: id, ts });\n        break;\n      case ChannelType.im:\n        response = await this.client.im.mark({ channel: id, ts });\n        break;\n    }\n\n    const { ok } = response;\n\n    if (ok) {\n      return {\n        ...channel,\n        readTimestamp: ts,\n        unreadCount: 0\n      };\n    }\n  };\n\n  openIMChannel = async (user: User): Promise<Channel | undefined> => {\n    const { id, name } = user;\n    let response: any = await this.client.im.open({\n      user: id,\n      return_im: true\n    });\n    const { ok, channel } = response;\n\n    if (ok) {\n      return {\n        id: channel.id,\n        name: `@${name}`,\n        type: ChannelType.im,\n        unreadCount: 0,\n        readTimestamp: undefined\n      };\n    }\n  };\n\n  getUserPrefs = async (): Promise<UserPreferences | undefined> => {\n    // Undocumented API: https://github.com/ErikKalkoken/slackApiDoc/blob/master/users.prefs.get.md\n    let response: any = await this.client.apiCall(\"users.prefs.get\");\n    const { ok, prefs } = response;\n\n    if (ok) {\n      const { muted_channels } = prefs;\n      return {\n        mutedChannels: muted_channels.split(\",\")\n      };\n    }\n  };\n\n  getReplies = async (\n    channelId: string,\n    messageTimestamp: string\n  ): Promise<Message | undefined> => {\n    // https://api.slack.com/methods/conversations.replies\n    let response: any = await this.client.conversations.replies({\n      channel: channelId,\n      ts: messageTimestamp\n    });\n    // Does not handle has_more in the response yet, could break\n    // for large threads\n    const { ok, messages } = response;\n\n    if (ok) {\n      const parent = messages.find((msg: any) => msg.thread_ts === msg.ts);\n      const replies = messages.filter((msg: any) => msg.thread_ts !== msg.ts);\n      const parentMessage = getMessage(parent);\n\n      return {\n        ...parentMessage[messageTimestamp],\n        replies: replies.map((reply: any) => ({\n          userId: reply.user,\n          timestamp: reply.ts,\n          text: reply.text,\n          attachment: !!reply.files ? getFile(reply.files[0]) : null\n        }))\n      };\n    }\n  };\n\n  setUserPresence = async (presence: \"auto\" | \"away\"): Promise<boolean> => {\n    const response = await this.client.users.setPresence({ presence });\n    return response.ok;\n  };\n\n  setUserSnooze = async (durationInMinutes: number): Promise<boolean> => {\n    const response = (await this.client.dnd.setSnooze({\n      num_minutes: durationInMinutes\n    })) as ISnoozeAPIResponse;\n    return response.ok && response.snooze_enabled;\n  };\n\n  endUserSnooze = async (): Promise<boolean> => {\n    const response = await this.client.dnd.endSnooze();\n    return response.ok;\n  };\n\n  endUserDnd = async (): Promise<boolean> => {\n    const response = await this.client.dnd.endDnd();\n    return response.ok;\n  };\n\n  getDndTeamInfo = async (): Promise<IDNDStatusForUser> => {\n    const response: any = await this.client.dnd.teamInfo();\n    const users: IDNDStatusForUser = response.users;\n    let result: IDNDStatusForUser = {};\n\n    const userIds = Object.keys(users);\n    userIds.forEach(userId => {\n      const { dnd_enabled } = users[userId];\n      if (!!dnd_enabled) {\n        result[userId] = users[userId];\n      }\n    });\n\n    return result;\n  };\n}\n"
  },
  {
    "path": "src/slack/common.ts",
    "content": "export interface IDNDStatus {\n  dnd_enabled: boolean;\n  next_dnd_start_ts: number;\n  next_dnd_end_ts: number;\n\n  // The following fields are only available for the\n  // DND_UPDATED_SELF event.\n  snooze_enabled?: boolean;\n  snooze_endtime?: number;\n  snooze_remaining?: number;\n}\n\nexport interface IDNDStatusForUser {\n  [userId: string]: IDNDStatus;\n}\n"
  },
  {
    "path": "src/slack/index.ts",
    "content": "import * as vscode from \"vscode\";\nimport { SelfCommands } from \"../constants\";\nimport SlackAPIClient from \"./client\";\nimport SlackMessenger from \"./messenger\";\nimport { IDNDStatusForUser, IDNDStatus } from \"./common\";\n\nconst stripLinkSymbols = (text: string): string => {\n  // To send out live share links and render them correctly,\n  // we append </> to the link text. However, this is not\n  // handled by normal Slack clients, and should be removed before\n  // we actually send the message via the RTM API\n\n  // This is hacky, and we will need a better solution - perhaps\n  // we could make all rendering manipulations on the extension side\n  // before sending the message to Vuejs for rendering\n  if (text.startsWith(\"<\") && text.endsWith(\">\")) {\n    return text.substr(1, text.length - 2);\n  } else {\n    return text;\n  }\n};\n\nexport class SlackChatProvider implements IChatProvider {\n  private client: SlackAPIClient;\n  private messenger: SlackMessenger;\n  private teamDndState: IDNDStatusForUser = {};\n  private dndTimers: NodeJS.Timer[] = [];\n\n  constructor(private token: string, private manager: IManager) {\n    this.client = new SlackAPIClient(this.token);\n    this.messenger = new SlackMessenger(\n      this.token,\n      (userId: string, presence: \"active\" | \"away\") =>\n        this.onPresenceChanged(userId, presence),\n      (userId: string, dndState: IDNDStatus) =>\n        this.onDndStateChanged(userId, dndState)\n    );\n  }\n\n  public validateToken(): Promise<CurrentUser | undefined> {\n    // This is creating a new client, since getToken from keychain\n    // is not called before validation\n    return this.client.authTest();\n  }\n\n  public connect(): Promise<CurrentUser> {\n    return this.messenger.start();\n  }\n\n  public isConnected(): boolean {\n    return !!this.messenger && this.messenger.isConnected();\n  }\n\n  public subscribePresence(users: Users) {\n    return this.messenger.subscribePresence(users);\n  }\n\n  public createIMChannel(user: User): Promise<Channel | undefined> {\n    return this.client.openIMChannel(user);\n  }\n\n  public fetchUsers(): Promise<Users> {\n    // async update for dnd statuses\n    this.client.getDndTeamInfo().then(response => {\n      this.teamDndState = response;\n      this.updateDndTimers();\n    });\n\n    return this.client.getUsers();\n  }\n\n  public fetchChannels(users: Users): Promise<Channel[]> {\n    // users argument is required to associate IM channels\n    // with users\n    return this.client.getChannels(users);\n  }\n\n  private onPresenceChanged(userId: string, rawPresence: \"active\" | \"away\") {\n    // This method is called from the websocket client\n    // Here, we parse the incoming raw presence (active / away), and use our\n    // known dnd related information, to find the final answer for this user\n    let presence: UserPresence = UserPresence.unknown;\n\n    switch (rawPresence) {\n      case \"active\":\n        presence = UserPresence.available;\n        break;\n      case \"away\":\n        presence = UserPresence.offline;\n        break;\n    }\n\n    if (presence === UserPresence.available) {\n      // Check user has dnd active right now\n      const userDnd = this.teamDndState[userId];\n\n      if (!!userDnd) {\n        const current = +new Date() / 1000.0;\n\n        if (\n          current > userDnd.next_dnd_start_ts &&\n          current < userDnd.next_dnd_end_ts\n        ) {\n          presence = UserPresence.doNotDisturb;\n        }\n      }\n    }\n\n    this.updateUserPresence(userId, presence);\n  }\n\n  private updateUserPresence(userId: string, presence: UserPresence) {\n    vscode.commands.executeCommand(SelfCommands.UPDATE_PRESENCE_STATUSES, {\n      userId,\n      presence,\n      provider: \"slack\"\n    });\n  }\n\n  private onDndStateChanged(userId: string, dndState: IDNDStatus) {\n    this.teamDndState[userId] = dndState;\n    this.updateDndTimerForUser(userId);\n  }\n\n  private updateDndTimers() {\n    const userIds = Object.keys(this.teamDndState);\n    userIds.forEach(userId => {\n      this.updateDndTimerForUser(userId);\n    });\n  }\n\n  private updateDndTimerForUser(userId: string) {\n    const dndState = this.teamDndState[userId];\n    const currentTime = +new Date() / 1000.0;\n    const { next_dnd_end_ts: dndEnd, next_dnd_start_ts: dndStart } = dndState;\n\n    if (currentTime < dndStart) {\n      // Impending start event, so we will define a start timer\n      const delay = (dndStart - currentTime) * 1000;\n      const timer = setTimeout(() => {\n        // If user is available, change to dnd\n        const presence = this.manager.getUserPresence(\"slack\", userId);\n\n        if (presence === UserPresence.available) {\n          this.updateUserPresence(userId, UserPresence.doNotDisturb);\n        }\n      }, delay);\n\n      this.dndTimers.push(timer);\n    }\n\n    if (currentTime < dndEnd) {\n      // Impending end event, so define a start timer\n      const delay = (dndEnd - currentTime) * 1000;\n      const timer = setTimeout(() => {\n        // If user is dnd, change to available\n        const presence = this.manager.getUserPresence(\"slack\", userId);\n\n        if (presence === UserPresence.doNotDisturb) {\n          this.updateUserPresence(userId, UserPresence.available);\n        }\n      }, delay);\n\n      this.dndTimers.push(timer);\n    }\n  }\n\n  public fetchUserInfo(userId: string): Promise<User | undefined> {\n    if (userId.startsWith(\"B\")) {\n      return this.client.getBotInfo(userId);\n    } else {\n      return this.client.getUserInfo(userId);\n    }\n  }\n\n  public loadChannelHistory(channelId: string): Promise<ChannelMessages> {\n    return this.client.getConversationHistory(channelId);\n  }\n\n  public getUserPreferences(): Promise<UserPreferences | undefined> {\n    return this.client.getUserPrefs();\n  }\n\n  public markChannel(\n    channel: Channel,\n    timestamp: string\n  ): Promise<Channel | undefined> {\n    return this.client.markChannel(channel, timestamp);\n  }\n\n  public fetchThreadReplies(\n    channelId: string,\n    timestamp: string\n  ): Promise<Message | undefined> {\n    return this.client.getReplies(channelId, timestamp);\n  }\n\n  public fetchChannelInfo(channel: Channel): Promise<Channel | undefined> {\n    return this.client.getChannelInfo(channel);\n  }\n\n  public sendThreadReply(\n    text: string,\n    currentUserId: string,\n    channelId: string,\n    parentTimestamp: string\n  ) {\n    const cleanText = stripLinkSymbols(text);\n    return this.client.sendMessage(channelId, cleanText, parentTimestamp);\n  }\n\n  public async sendMessage(\n    text: string,\n    currentUserId: string,\n    channelId: string\n  ) {\n    const cleanText = stripLinkSymbols(text);\n\n    try {\n      const result = await this.messenger.sendMessage(channelId, cleanText);\n\n      // TODO: this is not the correct timestamp to attach, since the\n      // API might get delayed, because of network issues\n      let newMessages: ChannelMessages = {};\n      newMessages[result.ts] = {\n        userId: currentUserId,\n        timestamp: result.ts,\n        text,\n        content: undefined,\n        reactions: [],\n        replies: {}\n      };\n\n      vscode.commands.executeCommand(SelfCommands.UPDATE_MESSAGES, {\n        channelId,\n        messages: newMessages,\n        provider: \"slack\"\n      });\n    } catch (error) {\n      return console.error(error);\n    }\n  }\n\n  public async updateSelfPresence(\n    presence: UserPresence,\n    durationInMinutes: number\n  ): Promise<UserPresence | undefined> {\n    let response;\n    const currentPresence = this.manager.getCurrentUserPresence(\"slack\");\n\n    switch (presence) {\n      case UserPresence.doNotDisturb:\n        response = await this.client.setUserSnooze(durationInMinutes);\n        break;\n      case UserPresence.available:\n        if (currentPresence === UserPresence.doNotDisturb) {\n          // client.endUserDnd() can handle both situations -- when user is on\n          // snooze, and when user is on a scheduled dnd\n          response = await this.client.endUserDnd();\n        } else {\n          response = await this.client.setUserPresence(\"auto\");\n        }\n\n        break;\n      case UserPresence.invisible:\n        response = await this.client.setUserPresence(\"away\");\n        break;\n      default:\n        throw new Error(`unsupported presence type`);\n    }\n\n    return !!response ? presence : undefined;\n  }\n\n  public destroy(): Promise<void> {\n    if (!!this.messenger) {\n      this.messenger.disconnect();\n    }\n\n    this.dndTimers.forEach(timer => {\n      clearTimeout(timer);\n    });\n\n    return Promise.resolve();\n  }\n\n  async sendTyping(currentUserId: string, channelId: string) { }\n}\n"
  },
  {
    "path": "src/slack/messenger.ts",
    "content": "import * as vscode from \"vscode\";\nimport { RTMClient, RTMClientOptions } from \"@slack/client\";\nimport { ConfigHelper } from \"../config\";\nimport { getMessage } from \"./client\";\nimport { SelfCommands } from \"../constants\";\nimport { IDNDStatus } from \"./common\";\n\nconst RTMEvents = {\n  AUTHENTICATED: \"authenticated\",\n  MESSAGE: \"message\",\n  ERROR: \"unable_to_rtm_start\",\n  REACTION_ADDED: \"reaction_added\",\n  REACTION_REMOVED: \"reaction_removed\",\n  PRESENCE_CHANGE: \"presence_change\",\n  CHANNEL_MARKED: \"channel_marked\",\n  GROUP_MARKED: \"group_marked\",\n  IM_MARKED: \"im_marked\",\n  DND_UPDATED_SELF: \"dnd_updated\",\n  DND_UPDATED_USER: \"dnd_updated_user\"\n};\n\nconst EventSubTypes = {\n  EDITED: \"message_changed\",\n  DELETED: \"message_deleted\",\n  REPLIED: \"message_replied\"\n};\n\nclass SlackMessenger {\n  rtmClient: RTMClient;\n\n  constructor(\n    token: string,\n    private onPresenceChanged: any,\n    private onDndStateChanged: any\n  ) {\n    // We can also use { useRtmConnect: false } for rtm.start\n    // instead of rtm.connect, which has more fields in the payload\n    let options: RTMClientOptions = {};\n    const customAgent = ConfigHelper.getCustomAgent();\n\n    if (!!customAgent) {\n      options.agent = customAgent;\n    }\n\n    this.rtmClient = new RTMClient(token, options);\n    this.rtmClient.on(RTMEvents.MESSAGE, event => {\n      const { subtype } = event;\n      let newMessages: ChannelMessagesWithUndefined = {};\n\n      switch (subtype) {\n        case EventSubTypes.DELETED:\n          const { deleted_ts } = event;\n          newMessages[deleted_ts] = undefined;\n          break;\n\n        case EventSubTypes.EDITED:\n          const { message } = event;\n          newMessages = { ...getMessage(message) };\n          break;\n\n        case EventSubTypes.REPLIED:\n          // We ignore this type, since these events also show up as normal messages\n          // TODO: We might want to use some of these types (copied over from Slack docs):\n          // \"You may also notice thread_subscribed, thread_unsubscribed, thread_marked update_thread_state event types\"\n          break;\n\n        default:\n          const { text, attachments, files, thread_ts, ts } = event;\n\n          if (!!thread_ts && !!ts && thread_ts !== ts) {\n            // This is a thread reply\n            const { user, text, channel } = event;\n            const reply: MessageReply = {\n              userId: user,\n              timestamp: ts,\n              text\n            };\n            vscode.commands.executeCommand(\n              SelfCommands.UPDATE_MESSAGE_REPLIES,\n              {\n                parentTimestamp: thread_ts,\n                channelId: channel,\n                reply,\n                provider: \"slack\"\n              }\n            );\n          } else {\n            const hasAttachment = attachments && attachments.length > 0;\n            const hasFiles = files && files.length > 0;\n\n            if (!!text || hasAttachment || hasFiles) {\n              const message = getMessage(event);\n              newMessages = {\n                ...newMessages,\n                ...message\n              };\n              this.handleMessageLinks(message);\n            }\n          }\n      }\n\n      // On sending messages, this also gets called, which means we\n      // send duplicate messages to the webview.\n      vscode.commands.executeCommand(SelfCommands.UPDATE_MESSAGES, {\n        channelId: event.channel,\n        messages: newMessages,\n        provider: \"slack\"\n      });\n    });\n\n    this.rtmClient.on(RTMEvents.REACTION_ADDED, event => {\n      const { user: userId, reaction: reactionName, item } = event;\n      const { channel: channelId, ts: msgTimestamp } = item;\n      vscode.commands.executeCommand(SelfCommands.ADD_MESSAGE_REACTION, {\n        userId,\n        channelId,\n        msgTimestamp,\n        reactionName,\n        provider: \"slack\"\n      });\n    });\n\n    this.rtmClient.on(RTMEvents.REACTION_REMOVED, event => {\n      const { user: userId, reaction: reactionName, item } = event;\n      const { channel: channelId, ts: msgTimestamp } = item;\n      vscode.commands.executeCommand(SelfCommands.REMOVE_MESSAGE_REACTION, {\n        userId,\n        channelId,\n        msgTimestamp,\n        reactionName,\n        provider: \"slack\"\n      });\n    });\n\n    this.rtmClient.on(RTMEvents.CHANNEL_MARKED, event => {\n      const { channel, ts, unread_count_display } = event;\n      vscode.commands.executeCommand(SelfCommands.CHANNEL_MARKED, {\n        channelId: channel,\n        readTimestamp: ts,\n        unreadCount: unread_count_display,\n        provider: \"slack\"\n      });\n    });\n\n    this.rtmClient.on(RTMEvents.GROUP_MARKED, event => {\n      const { channel, ts, unread_count_display } = event;\n      vscode.commands.executeCommand(SelfCommands.CHANNEL_MARKED, {\n        channelId: channel,\n        readTimestamp: ts,\n        unreadCount: unread_count_display,\n        provider: \"slack\"\n      });\n    });\n\n    this.rtmClient.on(RTMEvents.IM_MARKED, event => {\n      const { channel, ts, unread_count_display } = event;\n      vscode.commands.executeCommand(SelfCommands.CHANNEL_MARKED, {\n        channelId: channel,\n        readTimestamp: ts,\n        unreadCount: unread_count_display,\n        provider: \"slack\"\n      });\n    });\n\n    this.rtmClient.on(RTMEvents.PRESENCE_CHANGE, event => {\n      const { user: userId, presence: rawPresence } = event;\n      this.onPresenceChanged(userId, rawPresence);\n    });\n\n    this.rtmClient.on(RTMEvents.DND_UPDATED_SELF, event => {\n      // This is a no-op, since the DND_UPDATED_USER handler does everything\n      const { user: userId } = event;\n      const dndStatus: IDNDStatus = event.dnd_status;\n    });\n\n    this.rtmClient.on(RTMEvents.DND_UPDATED_USER, event => {\n      // This event is not fired when the snooze ends for a user\n      // Hence, we need to maintain that via dnd timers\n      const { user: userId } = event;\n      const dndStatus: IDNDStatus = event.dnd_status;\n      this.onDndStateChanged(userId, dndStatus);\n    });\n  }\n\n  isConnected(): boolean {\n    return !!this.rtmClient && this.rtmClient.connected;\n  }\n\n  start = (): Promise<CurrentUser> => {\n    return new Promise((resolve, reject) => {\n      this.rtmClient.once(RTMEvents.AUTHENTICATED, response => {\n        const { ok, team, self } = response;\n\n        if (ok) {\n          const { id, name } = self;\n          const { id: teamId, name: teamName } = team;\n          return resolve({\n            id,\n            name,\n            teams: [{ id: teamId, name: teamName }],\n            currentTeamId: teamId,\n            provider: Providers.slack\n          });\n        }\n      });\n\n      this.rtmClient.once(RTMEvents.ERROR, error => {\n        return reject(error);\n      });\n\n      // Note, rtm.start is heavily rate-limited\n      this.rtmClient.start();\n    });\n  };\n\n  sendMessage = (channelId: string, text: string) => {\n    return this.rtmClient.sendMessage(text, channelId);\n  };\n\n  handleMessageLinks = (incoming: ChannelMessages) => {\n    const messageTs = Object.keys(incoming)[0];\n    const message = incoming[messageTs];\n    let { text, userId } = message;\n    let uri: vscode.Uri | undefined;\n\n    if (text.startsWith(\"<\") && text.endsWith(\">\")) {\n      text = text.substring(1, text.length - 1); // Strip link symbols\n    }\n\n    try {\n      if (text.startsWith(\"http\")) {\n        uri = vscode.Uri.parse(text);\n        vscode.commands.executeCommand(SelfCommands.HANDLE_INCOMING_LINKS, {\n          provider: \"slack\",\n          senderId: userId,\n          uri\n        });\n      }\n    } catch (err) {}\n  };\n\n  subscribePresence = (users: Users) => {\n    this.rtmClient.subscribePresence(Object.keys(users));\n  };\n\n  disconnect() {\n    if (!!this.rtmClient) {\n      return this.rtmClient.disconnect();\n    }\n  }\n}\n\nexport default SlackMessenger;\n"
  },
  {
    "path": "src/status/index.ts",
    "content": "import * as vscode from \"vscode\";\nimport { SelfCommands } from \"../constants\";\n\nconst CHAT_OCTICON = \"$(comment-discussion)\";\n\nexport abstract class BaseStatusItem {\n    protected item: vscode.StatusBarItem;\n    protected disposableCommand: vscode.Disposable;\n    protected unreadCount: number = 0;\n    protected isVisible: boolean = false;\n\n    constructor(baseCommand: string, commandArgs: ChatArgs, commandModifier: string) {\n        this.item = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);\n\n        // We construct a new command to send args with base command\n        // From: https://github.com/Microsoft/vscode/issues/22353#issuecomment-325293438\n        const compound = `${baseCommand}.${commandModifier}.status`;\n        this.disposableCommand = vscode.commands.registerCommand(compound, () => {\n            return vscode.commands.executeCommand(baseCommand, commandArgs);\n        });\n\n        this.item.command = compound;\n    }\n\n    abstract updateCount(unreads: number): void;\n\n    show() {\n        if (!this.isVisible) {\n            this.item.show();\n            this.isVisible = true;\n        }\n    }\n\n    hide() {\n        if (this.isVisible) {\n            this.item.hide();\n            this.isVisible = false;\n        }\n    }\n\n    dispose() {\n        this.item.dispose();\n        this.disposableCommand.dispose();\n    }\n}\n\nexport class UnreadsStatusItem extends BaseStatusItem {\n    teamName: string;\n    providerName: string;\n\n    constructor(providerName: string, team: Team) {\n        const baseCommand = SelfCommands.CHANGE_CHANNEL;\n        let chatArgs: ChatArgs = {\n            providerName,\n            source: EventSource.status\n        };\n\n        const modifier = `${providerName}.${team.id}`; // This ensures discord teams have separate items\n        super(baseCommand, chatArgs, modifier);\n        this.providerName = providerName;\n        this.teamName = team.name;\n    }\n\n    updateCount(unreads: number) {\n        this.unreadCount = unreads;\n        this.item.text = `${CHAT_OCTICON} ${this.teamName}: ${unreads} new`;\n        return this.unreadCount > 0 ? this.show() : this.hide();\n    }\n}\n"
  },
  {
    "path": "src/store.ts",
    "content": "import * as vscode from \"vscode\";\nimport * as semver from \"semver\";\nimport { uuidv4, getExtensionVersion } from \"./utils\";\n\n// Large discord communities can have lots of users/channels\n// More than the quota of context.globalState\nconst VALUE_LENGTH_LIMIT = 100;\nconst MESSAGE_HISTORY_LIMIT = 50;\n\nconst stateKeys = {\n    EXTENSION_VERSION: \"extensionVersion\",\n    INSTALLATION_ID: \"installationId\",\n    LAST_CHANNEL_ID: \"lastChannelId\",\n    CHANNELS: \"channels\",\n    USER_INFO: \"userInfo\",\n    USERS: \"users\",\n    MESSAGE_HISTORY: \"messagesHistory\"\n};\n\nexport class Store implements IStore {\n    public installationId: string | undefined;\n    public existingVersion: string | undefined;\n    private currentUserInfo: { [provider: string]: CurrentUser };\n    private channels: { [provider: string]: Channel[] };\n    private users: { [provider: string]: Users };\n    private lastChannelId: { [provider: string]: string };\n\n    constructor(private context: vscode.ExtensionContext) {\n        this.loadInitialState();\n    }\n\n    loadInitialState() {\n        const { globalState } = this.context;\n        this.installationId = globalState.get(stateKeys.INSTALLATION_ID);\n        this.existingVersion = globalState.get(stateKeys.EXTENSION_VERSION);\n        this.channels = globalState.get(stateKeys.CHANNELS) || {};\n        this.currentUserInfo = globalState.get(stateKeys.USER_INFO) || {};\n        this.users = globalState.get(stateKeys.USERS) || {};\n        this.lastChannelId = globalState.get(stateKeys.LAST_CHANNEL_ID) || {};\n    }\n\n    async runStateMigrations() {\n        const currentVersion = getExtensionVersion();\n\n        if (!!currentVersion && this.existingVersion !== currentVersion) {\n            if (!!this.existingVersion) {\n                if (semver.lt(this.existingVersion, \"0.9.0\")) {\n                    await this.migrateFor09x();\n                }\n            }\n\n            this.updateExtensionVersion(currentVersion);\n            this.loadInitialState();\n        }\n    }\n\n    async migrateFor09x() {\n        // Run migrations for 0.9.x\n        const { globalState } = this.context;\n        const currentUser: any = globalState.get(stateKeys.USER_INFO);\n\n        if (!!currentUser) {\n            const { provider } = currentUser;\n\n            if (!!provider) {\n                const channels = globalState.get(stateKeys.CHANNELS);\n                const users = globalState.get(stateKeys.USERS);\n                const lastChannelId = globalState.get(stateKeys.LAST_CHANNEL_ID);\n                await globalState.update(stateKeys.USER_INFO, {\n                    [provider]: currentUser\n                });\n                await globalState.update(stateKeys.CHANNELS, {\n                    [provider]: channels\n                });\n                await globalState.update(stateKeys.USERS, { [provider]: users });\n                await globalState.update(stateKeys.LAST_CHANNEL_ID, {\n                    [provider]: lastChannelId\n                });\n            }\n        }\n    }\n\n    generateInstallationId(): string {\n        const uuidStr = uuidv4();\n        const { globalState } = this.context;\n        globalState.update(stateKeys.INSTALLATION_ID, uuidStr);\n        this.installationId = uuidStr;\n        return uuidStr;\n    }\n\n    updateExtensionVersion(version: string) {\n        const { globalState } = this.context;\n        return globalState.update(stateKeys.EXTENSION_VERSION, version);\n    }\n\n    getCurrentUser = (provider: string): CurrentUser | undefined => {\n        return this.currentUserInfo[provider];\n    };\n\n    getCurrentUserForAll = (): CurrentUser[] => {\n        const providers = Object.keys(this.currentUserInfo);\n        return providers.map(provider => this.currentUserInfo[provider]);\n    };\n\n    getUsers = (provider: string): Users => {\n        return this.users[provider] || {};\n    };\n\n    getUser = (provider: string, userId: string): User | undefined => {\n        const providerUsers = this.users[provider] || {};\n        return providerUsers[userId];\n    };\n\n    getChannels = (provider: string): Channel[] => {\n        return this.channels[provider] || [];\n    };\n\n    getLastChannelId = (provider: string): string | undefined => {\n        return this.lastChannelId[provider];\n    };\n\n    updateLastChannelId = (provider: string, channelId: string | undefined): Thenable<void> => {\n        const lastChannels = {\n            ...this.lastChannelId,\n            [provider]: channelId\n        };\n        this.lastChannelId = this.getObjectWithoutUndefined(lastChannels);\n        return this.context.globalState.update(stateKeys.LAST_CHANNEL_ID, this.lastChannelId);\n    };\n\n    updateUsers = (provider: string, users: Users): Thenable<void> => {\n        let newUsers = users;\n\n        this.users = {\n            ...this.users,\n            [provider]: newUsers\n        };\n        const totalUserCount = Object.values(this.users)\n            .map(usersObject => Object.keys(usersObject).length)\n            .reduce((acc, curr) => acc + curr);\n        const isUnderCacheSizeLimit = totalUserCount <= VALUE_LENGTH_LIMIT;\n\n        if (isUnderCacheSizeLimit) {\n            return this.context.globalState.update(stateKeys.USERS, this.users);\n        }\n\n        return Promise.resolve();\n    };\n\n    updateUser = (provider: string, userId: string, user: User) => {\n        // NOTE: This does not store to the local storage\n        const providerUsers = this.users[provider] || {};\n        this.users = {\n            ...this.users,\n            [provider]: {\n                ...providerUsers,\n                [userId]: { ...user }\n            }\n        };\n    };\n\n    updateChannels = (provider: string, channels: Channel[]): Thenable<void> => {\n        this.channels = { ...this.channels, [provider]: channels };\n        const totalChannelCount = Object.values(this.channels)\n            .map(channels => channels.length)\n            .reduce((acc, curr) => acc + curr);\n        const isUnderCacheSizeLimit = totalChannelCount <= VALUE_LENGTH_LIMIT;\n\n        if (isUnderCacheSizeLimit) {\n            return this.context.globalState.update(stateKeys.CHANNELS, this.channels);\n        }\n\n        return Promise.resolve();\n    };\n\n    updateCurrentUser = (provider: string, userInfo: CurrentUser | undefined): Thenable<void> => {\n        const cachedCurrentUser = this.currentUserInfo[provider];\n        let newCurrentUser: CurrentUser | undefined;\n\n        if (!userInfo) {\n            newCurrentUser = userInfo; // Resetting userInfo\n        } else {\n            // Copy cover the currentTeamId from existing state, if available\n            let currentTeamId = !!cachedCurrentUser ? cachedCurrentUser.currentTeamId : undefined;\n\n            if (!!userInfo.currentTeamId) {\n                currentTeamId = userInfo.currentTeamId;\n            }\n\n            newCurrentUser = { ...userInfo, currentTeamId };\n\n            // If this is Slack, our local state might know of more workspaces\n            if (provider === \"slack\" && !!cachedCurrentUser) {\n                let mergedTeams: any = {};\n                const { teams: newTeams } = userInfo;\n                const { teams: existingTeams } = cachedCurrentUser;\n                existingTeams.forEach(team => (mergedTeams[team.id] = team));\n                newTeams.forEach(team => (mergedTeams[team.id] = team));\n                const teams = Object.keys(mergedTeams).map(key => mergedTeams[key]);\n                newCurrentUser = {\n                    ...newCurrentUser,\n                    teams\n                };\n            }\n        }\n\n        const updatedCurrentUserInfo = {\n            ...this.currentUserInfo,\n            [provider]: !!newCurrentUser ? { ...newCurrentUser } : undefined\n        };\n        this.currentUserInfo = this.getObjectWithoutUndefined(updatedCurrentUserInfo);\n        return this.context.globalState.update(stateKeys.USER_INFO, this.currentUserInfo);\n    };\n\n    updateMessageHistory = (channelId: string, messages: ChannelMessages) => {\n        const existingMessages = this.context.globalState.get(stateKeys.MESSAGE_HISTORY) || {};\n        const timestamps = Object.keys(messages).map(t => +t);\n        let filteredTimestamps = timestamps;\n\n        if (timestamps.length > MESSAGE_HISTORY_LIMIT) {\n            const sortedTimestamps = timestamps.sort((a, b) => (b - a))\n            filteredTimestamps = sortedTimestamps.slice(0, MESSAGE_HISTORY_LIMIT);\n        }\n\n        let filteredMessages: ChannelMessages = {};\n        filteredTimestamps.forEach(ts => {\n            filteredMessages[`${ts}`] = messages[`${ts}`]\n        })\n\n        return this.context.globalState.update(stateKeys.MESSAGE_HISTORY, {\n            ...existingMessages,\n            [channelId]: filteredMessages\n        });\n    }\n\n    getMessageHistoryForChannel = (channelId: string) => {\n        const allMessages: Messages = this.context.globalState.get(stateKeys.MESSAGE_HISTORY) || {};\n        return allMessages[channelId] || {};\n    }\n\n    async clearProviderState(provider: string): Promise<void> {\n        this.currentUserInfo = this.getObjectWithoutUndefined({\n            ...this.currentUserInfo,\n            [provider]: undefined\n        });\n        this.users = this.getObjectWithoutUndefined({\n            ...this.users,\n            [provider]: undefined\n        });\n        this.channels = this.getObjectWithoutUndefined({\n            ...this.channels,\n            [provider]: undefined\n        });\n        this.lastChannelId = this.getObjectWithoutUndefined({\n            ...this.lastChannelId,\n            [provider]: undefined\n        });\n        await this.context.globalState.update(stateKeys.USER_INFO, this.currentUserInfo);\n        await this.context.globalState.update(stateKeys.USERS, this.users);\n        await this.context.globalState.update(stateKeys.CHANNELS, this.channels);\n        return this.context.globalState.update(stateKeys.LAST_CHANNEL_ID, this.lastChannelId);\n    }\n\n    private getObjectWithoutUndefined = (input: any) => {\n        // Remove undefined values from the input object\n        let withoutUndefined: any = {};\n        Object.keys(input).forEach(key => {\n            const value = input[key];\n            if (!!value) {\n                withoutUndefined[key] = value;\n            }\n        });\n        return withoutUndefined;\n    };\n}\n"
  },
  {
    "path": "src/strings.ts",
    "content": "export const CHANGE_CHANNEL_TITLE = \"Select a channel\";\n\nexport const CHANGE_WORKSPACE_TITLE = \"Select a workspace\";\n\nexport const CHANGE_PROVIDER_TITLE = \"Select a provider\";\n\nexport const RELOAD_CHANNELS = \"Reload Channels...\";\n\nexport const TOKEN_NOT_FOUND = \"Setup Team Chat to work for your account.\";\n\nexport const SETUP_SLACK = \"Set up Slack\";\n\nexport const SETUP_DISCORD = \"Set up Discord\";\n\nexport const REPORT_ISSUE = \"Report issue\";\n\nexport const RETRY = \"Retry\";\n\nexport const KEYCHAIN_ERROR =\n  \"The Team Chat extension is unable to access the system keychain.\";\n\nexport const TOKEN_PLACEHOLDER = \"Paste token here\";\n\nexport const AUTH_FAILED_MESSAGE =\n  \"Sign in failed. Help us get better by reporting an issue.\";\n\nexport const INVALID_TOKEN = (provider: string) =>\n  `The ${provider} token cannot be validated. Please enter a valid token.`;\n\nexport const INVALID_COMMAND = (text: string) =>\n  `${text} is not a recognised command.`;\n\nexport const UPLOADED_FILE = (link: string) => `uploaded a file: ${link}`;\n\nexport const LIVE_REQUEST_MESSAGE = \"wants to start a Live Share session\";\n\nexport const LIVE_SHARE_INVITE = (name: string) =>\n  `${name} has invited you to a Live Share collaboration session.`;\n\nexport const LIVE_SHARE_CHAT_NO_SESSION =\n  \"Chat requires an active Live Share collaboration session.\";\n\nexport const LIVE_SHARE_INFO_MESSAGES = {\n  started: \"_has started the Live Share session_\",\n  ended: \"_has ended the Live Share session_\",\n  joined: \"_has joined the Live Share session_\",\n  left: \"_has left the Live Share session_\"\n};\n\nexport const LIVE_SHARE_CONFIRM_SIGN_OUT = (provider: string) =>\n  `To use chat over VS Live Share, you need to sign out of your ${provider} account.`;\n\nexport const SIGN_OUT = \"Sign out\";\n\nexport const SELECT_SELF_PRESENCE = \"Select your presence status\";\n\nexport const SELECT_DND_DURATION = \"Select snooze duration for Slack\";\n\nexport const UNABLE_TO_MATCH_CONTACT =\n  \"Could not start chat: unable to match this contact.\";\n\nexport const NO_LIVE_SHARE_CHAT_ON_HOST = \n  \"Live Share Chat is unavailable for this session, since the host does not have it.\";\n"
  },
  {
    "path": "src/telemetry.ts",
    "content": "import * as vscode from \"vscode\";\nimport * as Mixpanel from \"mixpanel\";\nimport { MIXPANEL_TOKEN } from \"./constants\";\nimport { ConfigHelper } from \"./config\";\nimport Manager from \"./manager\";\nimport { getVersions, Versions, hasVslsExtensionPack } from \"./utils\";\n\nconst BATCH_SIZE = 10;\nconst INTERVAL_TIMEOUT = 30 * 60 * 1000; // 30 mins in ms\n\nexport default class TelemetryReporter implements vscode.Disposable {\n  private hasUserOptIn: boolean = false;\n  private uniqueId: string | undefined; // TODO: remove undefined\n  private mixpanel: Mixpanel.Mixpanel | undefined;\n  private versions: Versions;\n  private hasExtensionPack: boolean;\n  private pendingEvents: TelemetryEvent[] = [];\n  private interval: NodeJS.Timer | undefined;\n\n  constructor(private manager: Manager) {\n    const { installationId } = this.manager.store;\n    this.uniqueId = installationId;\n    this.versions = getVersions();\n\n    if (process.env.IS_DEBUG !== \"true\") {\n      this.hasUserOptIn = ConfigHelper.hasTelemetry();\n    }\n\n    if (this.hasUserOptIn) {\n      this.mixpanel = Mixpanel.init(MIXPANEL_TOKEN);\n\n      this.interval = setInterval(() => {\n        if (this.pendingEvents.length > 0) {\n          return this.flushBatch();\n        }\n      }, INTERVAL_TIMEOUT);\n    }\n\n    this.hasExtensionPack = hasVslsExtensionPack();\n  }\n\n  setUniqueId(uniqueId: string) {\n    this.uniqueId = uniqueId;\n  }\n\n  dispose(): Promise<any> {\n    if (!!this.interval) {\n      clearInterval(this.interval);\n    }\n\n    if (this.pendingEvents.length > 0) {\n      return this.flushBatch();\n    }\n\n    return Promise.resolve();\n  }\n\n  record(\n    name: EventType,\n    source: EventSource | undefined,\n    channelId: string | undefined, // TODO: change this to channelType\n    provider: string | undefined\n  ) {\n    let channelType = undefined;\n\n    if (!!channelId && !!provider) {\n      const channel = this.manager.getChannel(provider, channelId);\n      channelType = !!channel ? channel.type : undefined;\n    }\n\n    const event: TelemetryEvent = {\n      type: name,\n      time: new Date(),\n      properties: {\n        provider,\n        source: source,\n        channel_type: channelType\n      }\n    };\n\n    if (this.hasUserOptIn) {\n      this.pendingEvents.push(event);\n      const hasActivationEvents = name === EventType.activationEnded || name === EventType.activationStarted;\n\n      if (this.pendingEvents.length >= BATCH_SIZE || hasActivationEvents) {\n        this.flushBatch();\n      }\n    }\n  }\n\n  getMxEvent(event: TelemetryEvent): Mixpanel.Event {\n    const { os, extension, editor } = this.versions;\n    const { type: name, properties, time } = event;\n    const { provider } = properties;\n    return {\n      event: name,\n      properties: {\n        distinct_id: this.uniqueId,\n        extension_version: extension,\n        os_version: os,\n        editor_version: editor,\n        has_extension_pack: this.hasExtensionPack,\n        is_authenticated: this.manager.isAuthenticated(provider),\n        ...properties,\n        time\n      }\n    };\n  }\n\n  flushBatch(): Promise<any> {\n    const copy = [...this.pendingEvents];\n    const events = copy.map(event => this.getMxEvent(event));\n    this.pendingEvents = [];\n\n    return new Promise((resolve, reject) => {\n      if (!this.mixpanel) {\n        resolve();\n      } else {\n        this.mixpanel.track_batch(events, error => {\n          if (!error) {\n            resolve();\n          } else {\n            // We are not going to retry with `copy`\n            reject();\n          }\n        });\n      }\n    });\n  }\n}\n"
  },
  {
    "path": "src/test/extension.test.ts",
    "content": "//\n// Note: This example test is leveraging the Mocha test framework.\n// Please refer to their documentation on https://mochajs.org/ for help.\n//\nimport * as assert from \"assert\";\nimport * as vscode from \"vscode\";\nimport * as myExtension from \"../extension\";\n\n// Defines a Mocha test suite to group tests of similar kind together\nsuite(\"Extension Tests\", function () {\n  // Defines a Mocha unit test\n  test(\"Something 1\", function () {\n    assert.equal(-1, [1, 2, 3].indexOf(5));\n    assert.equal(-1, [1, 2, 3].indexOf(0));\n  });\n});\n"
  },
  {
    "path": "src/test/index.ts",
    "content": "//\n// PLEASE DO NOT MODIFY / DELETE UNLESS YOU KNOW WHAT YOU ARE DOING\n//\n// This file is providing the test runner to use when running extension tests.\n// By default the test runner in use is Mocha based.\n//\n// You can provide your own test runner if you want to override it by exporting\n// a function run(testRoot: string, clb: (error:Error) => void) that the extension\n// host can call to run the tests. The test runner is expected to use console.log\n// to report the results back to the caller. When the tests are finished, return\n// a possible error to the callback or null if none.\n\nimport * as testRunner from \"vscode/lib/testrunner\";\n\n// You can directly control Mocha options by uncommenting the following lines\n// See https://github.com/mochajs/mocha/wiki/Using-mocha-programmatically#set-options for more info\ntestRunner.configure({\n  ui: \"tdd\", // the TDD UI is being used in extension.test.ts (suite, test, etc.)\n  useColors: true // colored output from test results\n});\n\nmodule.exports = testRunner;\n"
  },
  {
    "path": "src/test/manager.test.ts",
    "content": "import * as assert from \"assert\";\nimport { Store } from \"../store\";\nimport Manager from \"../manager\";\nimport { mock, instance, verify, when } from \"ts-mockito\";\nimport { ChatProviderManager } from \"../manager/chatManager\";\nimport { SlackChatProvider } from \"../slack\";\n\nlet mockedStore = mock(Store);\nlet store = instance(mockedStore);\nlet manager: Manager = new Manager(store);\n\nlet slackProvider = new SlackChatProvider(\"test-token\", manager);\nlet slackManager = new ChatProviderManager(\n  store,\n  \"slack\",\n  \"test-team-id\",\n  slackProvider,\n  manager\n);\nmanager.chatProviders.set(\"slack\" as Providers, slackManager);\n\nsuite(\"Manager tests\", function() {\n  setup(() => {\n    const currentUser = {\n      id: \"user-id\",\n      name: \"user-name\",\n      teams: [],\n      currentTeamId: \"team-id\",\n      provider: Providers.slack\n    };\n    when(mockedStore.getCurrentUserForAll()).thenReturn([{ ...currentUser }]);\n    when(mockedStore.getCurrentUser(\"slack\")).thenReturn({ ...currentUser });\n    manager.initializeToken();\n  });\n\n  test(\"Get enabled providers works\", function() {\n    const enabledProviders = manager.getEnabledProviders().map(e => e.provider);\n    assert.equal(enabledProviders.indexOf(\"slack\") >= 0, true);\n  });\n\n  test(\"Clear all works\", function() {\n    assert.notEqual(manager.chatProviders.get(\"slack\" as Providers), undefined);\n    manager.clearAll();\n    verify(mockedStore.clearProviderState(\"slack\")).once();\n    assert.equal(manager.chatProviders.get(\"slack\" as Providers), undefined);\n  });\n\n  test(\"Authentication check works\", function() {\n    assert.equal(slackManager.isAuthenticated(), true);\n    when(mockedStore.getCurrentUser(\"slack\")).thenReturn(undefined);\n    assert.equal(slackManager.isAuthenticated(), false);\n  });\n});\n"
  },
  {
    "path": "src/test/utils.test.ts",
    "content": "import * as assert from \"assert\";\nimport { sanitiseTokenString } from \"../utils\";\n\nsuite(\"utility function tests\", function() {\n  setup(() => {});\n\n  test(\"sanitise token works\", function() {\n    assert.equal(sanitiseTokenString('\"token\"'), \"token\");\n    assert.equal(sanitiseTokenString(\" token\"), \"token\");\n    assert.equal(sanitiseTokenString(' \"token\"'), \"token\");\n  });\n});\n"
  },
  {
    "path": "src/tree/base.ts",
    "content": "import * as vscode from \"vscode\";\nimport { ChannelTreeItem } from \"./treeItem\";\nimport { equals, notUndefined } from \"../utils\";\n\nexport interface ISortingFunction {\n  (a: ChannelLabel, b: ChannelLabel): number;\n}\n\nexport interface IFilterFunction {\n  (a: ChannelLabel): boolean;\n}\n\nexport class BaseChannelsListTreeProvider\n  implements vscode.TreeDataProvider<ChatTreeNode>, vscode.Disposable {\n  private _onDidChangeTreeData = new vscode.EventEmitter<ChatTreeNode>();\n  readonly onDidChangeTreeData? = this._onDidChangeTreeData.event;\n  protected _disposables: vscode.Disposable[] = [];\n\n  protected sortingFn: ISortingFunction = (a: ChannelLabel, b: ChannelLabel) =>\n    a.label.localeCompare(b.label);\n  protected filterFn: IFilterFunction = () => true;\n  protected channelLabels: ChannelLabel[] = [];\n\n  constructor(protected providerName: string, protected viewId: string) {\n    this._disposables.push(\n      vscode.window.registerTreeDataProvider(this.viewId, this)\n    );\n  }\n\n  dispose() {\n    this._disposables.forEach(dispose => dispose.dispose());\n  }\n\n  async refresh(treeItem?: ChatTreeNode) {\n    return treeItem\n      ? this._onDidChangeTreeData.fire(treeItem)\n      : this._onDidChangeTreeData.fire();\n  }\n\n  getLabelsObject(\n    channeLabels: ChannelLabel[]\n  ): { [channelId: string]: ChannelLabel } {\n    let result: { [channelId: string]: ChannelLabel } = {};\n    channeLabels.forEach(label => {\n      const { channel } = label;\n      result[channel.id] = label;\n    });\n    return result;\n  }\n\n  updateChannels(channelLabels: ChannelLabel[]) {\n    const filtered = channelLabels.filter(this.filterFn).sort(this.sortingFn);\n    const prevLabels = this.getLabelsObject(this.channelLabels);\n    const newLabels = this.getLabelsObject(filtered);\n    this.channelLabels = filtered;\n    const prevKeys = new Set(Object.keys(prevLabels));\n    const newKeys = new Set(Object.keys(newLabels));\n\n    if (!equals(prevKeys, newKeys)) {\n      // We have new channels, so we are replacing everything\n      // Can potentially optimize this\n      return this.refresh();\n    }\n\n    // Looking for changes in presence and unread\n    Object.keys(newLabels).forEach(channelId => {\n      const newLabel = newLabels[channelId];\n      const prevLabel = prevLabels[channelId];\n\n      if (prevLabel.unread !== newLabel.unread) {\n        // Can we send just this element?\n        this.refresh();\n      }\n\n      if (prevLabel.presence !== newLabel.presence) {\n        // Can we send just this element?\n        this.refresh();\n      }\n    });\n  }\n\n  getParent = (element: ChatTreeNode): vscode.ProviderResult<ChatTreeNode> => {\n    const { channel } = element;\n\n    if (!!channel && !!channel.categoryName) {\n      return Promise.resolve(this.getItemForCategory(channel.categoryName));\n    }\n  };\n\n  getChildren = (\n    element?: ChatTreeNode\n  ): vscode.ProviderResult<ChatTreeNode[]> => {\n    if (!element) {\n      return this.getRootChildren();\n    }\n\n    if (!!element && element.isCategory) {\n      return this.getChildrenForCategory(element);\n    }\n  };\n\n  getChildrenForCategory = (\n    element: ChatTreeNode\n  ): vscode.ProviderResult<ChatTreeNode[]> => {\n    const { label: category } = element;\n    const channels = this.channelLabels\n      .filter(channelLabel => {\n        const { channel } = channelLabel;\n        return channel.categoryName === category;\n      })\n      .map(this.getItemForChannel);\n    return Promise.resolve(channels);\n  };\n\n  getRootChildren = (): vscode.ProviderResult<ChatTreeNode[]> => {\n    const channelsWithoutCategories = this.channelLabels\n      .filter(channelLabel => !channelLabel.channel.categoryName)\n      .map(this.getItemForChannel);\n    const categories: string[] = this.channelLabels\n      .map(channelLabel => channelLabel.channel.categoryName)\n      .filter(notUndefined);\n    const uniqueCategories = categories\n      .filter((item, pos) => categories.indexOf(item) === pos)\n      .map(category => this.getItemForCategory(category));\n    return Promise.resolve([...channelsWithoutCategories, ...uniqueCategories]);\n  };\n\n  getItemForChannel = (channelLabel: ChannelLabel): ChatTreeNode => {\n    const { label, presence, channel } = channelLabel;\n    return {\n      label,\n      presence,\n      channel,\n      isCategory: false,\n      user: undefined,\n      team: undefined,\n      providerName: this.providerName\n    };\n  };\n\n  getItemForCategory = (category: string): ChatTreeNode => {\n    return {\n      label: category,\n      presence: UserPresence.unknown,\n      isCategory: true,\n      channel: undefined,\n      user: undefined,\n      team: undefined,\n      providerName: this.providerName\n    };\n  };\n\n  getTreeItem = (element: ChatTreeNode): vscode.TreeItem => {\n    const { label, presence, isCategory, channel, user } = element;\n    const treeItem = new ChannelTreeItem(\n      label,\n      presence,\n      isCategory,\n      this.providerName,\n      channel,\n      user\n    );\n    return treeItem;\n  };\n}\n"
  },
  {
    "path": "src/tree/index.ts",
    "content": "import * as vscode from \"vscode\";\nimport {\n  BaseChannelsListTreeProvider,\n  IFilterFunction,\n  ISortingFunction\n} from \"./base\";\nimport { WorkspaceTreeItem } from \"./treeItem\";\nimport { equals, notUndefined } from \"../utils\";\n\nexport class WorkspacesTreeProvider extends BaseChannelsListTreeProvider {\n  protected filterFn: IFilterFunction = c => c.unread > 0;\n  protected sortingFn: ISortingFunction = (a, b) => b.unread - a.unread;\n  private userInfo: CurrentUser | undefined;\n\n  constructor(provider: string) {\n    super(provider, `chat.treeView.workspaces.${provider}`);\n  }\n\n  updateCurrentUser(userInfo: CurrentUser) {\n    if (!this.userInfo) {\n      this.userInfo = userInfo;\n      this.refresh();\n    } else {\n      const existingTeamIds = this.userInfo.teams.map(team => team.id);\n      const newTeamIds = userInfo.teams.map(team => team.id);\n      const hasTeamsChanged = !equals(\n        new Set(existingTeamIds),\n        new Set(newTeamIds)\n      );\n      const hasCurrentChanged =\n        this.userInfo.currentTeamId !== userInfo.currentTeamId;\n\n      if (hasCurrentChanged || hasTeamsChanged) {\n        this.userInfo = userInfo;\n        this.refresh();\n      }\n    }\n  }\n\n  getChildren = (\n    element?: ChatTreeNode\n  ): vscode.ProviderResult<ChatTreeNode[]> => {\n    if (!element) {\n      if (!!this.userInfo) {\n        const { teams } = this.userInfo;\n        return teams.map(this.getItemForTeam);\n      }\n    }\n  };\n\n  getItemForTeam = (team: Team): ChatTreeNode => {\n    let label = team.name;\n\n    if (!!this.userInfo) {\n      if (this.userInfo.currentTeamId === team.id) {\n        label = `${label} (active)`;\n      }\n    }\n\n    return {\n      label,\n      presence: UserPresence.unknown,\n      isCategory: false,\n      channel: undefined,\n      user: undefined,\n      team: team,\n      providerName: this.providerName\n    };\n  };\n\n  getTreeItem = (element: ChatTreeNode): vscode.TreeItem => {\n    const { label, team, providerName } = element;\n    const treeItem = new WorkspaceTreeItem(label, providerName, team);\n    return treeItem;\n  };\n}\n\nexport class UnreadsTreeProvider extends BaseChannelsListTreeProvider {\n  protected filterFn: IFilterFunction = c => c.unread > 0;\n  protected sortingFn: ISortingFunction = (a, b) => b.unread - a.unread;\n\n  constructor(provider: string) {\n    super(provider, `chat.treeView.unreads.${provider}`);\n  }\n}\n\nexport class ChannelTreeProvider extends BaseChannelsListTreeProvider {\n  protected filterFn: IFilterFunction = c =>\n    c.channel.type === ChannelType.channel;\n\n  constructor(provider: string) {\n    super(provider, `chat.treeView.channels.${provider}`);\n  }\n}\n\nexport class GroupTreeProvider extends BaseChannelsListTreeProvider {\n  protected filterFn: IFilterFunction = c =>\n    c.channel.type === ChannelType.group;\n\n  constructor(provider: string) {\n    super(provider, `chat.treeView.groups.${provider}`);\n  }\n}\n\nexport class IMsTreeProvider extends BaseChannelsListTreeProvider {\n  protected filterFn: IFilterFunction = c => c.channel.type === ChannelType.im;\n\n  constructor(provider: string) {\n    super(provider, `chat.treeView.ims.${provider}`);\n  }\n}\n\nexport class OnlineUsersTreeProvider extends BaseChannelsListTreeProvider {\n  private users: User[] = [];\n  private imChannels: { [userId: string]: Channel } = {};\n  private DM_ROLE_NAME = \"Direct Messages\";\n  private OTHERS_ROLE_NAME = \"Others\";\n\n  constructor(providerName: string) {\n    super(providerName, `chat.treeView.onlineUsers.${providerName}`);\n  }\n\n  updateData(\n    currentUser: CurrentUser,\n    users: Users,\n    imChannels: { [userId: string]: Channel }\n  ) {\n    const { id: currentId } = currentUser;\n    const ALLOWED_PRESENCE = [\n      UserPresence.available,\n      UserPresence.doNotDisturb,\n      UserPresence.idle\n    ];\n\n    const prevUserIds = new Set(this.users.map(user => user.id));\n    this.users = Object.keys(users)\n      .map(userId => users[userId])\n      .filter(user => ALLOWED_PRESENCE.indexOf(user.presence) >= 0)\n      .filter(user => user.id !== currentId); // Can't have the self user in this list\n    const newUserIds = new Set(this.users.map(user => user.id));\n    this.imChannels = imChannels;\n\n    if (!equals(prevUserIds, newUserIds)) {\n      return this.refresh();\n    }\n  }\n\n  getItemForUser(user: User): ChatTreeNode {\n    return {\n      label: user.name,\n      presence: user.presence,\n      isCategory: false,\n      user,\n      channel: this.imChannels[user.id],\n      team: undefined,\n      providerName: this.providerName\n    };\n  }\n\n  getChildrenForCategory = (element: ChatTreeNode) => {\n    const { label: role } = element;\n\n    if (role === this.DM_ROLE_NAME) {\n      const dmUserIds = Object.keys(this.imChannels);\n      return Promise.resolve(\n        this.users\n          .filter(user => dmUserIds.indexOf(user.id) >= 0)\n          .map(user => this.getItemForUser(user))\n      );\n    }\n\n    if (role === this.OTHERS_ROLE_NAME) {\n      const usersWithoutRoles = this.users.filter(user => !user.roleName);\n      return Promise.resolve(\n        usersWithoutRoles.map(user => this.getItemForUser(user))\n      );\n    }\n\n    const users = this.users\n      .filter(user => user.roleName === role)\n      .map(user => this.getItemForUser(user));\n    return Promise.resolve(users);\n  };\n\n  getRootChildren = (): vscode.ProviderResult<ChatTreeNode[]> => {\n    if (this.providerName === \"slack\") {\n      return Promise.resolve(this.users.map(user => this.getItemForUser(user)));\n    }\n\n    // Since Discord guilds can have lots of members, we want to ensure all\n    // members are categorised for easy navigation.\n    // For this, we introduced 2 roles: \"Direct Messages\" and \"Others\"\n    // const dmRoles = this.\n    let rootElements = [];\n    const dmUserIds = Object.keys(this.imChannels);\n\n    if (dmUserIds.length > 0) {\n      rootElements.push(this.getItemForCategory(this.DM_ROLE_NAME));\n    }\n\n    const roles = this.users\n      .filter(user => !!user.roleName)\n      .map(user => user.roleName);\n    const uniqueRoles = roles\n      .filter((item, pos) => roles.indexOf(item) === pos)\n      .filter(notUndefined)\n      .map(role => this.getItemForCategory(role));\n\n    if (uniqueRoles.length > 0) {\n      rootElements = [...rootElements, ...uniqueRoles];\n    }\n\n    const usersWithoutRoles = this.users.filter(user => !user.roleName);\n\n    if (usersWithoutRoles.length > 0) {\n      rootElements.push(this.getItemForCategory(this.OTHERS_ROLE_NAME));\n    }\n\n    return Promise.resolve(rootElements);\n  };\n\n  getParent = (element: ChatTreeNode): vscode.ProviderResult<ChatTreeNode> => {\n    return;\n  };\n}\n"
  },
  {
    "path": "src/tree/treeItem.ts",
    "content": "import * as vscode from \"vscode\";\nimport * as path from \"path\";\nimport { SelfCommands, EXTENSION_ID } from \"../constants\";\n\nconst selfExtension = vscode.extensions.getExtension(EXTENSION_ID) as vscode.Extension<any>;\nconst BASE_PATH = path.join(selfExtension.extensionPath, \"public\", \"icons\", \"presence\");\n\nconst PRESENCE_ICONS = {\n  green: path.join(BASE_PATH, \"green.svg\"),\n  red: path.join(BASE_PATH, \"red.svg\"),\n  yellow: path.join(BASE_PATH, \"yellow.svg\")\n};\n\nexport class WorkspaceTreeItem extends vscode.TreeItem {\n  constructor(label: string, provider: string, team: Team | undefined) {\n    super(label);\n\n    if (!!team) {\n      this.command = {\n        command: SelfCommands.CHANGE_WORKSPACE,\n        title: \"\",\n        arguments: [{ team, provider }]\n      };\n    }\n  }\n}\n\nexport class ChannelTreeItem extends vscode.TreeItem {\n  constructor(\n    label: string,\n    presence: UserPresence,\n    isCategory: boolean,\n    providerName: string,\n    channel?: Channel,\n    user?: User\n  ) {\n    super(label);\n\n    if (!!channel) {\n      // This is a channel item\n      this.contextValue = \"channel\";\n      const chatArgs: ChatArgs = {\n        channelId: channel ? channel.id : undefined,\n        user,\n        providerName,\n        source: EventSource.activity\n      };\n      this.command = {\n        command: SelfCommands.OPEN_WEBVIEW,\n        title: \"\",\n        arguments: [chatArgs]\n      };\n    }\n\n    switch (presence) {\n      case UserPresence.available:\n        this.iconPath = {\n          light: PRESENCE_ICONS.green,\n          dark: PRESENCE_ICONS.green\n        };\n        break;\n      case UserPresence.doNotDisturb:\n        this.iconPath = {\n          light: PRESENCE_ICONS.red,\n          dark: PRESENCE_ICONS.red\n        };\n        break;\n      case UserPresence.idle:\n        this.iconPath = {\n          light: PRESENCE_ICONS.yellow,\n          dark: PRESENCE_ICONS.yellow\n        };\n        break;\n    }\n\n    if (isCategory) {\n      this.collapsibleState = vscode.TreeItemCollapsibleState.Collapsed;\n    }\n  }\n}\n"
  },
  {
    "path": "src/types.ts",
    "content": "interface IChatProvider {\n    validateToken: () => Promise<CurrentUser | undefined>;\n    fetchUsers: () => Promise<Users>;\n    fetchUserInfo: (userId: string) => Promise<User | undefined>;\n    fetchChannels: (users: Users) => Promise<Channel[]>;\n    fetchChannelInfo: (channel: Channel) => Promise<Channel | undefined>;\n    loadChannelHistory: (channelId: string) => Promise<ChannelMessages>;\n    getUserPreferences: () => Promise<UserPreferences | undefined>;\n    markChannel: (channel: Channel, ts: string) => Promise<Channel | undefined>;\n    fetchThreadReplies: (channelId: string, ts: string) => Promise<Message | undefined>;\n    sendMessage: (text: string, currentUserId: string, channelId: string) => Promise<void>;\n    sendTyping: (currentUserId: string, channelId: string) => Promise<void>;\n    sendThreadReply: (text: string, currentUserId: string, channelId: string, parentTimestamp: string) => Promise<void>;\n    connect: () => Promise<CurrentUser | undefined>;\n    isConnected: () => boolean;\n    updateSelfPresence: (presence: UserPresence, durationInMinutes: number) => Promise<UserPresence | undefined>;\n    subscribePresence: (users: Users) => void;\n    createIMChannel: (user: User) => Promise<Channel | undefined>;\n    destroy: () => Promise<void>;\n}\n\nconst enum UserPresence {\n    unknown = \"unknown\",\n    available = \"available\",\n    idle = \"idle\",\n    doNotDisturb = \"doNotDisturb\",\n    invisible = \"invisible\",\n    offline = \"offline\"\n}\n\ninterface User {\n    id: string;\n    name: string;\n    email?: string; // Discord does not have emails, hence the ?\n    fullName: string;\n    internalName?: string; // Used by slack provider to associate DMs\n    imageUrl: string;\n    smallImageUrl: string;\n    presence: UserPresence;\n    isBot?: boolean;\n    isDeleted?: boolean;\n    roleName?: string;\n}\n\ninterface UserPreferences {\n    mutedChannels?: string[];\n}\n\nconst enum Providers {\n    slack = \"slack\",\n    discord = \"discord\",\n    vslsSpaces = \"vslsSpaces\"\n}\n\ninterface CurrentUser {\n    id: string;\n    name: string;\n    teams: Team[];\n    currentTeamId: string | undefined;\n    provider: Providers;\n}\n\ninterface Team {\n    // Team represents workspace for Slack, guild for Discord\n    id: string;\n    name: string;\n}\n\ninterface Users {\n    [id: string]: User;\n}\n\ninterface MessageAttachment {\n    name: string;\n    permalink: string;\n}\n\ninterface MessageContent {\n    author: string;\n    authorIcon?: string;\n    pretext: string;\n    title: string;\n    titleLink: string;\n    text: string;\n    footer: string;\n    borderColor?: string;\n}\n\ninterface MessageReaction {\n    name: string;\n    count: number;\n    userIds: string[];\n}\n\ninterface MessageReply {\n    userId: string;\n    timestamp: string;\n    text?: string;\n    attachment?: MessageAttachment;\n}\n\ninterface MessageReplies {\n    [timestamp: string]: MessageReply;\n}\n\ninterface Message {\n    timestamp: string;\n    userId: string;\n    text: string;\n    isEdited?: Boolean;\n    attachment?: MessageAttachment;\n    content: MessageContent | undefined;\n    reactions: MessageReaction[];\n    replies: MessageReplies;\n    // TODO - add\n    // subscribed (for threads)\n}\n\ninterface ChannelMessages {\n    [timestamp: string]: Message;\n}\n\ninterface ChannelMessagesWithUndefined {\n    [timestamp: string]: Message | undefined;\n}\n\ninterface Messages {\n    [channelId: string]: ChannelMessages;\n}\n\nconst enum ChannelType {\n    channel = \"channel\",\n    group = \"group\",\n    im = \"im\"\n}\n\ninterface IContactMetadata {\n    id: string;\n    email: string;\n}\n\ninterface Channel {\n    id: string;\n    name: string;\n    type: ChannelType;\n    readTimestamp: string | undefined;\n    unreadCount: number;\n    categoryName?: string; // for Discord\n    contactMetadata?: IContactMetadata; // for Live Share DMs\n}\n\ninterface ChannelLabel {\n    channel: Channel;\n    providerName: string;\n    teamName: string;\n    unread: number;\n    label: string;\n    presence: UserPresence;\n}\n\nconst enum MessageType {\n    text = \"text\",\n    thread_reply = \"thread_reply\",\n    command = \"command\",\n    link = \"link\",\n    internal = \"internal\"\n}\n\ninterface ExtensionMessage {\n    type: MessageType;\n    text: string;\n}\n\ninterface UIMessage {\n    fontFamily: string;\n    fontSize: string;\n    provider: string;\n    messages: ChannelMessages;\n    users: Users;\n    channel: Channel;\n    currentUser: CurrentUser;\n    statusText: string;\n    // atMentions: User[];\n}\n\ninterface UIMessageDateGroup {\n    groups: UIMessageGroup[];\n    date: string;\n}\n\ninterface UIMessageGroup {\n    messages: Message[];\n    userId: string;\n    user: User;\n    minTimestamp: string;\n    key: string;\n}\n\ninterface IStore {\n    installationId: string | undefined; // TODO: remove undefined\n    existingVersion: string | undefined;\n    generateInstallationId: () => string;\n    getCurrentUser: (provider: string) => CurrentUser | undefined;\n    getCurrentUserForAll: () => CurrentUser[];\n    getUsers: (provider: string) => Users;\n    getUser: (provider: string, userId: string) => User | undefined;\n    getChannels: (provider: string) => Channel[];\n    getLastChannelId: (provider: string) => string | undefined;\n    updateUsers: (provider: string, users: Users) => Thenable<void>;\n    updateUser: (provider: string, userId: string, user: User) => void;\n    updateChannels: (provider: string, channels: Channel[]) => Thenable<void>;\n    updateCurrentUser: (provider: string, userInfo: CurrentUser | undefined) => Thenable<void>;\n    updateLastChannelId: (provider: string, channelId: string | undefined) => Thenable<void>;\n    clearProviderState: (provider: string) => Promise<void>;\n    updateExtensionVersion: (version: string) => Thenable<void>;\n    getMessageHistoryForChannel: (channelId: string) => ChannelMessages;\n    updateMessageHistory: (channelId: string, messages: ChannelMessages) => Thenable<void>;\n}\n\ninterface IManager {\n    isTokenInitialized: boolean;\n    store: IStore;\n    isAuthenticated: (provider: string) => boolean;\n    getChannel: (provider: string, channelId: string | undefined) => Channel | undefined;\n    getIMChannel: (provider: string, user: User) => Channel | undefined;\n    getChannelLabels: (provider: string) => any;\n    getUnreadCount: (provider: string, channel: Channel) => number;\n    getCurrentUserFor: (provider: string) => CurrentUser | undefined;\n    getUserPresence: (provider: string, userId: string) => UserPresence | undefined;\n    getCurrentUserPresence: (provider: string) => UserPresence | undefined;\n    updateAllUI: () => void;\n    updateTreeViewsForProvider: (provider: string) => void;\n    updateStatusItemsForProvider: (provider: string) => void;\n    updateWebviewForProvider: (provider: string, channelId: string) => void;\n    getMessages: (provider: string) => Messages;\n}\n\ninterface IViewsManager {\n    updateTreeViews: (provider: string) => void;\n    updateWebview: (provider: string) => void;\n    updateStatusItem: (provider: string, team: Team) => void;\n}\n\ninterface ChatArgs {\n    channelId?: string;\n    user?: User;\n    providerName: string;\n    source: EventSource;\n}\n\nconst enum EventSource {\n    status = \"status_item\",\n    command = \"command_palette\",\n    activity = \"activity_bar\",\n    info = \"info_message\",\n    slash = \"slash_command\",\n    vslsContacts = \"vsls_contacts_panel\",\n    vslsStarted = \"vsls_started\"\n}\n\nconst enum EventType {\n    extensionInstalled = \"extension_installed\",\n    viewOpened = \"webview_opened\",\n    messageSent = \"message_sent\",\n    vslsShared = \"vsls_shared\",\n    vslsStarted = \"vsls_started\",\n    vslsEnded = \"vsls_ended\",\n    tokenConfigured = \"token_configured\",\n    channelChanged = \"channel_changed\",\n    authStarted = \"auth_started\",\n    activationStarted = \"activation_started\",\n    activationEnded = \"activation_ended\"\n}\n\ninterface EventProperties {\n    provider: string | undefined;\n    source: EventSource | undefined;\n    channel_type: ChannelType | undefined;\n}\n\ninterface TelemetryEvent {\n    type: EventType;\n    time: Date;\n    properties: EventProperties;\n}\n\ninterface ChatTreeNode {\n    label: string;\n    channel: Channel | undefined;\n    user: User | undefined;\n    team: Team | undefined;\n    isCategory: boolean;\n    presence: UserPresence;\n    providerName: string;\n}\n\ntype InitialState = {\n    provider: string;\n    teamId: string | undefined;\n};\n"
  },
  {
    "path": "src/uriHandler.ts",
    "content": "import * as vscode from \"vscode\";\nimport * as str from \"./strings\";\nimport IssueReporter from \"./issues\";\nimport { ConfigHelper } from \"./config\";\n\nexport class ExtensionUriHandler implements vscode.UriHandler {\n  handleUri(uri: vscode.Uri): vscode.ProviderResult<void> {\n    // vscode://karigari.chat/redirect?url=foobar\n    const { path, query } = uri;\n    const parsed = this.parseQuery(query);\n    const { token, msg, service, team } = parsed;\n\n    switch (path) {\n      case \"/redirect\":\n        return ConfigHelper.setToken(token, service, team);\n      case \"/error\":\n        return this.showIssuePrompt(msg, service);\n    }\n  }\n\n  showIssuePrompt(errorMsg: string, service: string) {\n    const actionItems = [str.REPORT_ISSUE];\n    vscode.window\n      .showWarningMessage(str.AUTH_FAILED_MESSAGE, ...actionItems)\n      .then(selected => {\n        switch (selected) {\n          case str.REPORT_ISSUE:\n            const issue = `Sign in with ${service} failed: ${errorMsg}`;\n            IssueReporter.openNewIssue(issue, issue);\n        }\n      });\n  }\n\n  parseQuery(queryString: string): any {\n    // From https://stackoverflow.com/a/13419367\n    const filtered =\n      queryString[0] === \"?\" ? queryString.substr(1) : queryString;\n    const pairs = filtered.split(\"&\");\n    var query: { [key: string]: string } = {};\n\n    for (var i = 0; i < pairs.length; i++) {\n      var pair = pairs[i].split(\"=\");\n      const key: string = decodeURIComponent(pair[0]);\n      const value: string = decodeURIComponent(pair[1] || \"\");\n      query[key] = value;\n    }\n\n    return query;\n  }\n}\n"
  },
  {
    "path": "src/utils/index.ts",
    "content": "import * as vscode from \"vscode\";\nimport * as os from \"os\";\nimport {\n  VSCodeCommands,\n  EXTENSION_ID,\n  VSLS_EXTENSION_PACK_ID,\n  VSLS_EXTENSION_ID,\n  VSLS_SPACES_EXTENSION_ID\n} from \"../constants\";\n\nexport const openUrl = (url: string) => {\n  const parsedUrl = vscode.Uri.parse(url);\n  return vscode.commands.executeCommand(VSCodeCommands.OPEN, parsedUrl);\n};\n\nexport const openSettings = () => {\n  vscode.commands.executeCommand(VSCodeCommands.OPEN_SETTINGS);\n};\n\nexport const setVsContext = (name: string, value: boolean) => {\n  return vscode.commands.executeCommand(\"setContext\", name, value);\n};\n\nexport const getExtension = (\n  extensionId: string\n): vscode.Extension<any> | undefined => {\n  return vscode.extensions.getExtension(extensionId);\n};\n\nexport interface Versions {\n  os: string;\n  extension: string;\n  editor: string;\n}\n\nexport const getExtensionVersion = (): string => {\n  const extension = getExtension(EXTENSION_ID);\n  return !!extension ? extension.packageJSON.version : undefined;\n};\n\nexport const getVersions = (): Versions => {\n  return {\n    os: `${os.type()} ${os.arch()} ${os.release()}`,\n    extension: getExtensionVersion(),\n    editor: vscode.version\n  };\n};\n\nexport const hasVslsExtensionPack = (): boolean => {\n  return !!getExtension(VSLS_EXTENSION_PACK_ID);\n};\n\nexport const hasVslsExtension = (): boolean => {\n  return !!getExtension(VSLS_EXTENSION_ID);\n};\n\nexport const hasVslsSpacesExtension = (): boolean => {\n  return !!getExtension(VSLS_SPACES_EXTENSION_ID);\n}\n\nexport const sanitiseTokenString = (token: string) => {\n  const trimmed = token.trim();\n  const sansQuotes = trimmed.replace(/['\"]+/g, \"\");\n  return sansQuotes;\n};\n\nexport function uuidv4(): string {\n  return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, function(c) {\n    var r = (Math.random() * 16) | 0,\n      v = c === \"x\" ? r : (r & 0x3) | 0x8;\n    return v.toString(16);\n  });\n}\n\nexport function isSuperset(set: Set<any>, subset: Set<any>): boolean {\n  for (var elem of subset) {\n    if (!set.has(elem)) {\n      return false;\n    }\n  }\n  return true;\n}\n\nexport function difference(setA: Set<any>, setB: Set<any>) {\n  var _difference = new Set(setA);\n  for (var elem of setB) {\n    _difference.delete(elem);\n  }\n  return _difference;\n}\n\nexport function equals(setA: Set<any>, setB: Set<any>) {\n  if (setA.size !== setB.size) {\n    return false;\n  }\n\n  for (var a of setA) {\n    if (!setB.has(a)) {\n      return false;\n    }\n  }\n\n  return true;\n}\n\n// User-defined type guard\n// https://github.com/Microsoft/TypeScript/issues/20707#issuecomment-351874491\nexport function notUndefined<T>(x: T | undefined): x is T {\n  return x !== undefined;\n}\n\nexport function toTitleCase(str: string) {\n  return str.replace(/\\w\\S*/g, function(txt) {\n    return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();\n  });\n}\n\nexport function toDateString(date: Date) {\n  // Returns ISO-format date string for a given date\n  let month = (date.getMonth() + 1).toString();\n  let day = date.getDate().toString();\n\n  if (month.length === 1) {\n    month = `0${month}`;\n  }\n\n  if (day.length === 1) {\n    day = `0${day}`;\n  }\n\n  return `${date.getFullYear()}-${month}-${day}`;\n}\n\nexport function camelCaseToTitle(text: string) {\n  var result = text.replace(/([A-Z])/g, \" $1\");\n  return result.charAt(0).toUpperCase() + result.slice(1);\n}\n\nexport function titleCaseToCamel(text: string) {\n  var result = text.replace(/ /g, \"\");\n  return result.charAt(0).toLowerCase() + result.slice(1);\n}\n"
  },
  {
    "path": "src/utils/keychain.ts",
    "content": "// From https://github.com/Microsoft/vscode-pull-request-github/blob/master/src/common/keychain.ts\nimport * as vscode from \"vscode\";\n\n// keytar depends on a native module shipped in vscode, so this is\n// how we load it\nimport * as keytarType from \"keytar\";\n\nfunction getNodeModule<T>(moduleName: string): T | undefined {\n  const vscodeRequire = eval(\"require\");\n\n  try {\n    return vscodeRequire(\n      `${vscode.env.appRoot}/node_modules.asar/${moduleName}`\n    );\n  } catch (err) {\n    // Not in ASAR.\n  }\n\n  try {\n    return vscodeRequire(`${vscode.env.appRoot}/node_modules/${moduleName}`);\n  } catch (err) {\n    // Not available.\n  }\n\n  return undefined;\n}\n\nexport const keychain = getNodeModule<typeof keytarType>(\"keytar\");\n"
  },
  {
    "path": "src/vslsSpaces/gravatar-api.d.ts",
    "content": "// foo.d.ts\ndeclare module \"gravatar-api\";\n"
  },
  {
    "path": "src/vslsSpaces/index.ts",
    "content": "import * as vscode from \"vscode\";\nimport * as gravatar from \"gravatar-api\";\nimport { VSLS_SPACES_EXTENSION_ID, SelfCommands } from \"../constants\";\nimport { getExtension } from \"../utils\";\n\ninterface IMessage {\n    type: string;\n    content: string;\n    timestamp: string;\n    sender: string;\n}\n\ninterface IUser {\n    name: string;\n    email: string;\n}\n\nconst toMessage = (msg: IMessage) => ({\n    timestamp: (Date.parse(msg.timestamp) / 1000.0).toString(),\n    userId: msg.sender,\n    text: msg.type === \"info_message\" ? `_${msg.content}_` : msg.content,\n    content: undefined,\n    reactions: [],\n    replies: {}\n});\n\nfunction sleep(ms: number) {\n    return new Promise(resolve => setTimeout(resolve, ms));\n}\n\nexport class VslsSpacesProvider implements IChatProvider {\n    isListenerSetup: boolean = false;\n    currentUser: IUser | undefined;\n\n    constructor() {\n        // Waiting for the extension to get activated\n        setTimeout(() => {\n            this.setupListeners();\n        }, 5000);\n    }\n\n    setupListeners() {\n        const extension = getExtension(VSLS_SPACES_EXTENSION_ID);\n\n        if (extension && extension.isActive) {\n            const exports = extension.exports;\n            exports.setMessageCallback((data: any) => {\n                this.onNewMessage(data);\n            });\n            exports.setSpaceCallback((name: string) => {\n                this.onNewSpace(name);\n            });\n            exports.setClearMessagesCallback((name: string) => {\n                this.onClearMessages(name);\n            });\n            exports.setUserChangedCallback(({ name, email }: IUser) => {\n                this.connect();\n            });\n\n            this.isListenerSetup = true;\n        }\n    }\n\n    async getApi() {\n        let extension = getExtension(VSLS_SPACES_EXTENSION_ID)!;\n\n        if (extension.isActive) {\n            if (!this.isListenerSetup) {\n                this.setupListeners();\n            }\n\n            return extension.exports;\n        } else {\n            await sleep(5000); // Give 5 secs for extension to activate\n\n            extension = getExtension(VSLS_SPACES_EXTENSION_ID)!;\n            return extension.exports;\n        }\n    }\n\n    async connect(): Promise<CurrentUser | undefined> {\n        const api = await this.getApi();\n\n        if (api) {\n            const userInfo: IUser | undefined = api.getUserInfo();\n\n            if (userInfo) {\n                const { name, email } = userInfo;\n                this.currentUser = userInfo;\n                return {\n                    id: email,\n                    name,\n                    teams: [],\n                    currentTeamId: undefined,\n                    provider: Providers.vslsSpaces\n                };\n            }\n        }\n    }\n\n    onNewMessage(data: any) {\n        const { name, messages } = data;\n        const chatMessages: Message[] = messages.map(toMessage);\n        let channelMessages: ChannelMessages = {};\n        chatMessages.forEach(msg => {\n            channelMessages[msg.timestamp] = msg;\n        });\n        vscode.commands.executeCommand(SelfCommands.UPDATE_MESSAGES, {\n            channelId: name,\n            messages: channelMessages,\n            provider: \"vslsSpaces\"\n        });\n    }\n\n    onNewSpace(spaceName: string) {\n        vscode.commands.executeCommand(SelfCommands.VSLS_SPACE_JOINED, {\n            name: spaceName\n        });\n    }\n\n    onClearMessages(spaceName: string) {\n        vscode.commands.executeCommand(SelfCommands.CLEAR_MESSAGES, {\n            channelId: spaceName,\n            provider: \"vslsSpaces\"\n        });\n    }\n\n    isConnected(): boolean {\n        return !!this.currentUser;\n    }\n\n    async sendMessage(text: string, currentUserId: string, channelId: string) {\n        const api = await this.getApi();\n        api.sendMessage(channelId, text);\n    }\n\n    async fetchUsers(): Promise<Users> {\n        const api = await this.getApi();\n        const users: User[] = api.getUsers().map(({ name, email }: any) => {\n            const avatar = gravatar.imageUrl({\n                email,\n                parameters: { size: \"200\", d: \"retro\" },\n                secure: true\n            });\n            return {\n                id: email,\n                name,\n                email,\n                fullName: name,\n                imageUrl: avatar,\n                smallImageUrl: avatar,\n                presence: UserPresence.available\n            };\n        });\n        let usersToSend: Users = {};\n        users.forEach(u => {\n            usersToSend[u.id] = u;\n        });\n        return usersToSend;\n    }\n\n    async fetchUserInfo(userId: string): Promise<User | undefined> {\n        const users = await this.fetchUsers();\n        return users[userId];\n    }\n\n    async fetchChannels(users: Users): Promise<Channel[]> {\n        const api = await this.getApi();\n        const spaces = api.getSpaces();\n        const channels: Channel[] = spaces.map((name: string) => ({\n            id: name,\n            name,\n            type: ChannelType.channel,\n            readTimestamp: undefined,\n            unreadCount: 0\n        }));\n        return channels;\n    }\n\n    async loadChannelHistory(channelId: string) {\n        const api = await this.getApi();\n        const messages: IMessage[] = await api.getChannelHistory(channelId);\n        const chatMessages: Message[] = messages.map(toMessage);\n        let channelMessages: ChannelMessages = {};\n        chatMessages.forEach(msg => {\n            channelMessages[msg.timestamp] = msg;\n        });\n        return channelMessages;\n    }\n\n    subscribePresence(users: Users) {}\n\n    getUserPreferences(): Promise<UserPreferences> {\n        return Promise.resolve({});\n    }\n\n    async validateToken(): Promise<CurrentUser | undefined> {\n        return;\n    }\n\n    async fetchChannelInfo(channel: Channel): Promise<Channel | undefined> {\n        return undefined;\n    }\n\n    async markChannel(\n        channel: Channel,\n        ts: string\n    ): Promise<Channel | undefined> {\n        return undefined;\n    }\n\n    async fetchThreadReplies(\n        channelId: string,\n        ts: string\n    ): Promise<Message | undefined> {\n        return undefined;\n    }\n\n    async sendThreadReply(\n        text: string,\n        currentUserId: string,\n        channelId: string,\n        parentTimestamp: string\n    ) {}\n\n    async updateSelfPresence(\n        presence: UserPresence,\n        durationInMinutes: number\n    ) {\n        return undefined;\n    }\n\n    async createIMChannel(user: User): Promise<Channel | undefined> {\n        return undefined;\n    }\n\n    async destroy() {}\n\n    async sendTyping(currentUserId: string, channelId: string) { }\n}\n"
  },
  {
    "path": "src/webview/index.ts",
    "content": "import * as vscode from \"vscode\";\nimport * as path from \"path\";\nimport { toDateString } from \"../utils\";\n\nconst SAME_GROUP_TIME = 5 * 60; // seconds\n\ninterface MessageWithUnread extends Message {\n  isUnread: boolean;\n}\n\nexport default class WebviewContainer {\n  panel: vscode.WebviewPanel;\n\n  constructor(\n    extensionPath: string,\n    private onDidDispose: () => void,\n    private onDidChangeViewState: (isVisible: Boolean) => void\n  ) {\n    const baseVuePath = path.join(extensionPath, \"static\");\n    const staticPath = vscode.Uri.file(baseVuePath).with({\n      scheme: \"vscode-resource\"\n    });\n\n    this.panel = vscode.window.createWebviewPanel(\n      \"chatPanel\",\n      \"Chat\",\n      vscode.ViewColumn.Beside,\n      {\n        enableScripts: true,\n        retainContextWhenHidden: true,\n        localResourceRoots: [vscode.Uri.file(baseVuePath)]\n      }\n    );\n\n    this.panel.webview.html = getWebviewContent(staticPath.toString());\n\n    // Handle on did dispose for webview panel\n    this.panel.onDidDispose(() => this.onDidDispose());\n\n    // Handle tab switching event\n    this.panel.onDidChangeViewState(event => {\n      const { visible } = event.webviewPanel;\n      this.onDidChangeViewState(visible);\n    });\n  }\n\n  setMessageHandler(msgHandler: (message: ExtensionMessage) => void) {\n    this.panel.webview.onDidReceiveMessage((message: ExtensionMessage) =>\n      msgHandler(message)\n    );\n  }\n\n  update(uiMessage: UIMessage) {\n    const { messages, users, channel, currentUser } = uiMessage;\n    const annotated = this.getAnnotatedMessages(messages, channel, currentUser);\n    const groups = this.getMessageGroups(annotated, users);\n    this.panel.webview.postMessage({ ...uiMessage, messages: groups });\n    this.panel.title = !!channel ? channel.name : \"\";\n  }\n\n  reveal() {\n    this.panel.reveal();\n  }\n\n  getAnnotatedMessages(\n    messages: ChannelMessages,\n    channel: Channel,\n    currentUser: CurrentUser\n  ): ChannelMessages {\n    if (!!channel) {\n      // Annotates every message with isUnread (boolean)\n      const { readTimestamp } = channel;\n      let result: { [ts: string]: MessageWithUnread } = {};\n\n      Object.keys(messages).forEach(ts => {\n        const message = messages[ts];\n        const isDifferentUser = message.userId !== currentUser.id;\n        const isUnread =\n          !!readTimestamp && isDifferentUser && +ts > +readTimestamp;\n\n        result[ts] = { ...message, isUnread };\n      });\n      return result;\n    } else {\n      return messages;\n    }\n  }\n\n  getMessageGroups(input: ChannelMessages, users: Users): UIMessageDateGroup[] {\n    let result: { [date: string]: ChannelMessages } = {};\n\n    Object.keys(input).forEach(ts => {\n      const date = new Date(+ts * 1000);\n      const dateStr = toDateString(date);\n      if (!(dateStr in result)) {\n        result[dateStr] = {};\n      }\n      result[dateStr][ts] = input[ts];\n    });\n\n    return Object.keys(result)\n      .sort((a, b) => a.localeCompare(b))\n      .map(date => {\n        const messages = result[date];\n        const groups = this.getMessageGroupsForDate(messages, users);\n        return {\n          groups,\n          date\n        };\n      });\n  }\n\n  getMessageGroupsForDate(\n    input: ChannelMessages,\n    users: Users\n  ): UIMessageGroup[] {\n    const timestamps = Object.keys(input).sort((a, b) => +a - +b); // ascending\n\n    const initial = {\n      current: {},\n      groups: []\n    };\n\n    const result = timestamps.reduce((accumulator: any, ts) => {\n      const { current, groups } = accumulator;\n      const message = input[ts];\n      const isSameUser = current.userId\n        ? message.userId === current.userId\n        : false;\n      const isSameTime = current.ts\n        ? +ts - +current.ts < SAME_GROUP_TIME\n        : false;\n\n      if (isSameUser && isSameTime) {\n        return {\n          groups,\n          current: {\n            ...current,\n            ts,\n            messages: [...current.messages, message]\n          }\n        };\n      } else {\n        const currentGroup = {\n          messages: [message],\n          userId: message.userId,\n          user: users[message.userId],\n          minTimestamp: ts,\n          ts,\n          key: ts\n        };\n        return {\n          groups: current.ts ? [...groups, current] : [...groups],\n          current: currentGroup\n        };\n      }\n    }, initial);\n\n    const { current, groups } = result;\n    return current.ts ? [...groups, current] : groups;\n  }\n\n  isVisible() {\n    return this.panel.visible;\n  }\n}\n\nfunction getWebviewContent(staticPath: string) {\n  return `<!DOCTYPE html>\n  <html lang=\"en\">\n  <head>\n      <meta charset=\"UTF-8\">\n      <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n      <meta http-equiv=\"Content-Security-Policy\" \n        content=\"default-src * vscode-resource: https: 'unsafe-inline' 'unsafe-eval';\n        script-src vscode-resource: blob: data: https: 'unsafe-inline' 'unsafe-eval';\n        style-src vscode-resource: https: 'unsafe-inline';\n        img-src vscode-resource: data: https:;\n        connect-src vscode-resource: blob: data: https: http:;\">\n      <title>Chat</title>\n\n      <link href=\"${staticPath}/css/app.css\" rel=\"preload\" as=\"style\">\n      <link href=\"${staticPath}/js/chunk-vendors.js\" rel=\"preload\" as=\"script\">\n      <link href=\"${staticPath}/js/app.js\" rel=\"preload\" as=\"script\">\n      <link href=\"${staticPath}/css/app.css\" rel=\"stylesheet\">\n  </head>\n  <body>\n      <div id=\"app\"> </div>\n      <script src=\"${staticPath}/js/chunk-vendors.js\"> </script>\n      <script src=\"${staticPath}/js/app.js\"> </script>\n  </body>\n  </html>`;\n}\n"
  },
  {
    "path": "tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"module\": \"commonjs\",\n    \"target\": \"es2017\",\n    \"outDir\": \"out\",\n    \"lib\": [\"es6\", \"esnext\"],\n    \"sourceMap\": true,\n    \"rootDir\": \"src\",\n\n    /* Strict Type-Checking Option */\n    \"strict\": true,\n    /* Added to compile vsls contact protocol */\n    \"experimentalDecorators\": true,\n    \"strictPropertyInitialization\": false\n  },\n  \"exclude\": [\n    \"node_modules\",\n    \".vscode-test\",\n    \"out/**\",\n    \"static\",\n    \"scripts\",\n    \"oauth-service\"\n  ]\n}\n"
  },
  {
    "path": "tslint.json",
    "content": "{\n  \"rules\": {\n    \"no-string-throw\": true,\n    \"no-unused-expression\": true,\n    \"no-duplicate-variable\": true,\n    \"curly\": true,\n    \"class-name\": true,\n    \"triple-equals\": true\n  },\n  \"defaultSeverity\": \"warning\"\n}\n"
  },
  {
    "path": "webpack.config.js",
    "content": "//@ts-check\nconst path = require(\"path\");\nconst webpack = require(\"webpack\");\n\n/** @type webpack.Configuration */\n\nconst config = {\n  entry: \"./src/extension.ts\",\n  mode: \"production\",\n  devtool: \"source-map\",\n  target: \"node\",\n  module: {\n    rules: [\n      {\n        test: /\\.ts$/,\n        use: \"ts-loader\"\n      }\n    ]\n  },\n  resolve: {\n    extensions: [\".ts\", \".js\", \".json\"]\n  },\n  output: {\n    filename: \"extension.js\",\n    path: path.resolve(__dirname, \"out\"),\n    libraryTarget: \"commonjs2\"\n  },\n  externals: {\n    vscode: \"commonjs vscode\"\n  }\n};\n\nmodule.exports = config;\n"
  },
  {
    "path": "webview/.gitignore",
    "content": ".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-error.log*\n\n# Editor directories and files\n.idea\n.vscode\n*.suo\n*.ntvs*\n*.njsproj\n*.sln\n*.sw?\n"
  },
  {
    "path": "webview/README.md",
    "content": "# 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\n```\n\nThis can be also be triggered from the root directory -- and this needs to be done everytime the webview is changed.\n\n```\nnpm run webview\n```\n"
  },
  {
    "path": "webview/babel.config.js",
    "content": "module.exports = {\n    presets: [\n        '@vue/app'\n    ]\n}\n"
  },
  {
    "path": "webview/package.json",
    "content": "{\n  \"name\": \"webview\",\n  \"version\": \"0.1.0\",\n  \"private\": true,\n  \"scripts\": {\n    \"serve\": \"vue-cli-service serve\",\n    \"build\": \"vue-cli-service build\",\n    \"lint\": \"vue-cli-service lint\"\n  },\n  \"dependencies\": {\n    \"core-js\": \"^2.6.5\",\n    \"markdown-it\": \"^10.0.0\",\n    \"markdown-it-slack\": \"^1.2.0\",\n    \"tributejs\": \"^3.7.3\",\n    \"vue\": \"^2.6.10\",\n    \"vue-tribute\": \"^1.0.3\"\n  },\n  \"devDependencies\": {\n    \"@vue/cli-plugin-babel\": \"^3.11.0\",\n    \"@vue/cli-plugin-eslint\": \"^3.11.0\",\n    \"@vue/cli-service\": \"^3.11.0\",\n    \"babel-eslint\": \"^10.0.1\",\n    \"eslint\": \"^5.16.0\",\n    \"eslint-plugin-vue\": \"^5.0.0\",\n    \"vue-template-compiler\": \"^2.6.10\"\n  },\n  \"eslintConfig\": {\n    \"root\": true,\n    \"env\": {\n      \"node\": true\n    },\n    \"extends\": [\n      \"plugin:vue/essential\",\n      \"eslint:recommended\"\n    ],\n    \"rules\": {\n      \"no-console\": \"off\",\n      \"no-unused-vars\": \"off\"\n    },\n    \"parserOptions\": {\n      \"parser\": \"babel-eslint\"\n    }\n  },\n  \"postcss\": {\n    \"plugins\": {\n      \"autoprefixer\": {}\n    }\n  },\n  \"browserslist\": [\n    \"> 1%\",\n    \"last 2 versions\"\n  ]\n}\n"
  },
  {
    "path": "webview/src/App.vue",
    "content": "<template>\n    <div id=\"app\" v-bind:style=\"cssProps\">\n        <div class=\"vue-container\">\n            <messages-section\n                v-bind:messages=\"messages\"\n                v-bind:users=\"users\">\n            </messages-section>\n\n            <form-section\n                ref=\"formSection\"\n                v-bind:channel=\"channel\"\n                v-bind:users=\"users\"\n                v-bind:atMentions=\"atMentions\"\n                v-bind:status=\"statusText\">\n            </form-section>\n        </div>\n    </div>\n</template>\n\n<script>\nimport Vue from 'vue';\nimport MessagesSection from './components/MessagesSection.vue';\nimport FormSection from './components/FormSection.vue'\n\nexport default {\n    name: 'app',\n    props: ['data'],\n    components: {\n        MessagesSection,\n        FormSection\n    },\n    computed: {\n        messages: function() { return this.data ? this.data.messages : []; },\n        users: function() { return this.data ? this.data.users : {}; },\n        channel: function() { return this.data ? this.data.channel : {} },\n        statusText: function() { return this.data ? this.data.statusText : ``; },\n        atMentions: function() { return this.data ? this.data.atMentions : []; },\n        cssProps() {\n            return {\n                '--chat-code-font-family': this.data ? this.data.fontFamily : `monospace`,\n                '--chat-font-size': this.data ? `${this.data.fontSize}px` : `12px`\n            }\n        }\n    },\n}\n</script>\n\n<style>\nhtml,\nbody,\n#app {\n    height: 100%;\n    font-size: var(--chat-font-size);\n}\n\ncode {\n    font-family: var(--chat-code-font-family);\n}\n\n.vue-container {\n    display: flex;\n    flex-direction: column;\n    justify-content: flex-end;\n    height: 100%;\n    overflow: hidden;\n}\n\n.messages-section {\n    overflow: auto;\n}\n\n.date-heading {\n    color: var(--vscode-sideBar-foreground);\n    font-weight: normal;\n}\n\n.timestamp {\n    color: var(--vscode-sideBar-foreground);\n}\n\n.message-group {\n    display: flex;\n    margin: 10px 1px;\n}\n\n.message-group-image {\n    width: 36px;\n    height: 36px;\n    margin: 5px 10px 5px 0;\n    flex-shrink: 0;\n}\n\n.message-group-image img {\n    min-width: 100%;\n    min-height: 100%;\n    border-radius: 2px;\n}\n\n.message-group-content {\n    width: 100%;\n}\n\n.message-list {\n    list-style: none;\n    padding: 0;\n    margin: 5px 0;\n}\n\n.message-list li {\n    margin: 3px 0;\n    word-break: break-word;\n}\n\n/* Reactions */\nul.message-reactions {\n    list-style: none;\n    padding-left: 0;\n}\n\nul.message-reactions li {\n    display: inline-block;\n    font-size: smaller;\n    padding: 2px 5px;\n    margin-right: 4px;\n    background-color: var(--vscode-input-background);\n    border-radius: 3px;\n    border: 1px solid var(--vscode-sideBar-background);\n}\n\nul.message-reactions li div {\n    display: inline-block;\n}\n\nul.message-reactions li div:first-child {\n    margin-right: 3px;\n}\n\n/* Form section styles */\n.form-section {\n    margin-bottom: 10px;\n}\n\n.status-text {\n    font-size: x-small;\n    padding-top: 2px;\n}\n\n.status-text:empty::after {\n    /* We want to set a min-height, but the font-size is variable */\n    /* Source: https://stackoverflow.com/a/33298969 */\n    content: \".\";\n    visibility: hidden;\n}\n\n/* At mentions styles */\ndiv.at-mentions {\n    background: red;\n}\n\n/* Message content styles */\ndiv.msg-author {\n    margin: 3px 0;\n}\n\ndiv.msg-title {\n    margin: 3px 0;\n    font-weight: bold;\n}\n\ndiv.msg-author img {\n    max-width: 18px;\n    max-height: 18px;\n    display: inline-block;\n    vertical-align: middle;\n}\n\ndiv.msg-author span {\n    display: inline-block;\n    vertical-align: middle;\n}\n\ndiv.msg-footer {\n    margin-top: 5px;\n    font-size: x-small;\n}\n\ndiv.msg-title a,\ndiv.msg-footer a {\n    text-decoration: none;\n}\n\ndiv.msg-title a:hover,\ndiv.msg-footer a:hover {\n    text-decoration: underline;\n}\n\n/* Markdown styles */\n.message-list li p {\n    -webkit-margin-after: 0;\n    -webkit-margin-before: 0;\n    line-height: 1.5;\n}\n\n.message-list li div.md {\n    display: inline;\n}\n\n.message-list li code {\n    background-color: var(--vscode-editor-selectionHighlightBackground);\n    color: var(--vscode-editor-foreground);\n}\n\n.message-list li pre {\n    padding: 3px;\n    background-color: var(--vscode-editor-selectionHighlightBackground);\n    border-radius: 2px;\n}\n\n.message-list li pre code {\n    background-color: transparent;\n    white-space: pre-wrap;\n}\n\n.message-list li span.edited {\n    font-size: x-small;\n    color: var(--vscode-scrollbarSlider-activeBackground);\n}\n\n.message-list li div.li-line {\n    margin: 7px 0;\n    border-left: 3px solid white;\n    padding-left: 7px;\n}\n\n/* Thread replies */\n.replies-container {\n    margin: 7px 0;\n    padding: 4px;\n    min-height: 27px;\n    background-color: var(--vscode-editor-selectionHighlightBackground);\n}\n\n.replies-summary {\n    display: flex;\n    align-items: center;\n}\n\n.replies-summary div {\n    margin-right: 5px;\n}\n\n.reply-image {\n    margin: 0 3px;\n}\n\nul.replies {\n    margin: 5px 0;\n}\n\nul.replies li {\n    list-style: none;\n    margin: 7px 0;\n}\n\n.unread {\n    border-right: 3px solid var(--vscode-gitDecoration-modifiedResourceForeground);\n    padding-right: 5px;\n}\n\n.pointer {\n    cursor: pointer;\n}\n</style>\n"
  },
  {
    "path": "webview/src/components/DateSeparator.vue",
    "content": "<template>\n    <h3 class=\"date-heading\">{{dateString}}</h3>\n</template>\n\n<script>\nexport default {\n    name: 'date-separator',\n    props: [\"date\"],\n    computed: {\n        dateString: function() {\n            const options = { weekday: \"long\", month: \"long\", day: \"numeric\", timeZone: \"UTC\" };\n            return new Date(this.date).toLocaleDateString(\"en-US\", options);\n        }\n    },\n}\n</script>\n"
  },
  {
    "path": "webview/src/components/FormSection.vue",
    "content": "<template>\n    <div class=\"form-section\">\n        <div>\n            <message-input\n                v-bind:onSubmit=\"onSubmit\"\n                v-bind:users=\"users\"\n                v-bind:placeholderText=\"placeholder\">\n            </message-input>\n            <status-text v-bind:status=\"status\"></status-text>\n        </div>\n    </div>\n</template>\n\n<script>\nimport Vue from 'vue';\nimport StatusText from './StatusText.vue'\nimport MessageInput from './MessageInput.vue'\nimport { sendMessage } from '../utils';\n\nexport default {\n    name: 'form-section',\n    props: ['channel', 'users', 'status', 'atMentions'],\n    components: {\n        StatusText, MessageInput\n    },\n    computed: {\n        placeholder: function() {\n            return `Message ${this.channel ? this.channel.name : \"\"}`;\n        }\n    },\n    methods: {\n        onSubmit: function(text) {\n            const type = text.startsWith(\"/\") ? \"command\" : \"text\";\n            sendMessage(text, type);\n        }\n    },\n    mounted() {\n        return sendMessage(\"is_ready\", \"internal\");\n    }\n}\n</script>\n"
  },
  {
    "path": "webview/src/components/MarkdownElement.vue",
    "content": "<template>\n    <div\n        v-if=\"html\"\n        v-bind:style=\"inlineStyleObject\"\n        v-html=\"html\">\n    </div>\n</template>\n\n<script>\nimport * as MarkdownIt from \"markdown-it\";\nimport * as MarkdownItSlack from \"markdown-it-slack\";\n\nfunction getAttachmentLink(name, permalink) {\n    return `[${name}](${permalink})`;\n};\n\nexport default {\n    name: 'markdown-element',\n    props: ['text', 'inline'],\n    computed: {\n        html: function() {\n            const md = new MarkdownIt({ breaks: true }).use(MarkdownItSlack);\n            return this.inline ? md.renderInline(this.text) : md.render(this.text);\n        },\n        inlineStyleObject: function() {\n            return { display: this.inline ? 'inline' : 'block' }\n        }\n    }\n}\n</script>\n"
  },
  {
    "path": "webview/src/components/MessageAuthor.vue",
    "content": "<template>\n    <div class=\"msg-author\">\n        <img v-bind:src=\"content.authorIcon\" />\n        <span>{{ content.author }}</span>\n    </div>\n</template>\n\n<script>\nexport default {\n    name: 'message-author',\n    props: ['content']\n}\n</script>\n"
  },
  {
    "path": "webview/src/components/MessageContent.vue",
    "content": "<template>\n    <div class=\"li-line\" v-bind:style=\"{ borderColor: borderColor }\">\n        <div v-if=\"content.pretext\">{{ content.pretext }} </div>\n        <message-author v-if=\"content.author\" v-bind:content=\"content\"></message-author>\n        <message-title v-if=\"content.title\" v-bind:content=\"content\"></message-title>\n        <markdown-element\n            v-if=\"content.text\"\n            v-bind:text=\"content.text\"\n            v-bind:inline=\"false\">\n        </markdown-element>\n        <markdown-element\n            v-if=\"content.footer\"\n            v-bind:text=\"content.footer\"\n            v-bind:inline=\"true\">\n        </markdown-element>\n    </div>\n</template>\n\n<script>\nimport MessageTitle from './MessageTitle.vue';\nimport MessageAuthor from './MessageAuthor.vue';\nimport MarkdownElement from './MarkdownElement';\n\nexport default {\n    name: 'message-content',\n    props: ['content'],\n    computed: {\n        borderColor: function() {\n            const { borderColor } = this.content;\n            const defaultColor = `var(--vscode-scrollbarSlider-activeBackground)`;\n            return borderColor ? `#${borderColor}` : defaultColor;\n        }\n    },\n    components: {\n        MessageTitle,\n        MessageAuthor,\n        MarkdownElement\n    }\n}\n</script>"
  },
  {
    "path": "webview/src/components/MessageGroup.vue",
    "content": "<template>\n    <div class=\"message-group\">\n        <div class=\"message-group-image\">\n            <img v-bind:src=\"user ? user.imageUrl : null\" />\n        </div>\n        <div class=\"message-group-content\">\n            <div>\n                <strong>{{ userName }}</strong>\n                &nbsp;\n                <span class=\"timestamp\">{{ readableTimestamp }}</span>\n            </div>\n            \n            <ul class=\"message-list\">\n                <message-item\n                    v-for=\"message in messages\"\n                    v-bind:key=\"message.timestamp\"\n                    v-bind:message=\"message\"\n                    v-bind:users=\"users\">\n                </message-item>\n            </ul>\n        </div>\n    </div>\n</template>\n\n<script>\nimport MessageItem from './MessageItem.vue'\nimport { formattedTime } from '../utils';\n\nexport default {\n    name: 'message-group',\n    props: [\"messages\", \"users\", \"userId\", \"user\", \"timestamp\"],\n    computed: {\n        readableTimestamp: function() {\n            return formattedTime(this.timestamp);\n        },\n        userName: function() {\n            return this.user ? this.user.name : this.userId;\n        }\n    },\n    components: {\n        MessageItem\n    }\n}\n</script>"
  },
  {
    "path": "webview/src/components/MessageInput.vue",
    "content": "<template>\n    <vue-tribute :options=\"tributeOptions\">\n        <p\n            ref=\"messageInput\"\n            class=\"editable\"\n            contenteditable\n            v-bind:data-ph=\"placeholderText\"\n            v-on:keydown.exact=\"onKeydown\"\n            v-on:focus=\"onFocus\"\n            v-focus\n            @input=\"onInput\"\n            @tribute-replaced=\"onTributeReplaced\">\n        </p>\n    </vue-tribute>\n</template>\n\n<script>\nimport Vue from 'vue';\nimport VueTribute from 'vue-tribute';\nimport { sendMessage } from '../utils';\n\nexport default {\n    name: 'message-input',\n    props: ['placeholderText', 'users', 'onSubmit'],\n    components: {\n        VueTribute\n    },\n    watch: {\n        users: function(newUsers, oldUsers) {\n            if (Object.keys(newUsers).length !== Object.keys(oldUsers).length) {\n                setTimeout(() => {\n                    // We need an async update here to avoid an error, and I don't know why.\n                    // https://github.com/syropian/vue-tribute/blob/0f98b64386452b6ecd87898143197f38dd72ac43/dist/vue-tribute.js#L189\n                    this.tributeOptions.values = Object.values(newUsers).map(user => {\n                        // {key: 'Gordon Ramsey', value: 'gramsey'}\n                        return { key: user.name, value: user.name }\n                    })\n                }, 200)\n            }\n        }\n    },\n    data: function() {\n        return {\n            text: \"\",\n            inComposition: false,\n            sendTypingEvents: true,\n            tributeOptions: {\n                values: [],\n                selectTemplate: function(item) {\n                    return `<span class=\"at-mention\" contenteditable=\"false\">@${item.original.value}</span>`;\n                }\n            }\n        };\n    },\n    mounted() {\n        this.$refs.messageInput.addEventListener(\"compositionstart\", event => {\n            this.inComposition = true;\n        });\n        this.$refs.messageInput.addEventListener(\"compositionend\", event => {\n            this.inComposition = false;\n        });\n    },\n    methods: {\n        onSubmitFunc: function(event) {\n            this.onSubmit(this.text);\n            this.clearInput();\n        },\n        onFocus: function(event) {\n            return sendMessage(\"is_focused\", \"internal\");\n        },\n        onKeydown: function(event) {\n            if (event.code === \"Enter\" && !event.shiftKey && !this.inComposition) {\n                event.preventDefault(); // Don't create a new line\n\n                if (this.text) {\n                    this.onSubmitFunc();\n                }\n            } else {\n                if (this.sendTypingEvents) {\n                    this.sendTypingEvents = false;\n                    sendMessage(\"is_typing\", \"internal\"); // Typing indicator\n                    setTimeout(() => {\n                        // This timeout value should be slightly lower\n                        // than the value used to timeout inside SHOW_TYPING command\n                        // so that we don't have a situation where a small gap in typing speed\n                        // causes the status text to flicker.\n                        this.sendTypingEvents = true;\n                    }, 300);\n                }\n            }\n        },\n        clearInput: function() {\n            this.text = '';\n            this.$refs.messageInput.innerHTML = '';\n        },\n        onInput: function(event) {\n            this.text = event.target.innerText;\n            // TODO: To support at-mentions completely, we should use innerHTML\n            // instead of innerText. To be able to support that, the \"message\" text\n            // field needs to support HTML.\n        },\n        onTributeReplaced: function(event) {\n            // Called when something is selected from the at-mentions list\n            console.log('replaced', event.detail)\n        }\n    }\n}\n\nVue.directive(\"focus\", {\n    // When the bound element is inserted into the DOM...\n    inserted: function(el) {\n        el.focus();\n    }\n});\n</script>\n\n<style>\n.tribute-container ul {\n    list-style: none;\n    padding-left: 0;\n    color: var(--vscode-input-foreground);\n    background-color: var(--vscode-input-background);\n    max-height: 200px;\n    overflow: auto;\n}\n\n.tribute-container ul li {\n    padding: 5px;\n}\n\n.tribute-container ul li.highlight {\n    background-color: var(--vscode-button-background);\n    color: var(--vscode-button-foreground);\n}\n\nspan.at-mention {\n    color: var(--vscode-textLink-foreground);\n}\n\np.editable {\n    width: 100%;\n    padding: 7px;\n    font-size: inherit;\n    font-family: inherit;\n    border-radius: 0;\n    box-sizing: border-box;\n    resize: none;\n    color: var(--vscode-input-foreground);\n    background-color: var(--vscode-input-background);\n    border: 1px solid var(--vscode-sideBar-background);\n}\n\n/* Disable blue border around the contenteditable field */\np.editable:focus {\n    outline: 0px solid transparent;\n    border: 1px solid var(--vscode-focusBorder);\n}\n\n/* Enable placeholder on contenteditable */\np.editable:empty:not(:focus):before{\n  content:attr(data-ph);\n  color: var(--vscode-descriptionForeground);\n}\n</style>\n"
  },
  {
    "path": "webview/src/components/MessageItem.vue",
    "content": "<template>\n    <li v-bind:class=\"{ unread: message.isUnread }\">\n        <markdown-element\n            v-bind:inline=\"false\"\n            v-bind:text=\"message.text\">\n        </markdown-element>\n        <span v-if=\"message.isEdited\" class=\"edited\">(edited)</span>\n        <message-reactions v-bind:reactions=\"message.reactions\"></message-reactions>\n        <message-content\n            v-if=\"message.content\" v-bind:content=\"message.content\">\n        </message-content>\n        <message-replies\n            v-if=\"hasReplies\" v-bind:message=\"message\" v-bind:users=\"users\">\n        </message-replies>\n    </li>\n</template>\n\n<script>\nimport MessageContent from './MessageContent.vue'\nimport MessageReactions from './MessageReactions.vue'\nimport MessageReplies from './MessageReplies.vue'\nimport MarkdownElement from './MarkdownElement.vue'\n\nexport default {\n    name: 'message-item',\n    props: ['message', 'users'],\n    computed: {\n        hasReplies: function() {\n            return Object.keys(this.message.replies).length > 0;\n        }\n    },\n    components: {\n        MessageContent,\n        MessageReplies,\n        MessageReactions,\n        MarkdownElement\n    }\n}\n</script>\n"
  },
  {
    "path": "webview/src/components/MessageReaction.vue",
    "content": "<template>\n    <li>\n        <div>{{emoji}}</div>\n        <div>{{count}}</div>\n    </li>\n</template>\n\n<script>\nexport default {\n    name: 'message-reaction',\n    props: ['emoji', 'count', 'users']\n}\n</script>"
  },
  {
    "path": "webview/src/components/MessageReactions.vue",
    "content": "<template>\n    <ul class=\"message-reactions\">\n        <message-reaction v-for=\"reaction in reactions\"\n            v-bind:emoji=\"reaction.name\"\n            v-bind:count=\"reaction.count\"\n            v-bind:users=\"reaction.userIds\"\n            v-bind:key=\"reaction.name\">\n        </message-reaction>\n    </ul>\n</template>\n\n<script>\nimport MessageReaction from './MessageReaction.vue'\n\nexport default {\n    name: 'message-reactions',\n    props: ['reactions'],\n    components: {\n        MessageReaction\n    }\n}\n</script>"
  },
  {
    "path": "webview/src/components/MessageReplies.vue",
    "content": "<template>\n    <div class=\"replies-container\">\n        <div class=\"replies-summary\">\n            <message-replies-images v-bind:images=\"imageUrls\"></message-replies-images>\n            <div>{{count}} replies</div>\n            <div><a class=\"pointer\" v-on:click=\"expandHandler\">{{expandText}}</a></div>\n        </div>\n        <ul v-if=\"isExpanded\" class=\"replies\">\n            <message-reply-item\n                v-for=\"reply in message.replies\"\n                v-bind:key=\"reply.timestamp\"\n                v-bind:users=\"users\"\n                v-bind:userId=\"reply.userId\"\n                v-bind:timestamp=\"reply.timestamp\"\n                v-bind:text=\"reply.text\">\n            </message-reply-item>\n        </ul>\n        <message-input\n            v-if=\"isExpanded\"\n            v-bind:placeholder=\"placeholder\"\n            v-bind:users=\"users\"\n            v-bind:onSubmit=\"onSubmit\"\n            ref=\"threadFormSection\">\n        </message-input>\n    </div>\n</template>\n\n<script>\nimport { vscode, sendMessage } from '../utils.js'\nimport MessageInput from './MessageInput.vue'\nimport MessageRepliesImages from './MessageRepliesImages.vue'\nimport MessageReplyItem from './MessageReplyItem.vue'\n\nexport default {\n    name: 'message-replies',\n    props: ['message', 'users'],\n    components: {\n        MessageRepliesImages,\n        MessageReplyItem,\n        MessageInput\n    },\n    data: function() {\n        return {\n            isExpanded: false\n        };\n    },\n    methods: {\n        expandHandler: function(event) {\n            this.isExpanded = !this.isExpanded;\n\n            if (this.isExpanded) {\n                const hasPendingText =\n                Object.keys(this.message.replies).filter(ts => !this.message.replies[ts].text).length > 0;\n\n                if (hasPendingText) {\n                    vscode.postMessage({\n                        type: \"internal\",\n                        text: \"fetch_replies\",\n                        parentTimestamp: this.message.timestamp\n                    });\n                }\n            }\n        },\n        onSubmit: function(text) {\n            const payload = { text, parentTimestamp: this.message.timestamp };\n            sendMessage(payload, \"thread_reply\");\n        }\n    },\n    computed: {\n        imageUrls: function() {\n            const userIds = Object.keys(this.message.replies).map(\n                replyTs => this.message.replies[replyTs].userId\n            );\n            const uniques = userIds.filter(\n                (item, pos) => userIds.indexOf(item) == pos\n            );\n            return uniques\n            .filter(userId => userId in this.users)\n            .filter(userId => this.users[userId].smallImageUrl)\n            .map(userId => this.users[userId].smallImageUrl);\n        },\n        placeholder: function() {\n            return \"Reply to thread\";\n        },\n        count: function() {\n            return Object.keys(this.message.replies).length;\n        },\n        expandText: function() {\n            return this.isExpanded ? \"Show less\" : \"Show all\";\n        }\n    },\n}\n</script>\n\n<style>\n.replies-container p.editable {\n    margin: 5px 0;\n    padding-left: 40px;\n}\n</style>"
  },
  {
    "path": "webview/src/components/MessageRepliesImages.vue",
    "content": "<template>\n    <div class=\"reply-images-container\">\n        <img v-for=\"url in images\" v-bind:src=\"url\" :key=\"url\" class=\"reply-image\" />\n    </div>\n</template>\n\n<script>\nexport default {\n    name: 'message-replies-images',\n    props: [\"images\"],\n}\n</script>\n"
  },
  {
    "path": "webview/src/components/MessageReplyItem.vue",
    "content": "<template>\n    <li>\n        <span>\n            <strong>{{username}}</strong>\n            &nbsp;\n            <span class=\"timestamp\">{{ readableTimestamp }}:</span>\n        </span>\n        &nbsp;\n        <markdown-element\n            v-if=\"text\"\n            v-bind:text=\"text\"\n            v-bind:inline=\"true\">\n        </markdown-element>\n    </li>\n</template>\n\n<script>\nimport MarkdownElement from './MarkdownElement'\nimport { formattedTime } from '../utils';\n\nexport default {\n    name: 'message-reply-item',\n    props: ['userId', 'timestamp', 'text', 'users'],\n    components: {\n        MarkdownElement\n    },\n    computed: {\n        username: function() {\n            const user = this.users[this.userId];\n            return user ? user.name : this.userId;\n        },\n        readableTimestamp: function() {\n            return formattedTime(this.timestamp);\n        }\n    },\n}\n</script>\n"
  },
  {
    "path": "webview/src/components/MessageTitle.vue",
    "content": "<template>\n    <div class=\"msg-title\">\n        <a\n            v-bind:href=\"content.titleLink\"\n            v-bind:onclick=\"titleOnclick\"\n            v-bind:tabindex=\"-1\">\n        {{ content.title }}\n        </a>\n    </div>\n</template>\n\n<script>\nimport { openLink } from '../utils';\n\nexport default {\n    name: 'message-title',\n    props: ['content'],\n    methods: {\n        titleOnclick: function() {\n            openLink(this.content.titleLink);\n            return false;\n        }\n    },\n}\n</script>\n"
  },
  {
    "path": "webview/src/components/MessagesDateGroup.vue",
    "content": "<template>\n    <div class=\"messages-date-section\">\n        <date-separator v-bind:date=\"date\"></date-separator>\n        <message-group\n            v-for=\"group in groups\"\n            v-bind:key=\"group.key\"\n            v-bind:messages=\"group.messages\"\n            v-bind:users=\"users\"\n            v-bind:userId=\"group.userId\"\n            v-bind:user=\"group.user\"\n            v-bind:timestamp=\"group.minTimestamp\">\n        </message-group>\n    </div>\n</template>\n\n<script>\nimport MessageGroup from \"./MessageGroup.vue\";\nimport DateSeparator from './DateSeparator.vue'\n\nexport default {\n    props: [\"groups\", \"users\", \"date\"],\n    components: {\n        DateSeparator,\n        MessageGroup\n    }    \n}\n</script>"
  },
  {
    "path": "webview/src/components/MessagesSection.vue",
    "content": "<template>\n    <div class=\"messages-section\">\n        <messages-date-group\n            v-for=\"dateGroup in messages\"\n            v-bind:users=\"users\"\n            v-bind:key=\"dateGroup.date\"\n            v-bind:groups=\"dateGroup.groups\"\n            v-bind:date=\"dateGroup.date\">\n        </messages-date-group>\n    </div>\n</template>\n\n<script>\nimport Vue from 'vue';\nimport MessagesDateGroup from './MessagesDateGroup.vue'\nimport { sendMessage } from '../utils';\n\nexport default {\n    name: 'messages-section',\n    props: [\"messages\", \"users\"],\n    components: {\n        MessagesDateGroup\n    },\n    data: function() {\n        return {\n            messagesLength: 0\n        };\n    },\n    updated() {\n        const groups = this.messages.map(dateGroup => dateGroup.groups);\n        const flattened = [].concat.apply([], groups);\n        const newLength = flattened.reduce((acc, currentGroup) => {\n            return acc + currentGroup.messages.length;\n        }, 0);\n        \n        if (newLength !== this.messagesLength) {\n            this.messagesLength = newLength;\n            this.$el.scrollTop = this.$el.scrollHeight;\n        }\n    }\n}\n</script>\n"
  },
  {
    "path": "webview/src/components/StatusText.vue",
    "content": "<template>\n    <div class=\"status-text\">{{ status }}</div>\n</template>\n\n<script>\nexport default {\n    name: 'status-text',\n    props: ['status']\n}\n</script>\n"
  },
  {
    "path": "webview/src/components/UserInfo.vue",
    "content": "<template>\n    <div class=\"user-info\">This is some text in a div.</div>\n</template>\n\n<script>\nexport default {\n    name: 'user-info',\n    props: ['user', 'actions']\n}\n</script>\n\n<style>\n.user-info {\n    width: 100px;\n    height: 100px;\n    background-color: red;\n\n    visibility: hidden;\n    position: absolute;\n    z-index: 1;\n    top: -5px;\n    left: 105%;\n}\n</style>\n"
  },
  {
    "path": "webview/src/main.js",
    "content": "import Vue from 'vue'\nimport App from './App.vue'\n\nvar app = new Vue({\n    template: `<app :data=\"data\"> </app>`,\n    props: ['data'],\n    components: { App },\n    el: '#app',\n})\n\nwindow.addEventListener('message', event => {\n    app.data = event.data;\n})\n"
  },
  {
    "path": "webview/src/utils.js",
    "content": "export const vscode = acquireVsCodeApi();\n\nexport function sendMessage(text, type) {\n    vscode.postMessage({\n        type,\n        text\n    });\n}\n\nexport function formattedTime(ts) {\n    const d = new Date(+ts * 1000);\n    return d.toLocaleTimeString([], { hour: \"2-digit\", minute: \"2-digit\" });\n}\n\nexport function openLink(href) {\n    return sendMessage(href, \"link\");\n}\n"
  },
  {
    "path": "webview/vue.config.js",
    "content": "module.exports = {\n    publicPath: './', // This is required to serve build output w/o an HTTP server\n    runtimeCompiler: true, // This is required to be able to use template tags\n    filenameHashing: false, // Pin names so we can import them easiy\n    outputDir: '../static'\n}\n"
  }
]