[
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.md",
    "content": "---\nname: Bug report\nabout: Create a report about a bug\ntitle: ''\nlabels: bug\nassignees: ''\n\n---\n\n### Describe the bug\n> A clear and concise description of what the bug is.\n\n### Steps to Reproduce\n> Detailed steps to reproduce the problematic behavior:\n\n### Expected behavior\n> A clear and concise description of what you expected to happen.\n\n### Environment:\n- OS/Version: [e.g. iOS/13.3]\n- Starscream Version [e.g. 4.0.4]\n- Xcode version [e.g. 11.5]\n\n### Additional context\n> Add any other context about the problem here.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/config.yml",
    "content": "blank_issues_enabled: false\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.md",
    "content": "---\nname: Feature request\nabout: Suggest an idea for this project\ntitle: ''\nlabels: feature_request\nassignees: ''\n\n---\n\n### What do you want to happen?\n> Please replace this with the general overview of the feature that you'd like to have.  \n\n### What happens now?\n> Please replace this with of what is happening currently.  \n\n### Demo Code\n> Any demo code that may used to implement/use the desired feature. \n\n### Describe alternatives you've considered\n> A clear and concise description of any alternative solutions or features you've considered.\n\n### Additional context\n> Add any other context or screenshots about the feature request here.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/general-question.md",
    "content": "---\nname: General Question\nabout: 'Ask any question about the framework. '\ntitle: ''\nlabels: question\nassignees: ''\n\n---\n\n### Question\n> A description of what you want to know.\n\n### Environment:\n- OS/Version: [e.g. iOS/13.3]\n- Starscream Version [e.g. 4.0.4]\n- Xcode version [e.g. 11.5]\n"
  },
  {
    "path": ".github/pull_request_template.md",
    "content": "### Issue Link 🔗\n> Please attach the link to an issue if it exists.\n\n### Goals ⚽\n> What you hope to address within this PR.\n\n### Implementation Details 🚧\n> Additional details about the PR. \n"
  },
  {
    "path": ".github/workflows/release.yml",
    "content": "name: Release\n\non:\n  push:\n    tags:\n      - \"*.*.*\"\njobs:\n  release:\n    runs-on: macos-latest\n\n    steps:\n      - uses: actions/checkout@v4\n      - name: Set Latest Tag\n        id: vars\n        run: echo \"tag=$(git describe --tags `git rev-list --tags --max-count=1`)\" >> $GITHUB_OUTPUT\n      - uses: ruby/setup-ruby@v1\n        with:\n          bundler-cache: true # runs 'bundle install' and caches installed gems automatically\n      - run: bundle exec fastlane test\n      - run: bundle exec fastlane release\n        env:\n          GITHUB_TOKEN: ${{ secrets.BOT_GITHUB_TOKEN }}\n          COCOAPODS_TRUNK_TOKEN: ${{ secrets.COCOAPODS_TRUNK_TOKEN }}\n          TAG: ${{ steps.vars.outputs.tag }}\n"
  },
  {
    "path": ".gitignore",
    "content": "# CocoaPods\n#\n# We recommend against adding the Pods directory to your .gitignore. However\n# you should judge for yourself, the pros and cons are mentioned at:\n# http://guides.cocoapods.org/using/using-cocoapods.html#should-i-ignore-the-pods-directory-in-source-control?\n#\n Pods/\n\n# Xcode\n.DS_Store\nbuild\n*.pbxuser\n!default.pbxuser\n*.mode1v3\n!default.mode1v3\n*.mode2v3\n!default.mode2v3\n*.perspectivev3\n!default.perspectivev3\nxcuserdata\nprofile\n*.moved-aside\nDerivedData\n.idea/\n*.hmap\n*.xccheckout\n*.xcodeproj/*.xcworkspace\n\n\n# Created by https://www.gitignore.io/api/swift,swiftpm\n\n### Swift ###\n# Xcode\n#\n# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore\n\n## Build generated\nbuild/\nDerivedData/\n\n## Various settings\n*.pbxuser\n!default.pbxuser\n*.mode1v3\n!default.mode1v3\n*.mode2v3\n!default.mode2v3\n*.perspectivev3\n!default.perspectivev3\nxcuserdata/\n\n## Other\n*.moved-aside\n*.xccheckout\n*.xcscmblueprint\n\n## Obj-C/Swift specific\n*.hmap\n*.ipa\n*.dSYM.zip\n*.dSYM\n\n## Playgrounds\ntimeline.xctimeline\nplayground.xcworkspace\n\n# Swift Package Manager\n#\n# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies.\n# Packages/\n# Package.pins\n# Package.resolved\n.build/\n\n# CocoaPods\n#\n# We recommend against adding the Pods directory to your .gitignore. However\n# you should judge for yourself, the pros and cons are mentioned at:\n# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control\n#\n# Pods/\n#\n# Add this line if you want to avoid checking in source code from the Xcode workspace\n# *.xcworkspace\n\n# Carthage\n#\n# Add this line if you want to avoid checking in source code from Carthage dependencies.\n# Carthage/Checkouts\n\nCarthage/Build\n\n# fastlane\n#\n# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the\n# screenshots whenever they are needed.\n# For more information about the recommended setup visit:\n# https://docs.fastlane.tools/best-practices/source-control/#source-control\n\nfastlane/report.xml\nfastlane/Preview.html\nfastlane/screenshots/**/*.png\nfastlane/test_output\n\n# Code Injection\n#\n# After new code Injection tools there's a generated folder /iOSInjectionProject\n# https://github.com/johnno1962/injectionforxcode\n\niOSInjectionProject/\n\n### SwiftPM ###\nPackages\nxcuserdata\n*.xcodeproj\n\n\n# End of https://www.gitignore.io/api/swift,swiftpm\n"
  },
  {
    "path": ".ruby-version",
    "content": "3.2.2"
  },
  {
    "path": "CHANGELOG.md",
    "content": "# Change Log\nAll notable changes to this project will be documented in this file.\n`Starscream` adheres to [Semantic Versioning](http://semver.org/).\n\n### [4.0.4](https://github.com/daltoniam/Starscream/tree/4.0.4)\n\nBug fixes for 4.0.3.\n\n[#808](https://github.com/daltoniam/Starscream/pull/808)\n[#807](https://github.com/daltoniam/Starscream/pull/807)\n[#799](https://github.com/daltoniam/Starscream/pull/799)\n[#797](https://github.com/daltoniam/Starscream/pull/797)\n[#790](https://github.com/daltoniam/Starscream/pull/790)\n[#788](https://github.com/daltoniam/Starscream/pull/788)\n[#777](https://github.com/daltoniam/Starscream/pull/777)\n[#768](https://github.com/daltoniam/Starscream/pull/768)\n[#766](https://github.com/daltoniam/Starscream/pull/766)\n[#764](https://github.com/daltoniam/Starscream/pull/764)\n\n### [4.0.3](https://github.com/daltoniam/Starscream/tree/4.0.3)\n\nBug fixes for 4.0.2.\n\n[#760](https://github.com/daltoniam/Starscream/issues/760)\n\n### [4.0.2](https://github.com/daltoniam/Starscream/tree/4.0.2)\n\nBug fixes for 4.0.1. Fixed native engine is connected/disconnected. Native engine isn't the default since the API lacks features.\n\n[#697](https://github.com/daltoniam/Starscream/pull/697)\n\n### [4.0.1](https://github.com/daltoniam/Starscream/tree/4.0.1)\n\nBug fixes for 4.0.0. Enabled Native engine now that the API is out of beta and works properly.\n\n[#749](https://github.com/daltoniam/Starscream/pull/749)\n[#755](https://github.com/daltoniam/Starscream/pull/755)\n\n### [4.0.0](https://github.com/daltoniam/Starscream/tree/4.0.0)\n\nMajor API refactor.\n\n### [3.1.1](https://github.com/daltoniam/Starscream/tree/3.1.1)\n\nSmall version number fix for 3.1.0: [#703](https://github.com/daltoniam/Starscream/issues/703)\n\n### [3.1.0](https://github.com/daltoniam/Starscream/tree/3.1.0)\n\n* Swift 5.0 and Xcode 10.2 support\n\n#### [3.0.6](https://github.com/daltoniam/Starscream/tree/3.0.6)\n\n* Swift 4.2 and Xcode 10 support\n* added pongDelegate\n* moved CommonCrypto and zlib dependencies\n* HTTP proxy support\n\n#### [3.0.5](https://github.com/daltoniam/Starscream/tree/3.0.5)\n\nSwift 4.1 support and bug fixes.\n\nPull Requests:\n[#492](https://github.com/daltoniam/Starscream/pull/492)\n[#461](https://github.com/daltoniam/Starscream/pull/461)\n[#476](https://github.com/daltoniam/Starscream/pull/476)\n\nIssues:\n[#494](https://github.com/daltoniam/Starscream/issues/494)\n[#491](https://github.com/daltoniam/Starscream/issues/491)\n[#474](https://github.com/daltoniam/Starscream/issues/474)\n[#471](https://github.com/daltoniam/Starscream/issues/471)\n[#437](https://github.com/daltoniam/Starscream/issues/437)\n[#445](https://github.com/daltoniam/Starscream/issues/445)\n[#466](https://github.com/daltoniam/Starscream/issues/466)\n\n\n#### [3.0.4](https://github.com/daltoniam/Starscream/tree/3.0.4)\n\nImproved error handling. Timeout fix. Small assorted fixes.\n\nPull Requests:\n[#452](https://github.com/daltoniam/Starscream/pull/452)\n[#448](https://github.com/daltoniam/Starscream/pull/448)\n[#444](https://github.com/daltoniam/Starscream/pull/444)\n[#443](https://github.com/daltoniam/Starscream/pull/443)\n\nIssues:\n[#415](https://github.com/daltoniam/Starscream/issues/415)\n[#422](https://github.com/daltoniam/Starscream/issues/422)\n[#429](https://github.com/daltoniam/Starscream/issues/429)\n[#433](https://github.com/daltoniam/Starscream/issues/433)\n[#439](https://github.com/daltoniam/Starscream/issues/439)\n\n#### [3.0.3](https://github.com/daltoniam/Starscream/tree/3.0.3)\n\nAssorted fixes.\n\nPull Requests:\n[#438](https://github.com/daltoniam/Starscream/pull/438)\n[#423](https://github.com/daltoniam/Starscream/pull/423)\n[#420](https://github.com/daltoniam/Starscream/pull/420)\n[#418](https://github.com/daltoniam/Starscream/pull/418)\n[#410](https://github.com/daltoniam/Starscream/pull/410)\n[#405](https://github.com/daltoniam/Starscream/pull/405)\n[#404](https://github.com/daltoniam/Starscream/pull/404)\n[#400](https://github.com/daltoniam/Starscream/pull/400)\n\nIssues:\n[#435](https://github.com/daltoniam/Starscream/issues/435)\n[#431](https://github.com/daltoniam/Starscream/issues/431)\n[#426](https://github.com/daltoniam/Starscream/issues/426)\n[#409](https://github.com/daltoniam/Starscream/issues/409)\n[#408](https://github.com/daltoniam/Starscream/issues/408)\n[#401](https://github.com/daltoniam/Starscream/issues/401)\n[#399](https://github.com/daltoniam/Starscream/issues/399)\n[#378](https://github.com/daltoniam/Starscream/issues/378)\n\n#### [3.0.2](https://github.com/daltoniam/Starscream/tree/3.0.2)\n\nSmall fixes for 3.0.1.\n\n[#394](https://github.com/daltoniam/Starscream/issues/394)\n[#392](https://github.com/daltoniam/Starscream/issues/392)\n[#391](https://github.com/daltoniam/Starscream/issues/391)\n\n#### [3.0.1](https://github.com/daltoniam/Starscream/tree/3.0.1)\n\nSmall fixes for 3.0.0.\n\n[#389](https://github.com/daltoniam/Starscream/issues/389)\n[#354](https://github.com/daltoniam/Starscream/issues/354)\n[#386](https://github.com/daltoniam/Starscream/pull/386)\n[#388](https://github.com/daltoniam/Starscream/pull/388)\n[#390](https://github.com/daltoniam/Starscream/pull/390)\n\n#### [3.0.0](https://github.com/daltoniam/Starscream/tree/3.0.0)\n\nMajor refactor and Swift 4 support. Additions include:\n\n- Watchos support.\n- Linux support.\n- New Stream class to allow custom socket implementations if desired.\n- Protocol added for mocking (dependency injection).\n- Single framework (no more platform suffixes! e.g. StarscreamOSX, StarscreamTVOS, etc).\n\n[#384](https://github.com/daltoniam/Starscream/issues/384)\n[#377](https://github.com/daltoniam/Starscream/pull/377)\n[#374](https://github.com/daltoniam/Starscream/issues/374)\n[#346](https://github.com/daltoniam/Starscream/issues/346)\n[#335](https://github.com/daltoniam/Starscream/issues/335)\n[#311](https://github.com/daltoniam/Starscream/pull/311)\n[#269](https://github.com/daltoniam/Starscream/issues/269)\n\n#### [2.1.1](https://github.com/daltoniam/Starscream/tree/2.1.1)\n\nFixes race condition. Updated to avoid SPM dependencies.\n\n[#370](https://github.com/daltoniam/Starscream/issues/370)\n[#367](https://github.com/daltoniam/Starscream/issues/367)\n[#364](https://github.com/daltoniam/Starscream/pull/364)\n[#357](https://github.com/daltoniam/Starscream/pull/357)\n[#355](https://github.com/daltoniam/Starscream/pull/355)\n\n#### [2.1.0](https://github.com/daltoniam/Starscream/tree/2.1.0)\n\nAdds WebSocket compression. Also adds advance WebSocket delegate for extra control. Bug Fixes.\n\n[#349](https://github.com/daltoniam/Starscream/pull/349)\n[#344](https://github.com/daltoniam/Starscream/pull/344)\n[#339](https://github.com/daltoniam/Starscream/pull/339)\n[#337](https://github.com/daltoniam/Starscream/pull/337)\n[#334](https://github.com/daltoniam/Starscream/issues/334)\n[#333](https://github.com/daltoniam/Starscream/pull/333)\n[#319](https://github.com/daltoniam/Starscream/issues/319)\n[#309](https://github.com/daltoniam/Starscream/issues/309)\n[#329](https://github.com/daltoniam/Starscream/issues/329)\n\n#### [2.0.4](https://github.com/daltoniam/Starscream/tree/2.0.4)\n\nSSL Pinning fix by Giuliano Galea as reported by Lukas Futera of [Centralway](https://www.centralway.com/de/).\nWarning fixes for Swift 3.1\n\n#### [2.0.3](https://github.com/daltoniam/Starscream/tree/2.0.3)\n\n[#302](https://github.com/daltoniam/Starscream/issues/302)\n[#301](https://github.com/daltoniam/Starscream/issues/301)\n[#300](https://github.com/daltoniam/Starscream/issues/300)\n[#296](https://github.com/daltoniam/Starscream/issues/296)\n[#294](https://github.com/daltoniam/Starscream/issues/294)\n[#292](https://github.com/daltoniam/Starscream/issues/292)\n[#289](https://github.com/daltoniam/Starscream/issues/289)\n[#288](https://github.com/daltoniam/Starscream/issues/288)\n\n#### [2.0.2](https://github.com/daltoniam/Starscream/tree/2.0.2)\n\nFix for the Swift Package Manager.\n\nFixed:\n[#277](https://github.com/daltoniam/Starscream/issues/277)\n\n#### [2.0.1](https://github.com/daltoniam/Starscream/tree/2.0.1)\n\nBug fixes.\n\nFixed:\n[#261](https://github.com/daltoniam/Starscream/issues/261)\n[#276](https://github.com/daltoniam/Starscream/issues/276)\n[#267](https://github.com/daltoniam/Starscream/issues/267)\n[#266](https://github.com/daltoniam/Starscream/issues/266)\n[#259](https://github.com/daltoniam/Starscream/issues/259)\n\n#### [2.0.0](https://github.com/daltoniam/Starscream/tree/2.0.0)\n\nAdded Swift 3 support.\n\nFixed:\n[#229](https://github.com/daltoniam/Starscream/issues/229)\n[#232](https://github.com/daltoniam/Starscream/issues/232)\n\n#### [1.1.4](https://github.com/daltoniam/Starscream/tree/1.1.4)\n\nSwift 2.3 support.\n\n#### [1.1.3](https://github.com/daltoniam/Starscream/tree/1.1.3)\n\nChanged:\n[#170](https://github.com/daltoniam/Starscream/issues/170)\n[#171](https://github.com/daltoniam/Starscream/issues/171)\n[#174](https://github.com/daltoniam/Starscream/issues/174)\n[#177](https://github.com/daltoniam/Starscream/issues/177)\n[#178](https://github.com/daltoniam/Starscream/issues/178)\n\n#### [1.1.2](https://github.com/daltoniam/Starscream/tree/1.1.2)\n\nFixed:\n[#158](https://github.com/daltoniam/Starscream/issues/158)\n[#161](https://github.com/daltoniam/Starscream/issues/161)\n[#164](https://github.com/daltoniam/Starscream/issues/164)\n\n#### [1.1.1](https://github.com/daltoniam/Starscream/tree/1.1.1)\n\nFixed:\n[#157](https://github.com/daltoniam/Starscream/issues/157)\n\n#### [1.1.0](https://github.com/daltoniam/Starscream/tree/1.1.0)\n\nChanged:\nMoved over to Runloop/default GCD queues to shared queue.\n\nFixed:\n[#153](https://github.com/daltoniam/Starscream/issues/153)\n[#151](https://github.com/daltoniam/Starscream/issues/151)\n[#150](https://github.com/daltoniam/Starscream/issues/150)\n[#149](https://github.com/daltoniam/Starscream/issues/149)\n[#147](https://github.com/daltoniam/Starscream/issues/147)\n[#139](https://github.com/daltoniam/Starscream/issues/139)\n[#77](https://github.com/daltoniam/Starscream/issues/77)\n\n#### [1.0.2](https://github.com/daltoniam/Starscream/tree/1.0.2)\n\nAdded TVOS support.\n\n#### [1.0.1](https://github.com/daltoniam/Starscream/tree/1.0.1)\n\nFixes for #121, #123\n\n#### [1.0.0](https://github.com/daltoniam/Starscream/tree/1.0.0)\n\nfirst release of Swift 2 support.\n"
  },
  {
    "path": "Gemfile",
    "content": "source \"https://rubygems.org\"\n\ngem \"fastlane\"\ngem \"cocoapods\"\n"
  },
  {
    "path": "LICENSE",
    "content": "                              Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   Copyright (c) 2014-2023 Dalton Cherry.\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability."
  },
  {
    "path": "Package.swift",
    "content": "// swift-tools-version:5.3\n\n//\n//  Package.Swift\n//  Starscream\n//\n//  Created by Dalton Cherry on 5/16/15.\n//  Copyright (c) 2014-2016 Dalton Cherry.\n//\n//  Licensed under the Apache License, Version 2.0 (the \"License\");\n//  you may not use this file except in compliance with the License.\n//  You may obtain a copy of the License at\n//\n//  http://www.apache.org/licenses/LICENSE-2.0\n//\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n//\n\nimport PackageDescription\n\nlet package = Package(\n        name: \"Starscream\",\n        products: [\n            .library(name: \"Starscream\", targets: [\"Starscream\"])\n        ],\n        dependencies: [],\n        targets: [\n            .target(name: \"Starscream\",\n                    path: \"Sources\",\n                    resources: [.copy(\"PrivacyInfo.xcprivacy\")])\n        ]\n)\n\n#if os(Linux)\n    package.dependencies.append(.package(url: \"https://github.com/apple/swift-nio-zlib-support.git\", from: \"1.0.0\"))\n#endif\n"
  },
  {
    "path": "README.md",
    "content": "![starscream](https://raw.githubusercontent.com/daltoniam/starscream/assets/starscream.jpg)\n\nStarscream is a conforming WebSocket ([RFC 6455](https://datatracker.ietf.org/doc/html/rfc6455)) library in Swift.\n\n## Features\n\n- Conforms to all of the base [Autobahn test suite](https://crossbar.io/autobahn/).\n- Nonblocking. Everything happens in the background, thanks to GCD.\n- TLS/WSS support.\n- Compression Extensions support ([RFC 7692](https://tools.ietf.org/html/rfc7692))\n\n### Import the framework\n\nFirst thing is to import the framework. See the Installation instructions on how to add the framework to your project.\n\n```swift\nimport Starscream\n```\n\n### Connect to the WebSocket Server\n\nOnce imported, you can open a connection to your WebSocket server. Note that `socket` is probably best as a property, so it doesn't get deallocated right after being setup.\n\n```swift\nvar request = URLRequest(url: URL(string: \"http://localhost:8080\")!)\nrequest.timeoutInterval = 5\nsocket = WebSocket(request: request)\nsocket.delegate = self\nsocket.connect()\n```\n\nAfter you are connected, there is either a delegate or closure you can use for process WebSocket events.\n\n### Receiving data from a WebSocket\n\n`didReceive` receives all the WebSocket events in a single easy to handle enum.\n\n```swift\nfunc didReceive(event: WebSocketEvent, client: WebSocket) {\n\tswitch event {\n\tcase .connected(let headers):\n\t\tisConnected = true\n\t\tprint(\"websocket is connected: \\(headers)\")\n\tcase .disconnected(let reason, let code):\n\t\tisConnected = false\n\t\tprint(\"websocket is disconnected: \\(reason) with code: \\(code)\")\n\tcase .text(let string):\n\t\tprint(\"Received text: \\(string)\")\n\tcase .binary(let data):\n\t\tprint(\"Received data: \\(data.count)\")\n\tcase .ping(_):\n\t\tbreak\n\tcase .pong(_):\n\t\tbreak\n\tcase .viabilityChanged(_):\n\t\tbreak\n\tcase .reconnectSuggested(_):\n\t\tbreak\n\tcase .cancelled:\n\t\tisConnected = false\n\tcase .error(let error):\n\t\tisConnected = false\n\t\thandleError(error)\n        case .peerClosed:\n               break\n\t}\n}\n```\n\nThe closure of this would be:\n\n```swift\nsocket.onEvent = { event in\n\tswitch event {\n\t\t// handle events just like above...\n\t}\n}\n```\n\n### Writing to a WebSocket\n\n### write a binary frame\n\nThe writeData method gives you a simple way to send `Data` (binary) data to the server.\n\n```swift\nsocket.write(data: data) //write some Data over the socket!\n```\n\n### write a string frame\n\nThe writeString method is the same as writeData, but sends text/string.\n\n```swift\nsocket.write(string: \"Hi Server!\") //example on how to write text over the socket!\n```\n\n### write a ping frame\n\nThe writePing method is the same as write, but sends a ping control frame.\n\n```swift\nsocket.write(ping: Data()) //example on how to write a ping control frame over the socket!\n```\n\n### write a pong frame\n\nthe writePong method is the same as writePing, but sends a pong control frame.\n\n```swift\nsocket.write(pong: Data()) //example on how to write a pong control frame over the socket!\n```\n\nStarscream will automatically respond to incoming `ping` control frames so you do not need to manually send `pong`s.\n\nHowever if for some reason you need to control this process you can turn off the automatic `ping` response by disabling `respondToPingWithPong`.\n\n```swift\nsocket.respondToPingWithPong = false //Do not automaticaly respond to incoming pings with pongs.\n```\n\nIn most cases you will not need to do this.\n\n### disconnect\n\nThe disconnect method does what you would expect and closes the socket.\n\n```swift\nsocket.disconnect()\n```\n\nThe disconnect method can also send a custom close code if desired.\n\n```swift\nsocket.disconnect(closeCode: CloseCode.normal.rawValue)\n```\n\n### Custom Headers, Protocols and Timeout\n\nYou can override the default websocket headers, add your own custom ones and set a timeout:\n\n```swift\nvar request = URLRequest(url: URL(string: \"ws://localhost:8080/\")!)\nrequest.timeoutInterval = 5 // Sets the timeout for the connection\nrequest.setValue(\"someother protocols\", forHTTPHeaderField: \"Sec-WebSocket-Protocol\")\nrequest.setValue(\"14\", forHTTPHeaderField: \"Sec-WebSocket-Version\")\nrequest.setValue(\"chat,superchat\", forHTTPHeaderField: \"Sec-WebSocket-Protocol\")\nrequest.setValue(\"Everything is Awesome!\", forHTTPHeaderField: \"My-Awesome-Header\")\nlet socket = WebSocket(request: request)\n```\n\n### SSL Pinning\n\nSSL Pinning is also supported in Starscream.\n\n\nAllow Self-signed certificates:\n\n```swift\nvar request = URLRequest(url: URL(string: \"ws://localhost:8080/\")!)\nlet pinner = FoundationSecurity(allowSelfSigned: true) // don't validate SSL certificates\nlet socket = WebSocket(request: request, certPinner: pinner)\n```\n\nTODO: Update docs on how to load certificates and public keys into an app bundle, use the builtin pinner and TrustKit.\n\n### Compression Extensions\n\nCompression Extensions ([RFC 7692](https://tools.ietf.org/html/rfc7692)) is supported in Starscream.  Compression is enabled by default, however compression will only be used if it is supported by the server as well. You may enable compression by adding a `compressionHandler`:\n\n```swift\nvar request = URLRequest(url: URL(string: \"ws://localhost:8080/\")!)\nlet compression = WSCompression()\nlet socket = WebSocket(request: request, compressionHandler: compression)\n```\n\nCompression should be disabled if your application is transmitting already-compressed, random, or other uncompressable data.\n\n### Custom Queue\n\nA custom queue can be specified when delegate methods are called. By default `DispatchQueue.main` is used, thus making all delegate methods calls run on the main thread. It is important to note that all WebSocket processing is done on a background thread, only the delegate method calls are changed when modifying the queue. The actual processing is always on a background thread and will not pause your app.\n\n```swift\nsocket = WebSocket(url: URL(string: \"ws://localhost:8080/\")!, protocols: [\"chat\",\"superchat\"])\n//create a custom queue\nsocket.callbackQueue = DispatchQueue(label: \"com.vluxe.starscream.myapp\")\n```\n\n## Example Project\n\nCheck out the SimpleTest project in the examples directory to see how to setup a simple connection to a WebSocket server.\n\n## Requirements\n\nStarscream works with iOS 8/10.10 or above for CocoaPods/framework support. To use Starscream with a project targeting iOS 7, you must include all Swift files directly in your project.\n\n## Installation\n\n### Swift Package Manager\n\nThe [Swift Package Manager](https://swift.org/package-manager/) is a tool for automating the distribution of Swift code and is integrated into the `swift` compiler.\n\nOnce you have your Swift package set up, adding Starscream as a dependency is as easy as adding it to the `dependencies` value of your `Package.swift`.\n\n```swift\ndependencies: [\n    .package(url: \"https://github.com/daltoniam/Starscream.git\", from: \"4.0.6\")\n]\n```\n\n### CocoaPods\n\nCheck out [Get Started](http://cocoapods.org/) tab on [cocoapods.org](http://cocoapods.org/).\n\nTo use Starscream in your project add the following 'Podfile' to your project\n\n\tsource 'https://github.com/CocoaPods/Specs.git'\n\tplatform :ios, '12.0'\n\tuse_frameworks!\n\n\tpod 'Starscream', '~> 4.0.6'\n\nThen run:\n\n    pod install\n\n### Carthage\n\nCheck out the [Carthage](https://github.com/Carthage/Carthage) docs on how to add a install. The `Starscream` framework is already setup with shared schemes.\n\n[Carthage Install](https://github.com/Carthage/Carthage#adding-frameworks-to-an-application)\n\nYou can install Carthage with [Homebrew](http://brew.sh/) using the following command:\n\n```bash\n$ brew update\n$ brew install carthage\n```\n\nTo integrate Starscream into your Xcode project using Carthage, specify it in your `Cartfile`:\n\n```\ngithub \"daltoniam/Starscream\" >= 4.0.6\n```\n\n### Other\n\nSimply grab the framework (either via git submodule or another package manager).\n\nAdd the `Starscream.xcodeproj` to your Xcode project. Once that is complete, in your \"Build Phases\" add the `Starscream.framework` to your \"Link Binary with Libraries\" phase.\n\n### Add Copy Frameworks Phase\n\nIf you are running this in an OSX app or on a physical iOS device you will need to make sure you add the `Starscream.framework` to be included in your app bundle. To do this, in Xcode, navigate to the target configuration window by clicking on the blue project icon, and selecting the application target under the \"Targets\" heading in the sidebar. In the tab bar at the top of that window, open the \"Build Phases\" panel. Expand the \"Link Binary with Libraries\" group, and add `Starscream.framework`. Click on the + button at the top left of the panel and select \"New Copy Files Phase\". Rename this new phase to \"Copy Frameworks\", set the \"Destination\" to \"Frameworks\", and add `Starscream.framework` respectively.\n\n## TODOs\n\n- [ ] Proxy support\n- [ ] Thread safe implementation\n- [ ] Better testing/CI\n- [ ] SSL Pinning/client auth examples\n\n## License\n\nStarscream is licensed under the Apache v2 License.\n\n## Contact\n\n### Dalton Cherry\n* https://github.com/daltoniam\n* http://twitter.com/daltoniam\n* http://daltoniam.com\n\n### Austin Cherry ###\n* https://github.com/acmacalister\n* http://twitter.com/acmacalister\n* http://austincherry.me\n"
  },
  {
    "path": "Sources/Compression/Compression.swift",
    "content": "//////////////////////////////////////////////////////////////////////////////////////////////////\n//\n//  Compression.swift\n//  Starscream\n//\n//  Created by Dalton Cherry on 2/4/19.\n//  Copyright © 2019 Vluxe. All rights reserved.\n//\n//  Licensed under the Apache License, Version 2.0 (the \"License\");\n//  you may not use this file except in compliance with the License.\n//  You may obtain a copy of the License at\n//\n//  http://www.apache.org/licenses/LICENSE-2.0\n//\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n//\n//////////////////////////////////////////////////////////////////////////////////////////////////\n\nimport Foundation\n\npublic protocol CompressionHandler {\n    func load(headers: [String: String])\n    func decompress(data: Data, isFinal: Bool) -> Data?\n    func compress(data: Data) -> Data?\n}\n"
  },
  {
    "path": "Sources/Compression/WSCompression.swift",
    "content": "//////////////////////////////////////////////////////////////////////////////////////////////////\n//\n//  WSCompression.swift\n//\n//  Created by Joseph Ross on 7/16/14.\n//  Copyright © 2017 Joseph Ross & Vluxe. All rights reserved.\n//\n//  Licensed under the Apache License, Version 2.0 (the \"License\");\n//  you may not use this file except in compliance with the License.\n//  You may obtain a copy of the License at\n//\n//  http://www.apache.org/licenses/LICENSE-2.0\n//\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n//\n//////////////////////////////////////////////////////////////////////////////////////////////////\n\n//////////////////////////////////////////////////////////////////////////////////////////////////\n//\n//  Compression implementation is implemented in conformance with RFC 7692 Compression Extensions\n//  for WebSocket: https://tools.ietf.org/html/rfc7692\n//\n//////////////////////////////////////////////////////////////////////////////////////////////////\n\nimport Foundation\nimport zlib\n\npublic class WSCompression: CompressionHandler {\n    let headerWSExtensionName = \"Sec-WebSocket-Extensions\"\n    var decompressor: Decompressor?\n    var compressor: Compressor?\n    var decompressorTakeOver = false\n    var compressorTakeOver = false\n    \n    public init() {\n        \n    }\n    \n    public func load(headers: [String: String]) {\n        guard let extensionHeader = headers[headerWSExtensionName] else { return }\n        decompressorTakeOver = false\n        compressorTakeOver = false\n\n        // assume defaults unless the headers say otherwise\n        compressor = Compressor(windowBits: 15)\n        decompressor = Decompressor(windowBits: 15)\n        \n        let parts = extensionHeader.components(separatedBy: \";\")\n        for p in parts {\n            let part = p.trimmingCharacters(in: .whitespaces)\n            if part.hasPrefix(\"server_max_window_bits=\") {\n                let valString = part.components(separatedBy: \"=\")[1]\n                if let val = Int(valString.trimmingCharacters(in: .whitespaces)) {\n                    decompressor = Decompressor(windowBits: val)\n                }\n            } else if part.hasPrefix(\"client_max_window_bits=\") {\n                let valString = part.components(separatedBy: \"=\")[1]\n                if let val = Int(valString.trimmingCharacters(in: .whitespaces)) {\n                    compressor = Compressor(windowBits: val)\n                }\n            } else if part == \"client_no_context_takeover\" {\n                compressorTakeOver = true\n            } else if part == \"server_no_context_takeover\" {\n                decompressorTakeOver = true\n            }\n        }\n    }\n    \n    public func decompress(data: Data, isFinal: Bool) -> Data? {\n        guard let decompressor = decompressor else { return nil }\n        do {\n            let decompressedData = try decompressor.decompress(data, finish: isFinal)\n            if decompressorTakeOver {\n                try decompressor.reset()\n            }\n            return decompressedData\n        } catch {\n            //do nothing with the error for now\n        }\n        return nil\n    }\n    \n    public func compress(data: Data) -> Data? {\n        guard let compressor = compressor else { return nil }\n        do {\n            let compressedData = try compressor.compress(data)\n            if compressorTakeOver {\n                try compressor.reset()\n            }\n            return compressedData\n        } catch {\n            //do nothing with the error for now\n        }\n        return nil\n    }\n    \n\n}\n\nclass Decompressor {\n    private var strm = z_stream()\n    private var buffer = [UInt8](repeating: 0, count: 0x2000)\n    private var inflateInitialized = false\n    private let windowBits: Int\n\n    init?(windowBits: Int) {\n        self.windowBits = windowBits\n        guard initInflate() else { return nil }\n    }\n\n    private func initInflate() -> Bool {\n        if Z_OK == inflateInit2_(&strm, -CInt(windowBits),\n                                 ZLIB_VERSION, CInt(MemoryLayout<z_stream>.size))\n        {\n            inflateInitialized = true\n            return true\n        }\n        return false\n    }\n\n    func reset() throws {\n        teardownInflate()\n        guard initInflate() else { throw WSError(type: .compressionError, message: \"Error for decompressor on reset\", code: 0) }\n    }\n\n    func decompress(_ data: Data, finish: Bool) throws -> Data {\n        return try data.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> Data in\n            return try decompress(bytes: bytes, count: data.count, finish: finish)\n        }\n    }\n\n    func decompress(bytes: UnsafePointer<UInt8>, count: Int, finish: Bool) throws -> Data {\n        var decompressed = Data()\n        try decompress(bytes: bytes, count: count, out: &decompressed)\n\n        if finish {\n            let tail:[UInt8] = [0x00, 0x00, 0xFF, 0xFF]\n            try decompress(bytes: tail, count: tail.count, out: &decompressed)\n        }\n\n        return decompressed\n    }\n\n    private func decompress(bytes: UnsafePointer<UInt8>, count: Int, out: inout Data) throws {\n        var res: CInt = 0\n        strm.next_in = UnsafeMutablePointer<UInt8>(mutating: bytes)\n        strm.avail_in = CUnsignedInt(count)\n\n        repeat {\n            buffer.withUnsafeMutableBytes { (bufferPtr) in\n                strm.next_out = bufferPtr.bindMemory(to: UInt8.self).baseAddress\n                strm.avail_out = CUnsignedInt(bufferPtr.count)\n\n                res = inflate(&strm, 0)\n            }\n\n            let byteCount = buffer.count - Int(strm.avail_out)\n            out.append(buffer, count: byteCount)\n        } while res == Z_OK && strm.avail_out == 0\n\n        guard (res == Z_OK && strm.avail_out > 0)\n            || (res == Z_BUF_ERROR && Int(strm.avail_out) == buffer.count)\n            else {\n                throw WSError(type: .compressionError, message: \"Error on decompressing\", code: 0)\n        }\n    }\n\n    private func teardownInflate() {\n        if inflateInitialized, Z_OK == inflateEnd(&strm) {\n            inflateInitialized = false\n        }\n    }\n\n    deinit {\n        teardownInflate()\n    }\n}\n\nclass Compressor {\n    private var strm = z_stream()\n    private var buffer = [UInt8](repeating: 0, count: 0x2000)\n    private var deflateInitialized = false\n    private let windowBits: Int\n\n    init?(windowBits: Int) {\n        self.windowBits = windowBits\n        guard initDeflate() else { return nil }\n    }\n\n    private func initDeflate() -> Bool {\n        if Z_OK == deflateInit2_(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED,\n                                 -CInt(windowBits), 8, Z_DEFAULT_STRATEGY,\n                                 ZLIB_VERSION, CInt(MemoryLayout<z_stream>.size))\n        {\n            deflateInitialized = true\n            return true\n        }\n        return false\n    }\n\n    func reset() throws {\n        teardownDeflate()\n        guard initDeflate() else { throw WSError(type: .compressionError, message: \"Error for compressor on reset\", code: 0) }\n    }\n\n    func compress(_ data: Data) throws -> Data {\n        guard !data.isEmpty else {\n            // For example, PONG has no content\n            return data\n        }\n\n        var compressed = Data()\n        var res: CInt = 0\n        data.withUnsafeBytes { (ptr:UnsafePointer<UInt8>) -> Void in\n            strm.next_in = UnsafeMutablePointer<UInt8>(mutating: ptr)\n            strm.avail_in = CUnsignedInt(data.count)\n\n            repeat {\n                buffer.withUnsafeMutableBytes { (bufferPtr) in\n                    strm.next_out = bufferPtr.bindMemory(to: UInt8.self).baseAddress\n                    strm.avail_out = CUnsignedInt(bufferPtr.count)\n\n                    res = deflate(&strm, Z_SYNC_FLUSH)\n                }\n\n                let byteCount = buffer.count - Int(strm.avail_out)\n                compressed.append(buffer, count: byteCount)\n            }\n            while res == Z_OK && strm.avail_out == 0\n\n        }\n\n        guard res == Z_OK && strm.avail_out > 0\n            || (res == Z_BUF_ERROR && Int(strm.avail_out) == buffer.count)\n        else {\n            throw WSError(type: .compressionError, message: \"Error on compressing\", code: 0)\n        }\n\n        compressed.removeLast(4)\n        return compressed\n    }\n\n    private func teardownDeflate() {\n        if deflateInitialized, Z_OK == deflateEnd(&strm) {\n            deflateInitialized = false\n        }\n    }\n\n    deinit {\n        teardownDeflate()\n    }\n}\n"
  },
  {
    "path": "Sources/DataBytes/Data+Extensions.swift",
    "content": "//////////////////////////////////////////////////////////////////////////////////////////////////\n//\n//  Data+Extensions.swift\n//  Starscream\n//\n//  Created by Dalton Cherry on 3/27/19.\n//  Copyright © 2019 Vluxe. All rights reserved.\n//\n//  Fix for deprecation warnings\n//\n//  Licensed under the Apache License, Version 2.0 (the \"License\");\n//  you may not use this file except in compliance with the License.\n//  You may obtain a copy of the License at\n//\n//  http://www.apache.org/licenses/LICENSE-2.0\n//\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n//\n//////////////////////////////////////////////////////////////////////////////////////////////////\n\nimport Foundation\n\ninternal extension Data {\n    struct ByteError: Swift.Error {}\n    \n    #if swift(>=5.0)\n    func withUnsafeBytes<ResultType, ContentType>(_ completion: (UnsafePointer<ContentType>) throws -> ResultType) rethrows -> ResultType {\n        return try withUnsafeBytes {\n            if let baseAddress = $0.baseAddress, $0.count > 0 {\n                return try completion(baseAddress.assumingMemoryBound(to: ContentType.self))\n            } else {\n                throw ByteError()\n            }\n        }\n    }\n    #endif\n    \n    #if swift(>=5.0)\n    mutating func withUnsafeMutableBytes<ResultType, ContentType>(_ completion: (UnsafeMutablePointer<ContentType>) throws -> ResultType) rethrows -> ResultType {\n        return try withUnsafeMutableBytes {\n            if let baseAddress = $0.baseAddress, $0.count > 0 {\n                return try completion(baseAddress.assumingMemoryBound(to: ContentType.self))\n            } else {\n                throw ByteError()\n            }\n        }\n    }\n    #endif\n}\n"
  },
  {
    "path": "Sources/Engine/Engine.swift",
    "content": "//////////////////////////////////////////////////////////////////////////////////////////////////\n//\n//  Engine.swift\n//  Starscream\n//\n//  Created by Dalton Cherry on 6/15/19\n//  Copyright © 2019 Vluxe. All rights reserved.\n//\n//  Licensed under the Apache License, Version 2.0 (the \"License\");\n//  you may not use this file except in compliance with the License.\n//  You may obtain a copy of the License at\n//\n//  http://www.apache.org/licenses/LICENSE-2.0\n//\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n//\n//////////////////////////////////////////////////////////////////////////////////////////////////\n\nimport Foundation\n\npublic protocol EngineDelegate: AnyObject {\n    func didReceive(event: WebSocketEvent)\n}\n\npublic protocol Engine {\n    func register(delegate: EngineDelegate)\n    func start(request: URLRequest)\n    func stop(closeCode: UInt16)\n    func forceStop()\n    func write(data: Data, opcode: FrameOpCode, completion: (() -> ())?)\n    func write(string: String, completion: (() -> ())?)\n}\n"
  },
  {
    "path": "Sources/Engine/NativeEngine.swift",
    "content": "//////////////////////////////////////////////////////////////////////////////////////////////////\n//\n//  NativeEngine.swift\n//  Starscream\n//\n//  Created by Dalton Cherry on 6/15/19\n//  Copyright © 2019 Vluxe. All rights reserved.\n//\n//  Licensed under the Apache License, Version 2.0 (the \"License\");\n//  you may not use this file except in compliance with the License.\n//  You may obtain a copy of the License at\n//\n//  http://www.apache.org/licenses/LICENSE-2.0\n//\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n//\n//////////////////////////////////////////////////////////////////////////////////////////////////\n\nimport Foundation\n\n@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)\npublic class NativeEngine: NSObject, Engine, URLSessionDataDelegate, URLSessionWebSocketDelegate {\n    private var task: URLSessionWebSocketTask?\n    weak var delegate: EngineDelegate?\n\n    public func register(delegate: EngineDelegate) {\n        self.delegate = delegate\n    }\n\n    public func start(request: URLRequest) {\n        let session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil)\n        task = session.webSocketTask(with: request)\n        doRead()\n        task?.resume()\n    }\n\n    public func stop(closeCode: UInt16) {\n        let closeCode = URLSessionWebSocketTask.CloseCode(rawValue: Int(closeCode)) ?? .normalClosure\n        task?.cancel(with: closeCode, reason: nil)\n    }\n\n    public func forceStop() {\n        stop(closeCode: UInt16(URLSessionWebSocketTask.CloseCode.abnormalClosure.rawValue))\n    }\n\n    public func write(string: String, completion: (() -> ())?) {\n        task?.send(.string(string), completionHandler: { (error) in\n            completion?()\n        })\n    }\n\n    public func write(data: Data, opcode: FrameOpCode, completion: (() -> ())?) {\n        switch opcode {\n        case .binaryFrame:\n            task?.send(.data(data), completionHandler: { (error) in\n                completion?()\n            })\n        case .textFrame:\n            let text = String(data: data, encoding: .utf8)!\n            write(string: text, completion: completion)\n        case .ping:\n            task?.sendPing(pongReceiveHandler: { (error) in\n                completion?()\n            })\n        default:\n            break //unsupported\n        }\n    }\n\n    private func doRead() {\n        task?.receive { [weak self] (result) in\n            switch result {\n            case .success(let message):\n                switch message {\n                case .string(let string):\n                    self?.broadcast(event: .text(string))\n                case .data(let data):\n                    self?.broadcast(event: .binary(data))\n                @unknown default:\n                    break\n                }\n                break\n            case .failure(let error):\n                self?.broadcast(event: .error(error))\n                return\n            }\n            self?.doRead()\n        }\n    }\n\n    private func broadcast(event: WebSocketEvent) {\n        delegate?.didReceive(event: event)\n    }\n    \n    public func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didOpenWithProtocol protocol: String?) {\n        let p = `protocol` ?? \"\"\n        broadcast(event: .connected([HTTPWSHeader.protocolName: p]))\n    }\n    \n    public func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didCloseWith closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) {\n        var r = \"\"\n        if let d = reason {\n            r = String(data: d, encoding: .utf8) ?? \"\"\n        }\n        broadcast(event: .disconnected(r, UInt16(closeCode.rawValue)))\n    }\n    \n    public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {\n        broadcast(event: .error(error))\n    }\n}\n"
  },
  {
    "path": "Sources/Engine/WSEngine.swift",
    "content": "//////////////////////////////////////////////////////////////////////////////////////////////////\n//\n//  WSEngine.swift\n//  Starscream\n//\n//  Created by Dalton Cherry on 6/15/19\n//  Copyright © 2019 Vluxe. All rights reserved.\n//\n//  Licensed under the Apache License, Version 2.0 (the \"License\");\n//  you may not use this file except in compliance with the License.\n//  You may obtain a copy of the License at\n//\n//  http://www.apache.org/licenses/LICENSE-2.0\n//\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n//\n//////////////////////////////////////////////////////////////////////////////////////////////////\n\nimport Foundation\n\npublic class WSEngine: Engine, TransportEventClient, FramerEventClient,\nFrameCollectorDelegate, HTTPHandlerDelegate {\n    private let transport: Transport\n    private let framer: Framer\n    private let httpHandler: HTTPHandler\n    private let compressionHandler: CompressionHandler?\n    private let certPinner: CertificatePinning?\n    private let headerChecker: HeaderValidator\n    private var request: URLRequest!\n    \n    private let frameHandler = FrameCollector()\n    private var didUpgrade = false\n    private var secKeyValue = \"\"\n    private let writeQueue = DispatchQueue(label: \"com.vluxe.starscream.writequeue\")\n    private let mutex = DispatchSemaphore(value: 1)\n    private var canSend = false\n    private var isConnecting = false\n    \n    weak var delegate: EngineDelegate?\n    public var respondToPingWithPong: Bool = true\n    \n    public init(transport: Transport,\n                certPinner: CertificatePinning? = nil,\n                headerValidator: HeaderValidator = FoundationSecurity(),\n                httpHandler: HTTPHandler = FoundationHTTPHandler(),\n                framer: Framer = WSFramer(),\n                compressionHandler: CompressionHandler? = nil) {\n        self.transport = transport\n        self.framer = framer\n        self.httpHandler = httpHandler\n        self.certPinner = certPinner\n        self.headerChecker = headerValidator\n        self.compressionHandler = compressionHandler\n        framer.updateCompression(supports: compressionHandler != nil)\n        frameHandler.delegate = self\n    }\n    \n    public func register(delegate: EngineDelegate) {\n        self.delegate = delegate\n    }\n    \n    public func start(request: URLRequest) {\n        mutex.wait()\n        let isConnecting = self.isConnecting\n        let isConnected = canSend\n        mutex.signal()\n        if isConnecting || isConnected {\n            return\n        }\n        \n        self.request = request\n        transport.register(delegate: self)\n        framer.register(delegate: self)\n        httpHandler.register(delegate: self)\n        frameHandler.delegate = self\n        guard let url = request.url else {\n            return\n        }\n        mutex.wait()\n        self.isConnecting = true\n        mutex.signal()\n        transport.connect(url: url, timeout: request.timeoutInterval, certificatePinning: certPinner)\n    }\n    \n    public func stop(closeCode: UInt16 = CloseCode.normal.rawValue) {\n        let capacity = MemoryLayout<UInt16>.size\n        var pointer = [UInt8](repeating: 0, count: capacity)\n        writeUint16(&pointer, offset: 0, value: closeCode)\n        let payload = Data(bytes: pointer, count: MemoryLayout<UInt16>.size)\n        write(data: payload, opcode: .connectionClose, completion: { [weak self] in\n            self?.reset()\n            self?.forceStop()\n        })\n    }\n    \n    public func forceStop() {\n        mutex.wait()\n        isConnecting = false\n        mutex.signal()\n        \n        transport.disconnect()\n    }\n    \n    public func write(string: String, completion: (() -> ())?) {\n        let data = string.data(using: .utf8)!\n        write(data: data, opcode: .textFrame, completion: completion)\n    }\n    \n    public func write(data: Data, opcode: FrameOpCode, completion: (() -> ())?) {\n        writeQueue.async { [weak self] in\n            guard let s = self else { return }\n            s.mutex.wait()\n            let canWrite = s.canSend\n            s.mutex.signal()\n            if !canWrite {\n                return\n            }\n            \n            var isCompressed = false\n            var sendData = data\n            if let compressedData = s.compressionHandler?.compress(data: data) {\n                sendData = compressedData\n                isCompressed = true\n            }\n            \n            let frameData = s.framer.createWriteFrame(opcode: opcode, payload: sendData, isCompressed: isCompressed)\n            s.transport.write(data: frameData, completion: {_ in\n                completion?()\n            })\n        }\n    }\n    \n    // MARK: - TransportEventClient\n    \n    public func connectionChanged(state: ConnectionState) {\n        switch state {\n        case .connected:\n            secKeyValue = HTTPWSHeader.generateWebSocketKey()\n            let wsReq = HTTPWSHeader.createUpgrade(request: request, supportsCompression: framer.supportsCompression(), secKeyValue: secKeyValue)\n            let data = httpHandler.convert(request: wsReq)\n            transport.write(data: data, completion: {_ in })\n        case .waiting:\n            break\n        case .failed(let error):\n            handleError(error)\n        case .viability(let isViable):\n            broadcast(event: .viabilityChanged(isViable))\n        case .shouldReconnect(let status):\n            broadcast(event: .reconnectSuggested(status))\n        case .receive(let data):\n            if didUpgrade {\n                framer.add(data: data)\n            } else {\n                let offset = httpHandler.parse(data: data)\n                if offset > 0 {\n                    let extraData = data.subdata(in: offset..<data.endIndex)\n                    framer.add(data: extraData)\n                }\n            }\n        case .cancelled:\n            mutex.wait()\n            isConnecting = false\n            mutex.signal()\n            \n            broadcast(event: .cancelled)\n        case .peerClosed:\n            broadcast(event: .peerClosed)\n        }\n    }\n    \n    // MARK: - HTTPHandlerDelegate\n    \n    public func didReceiveHTTP(event: HTTPEvent) {\n        switch event {\n        case .success(let headers):\n            if let error = headerChecker.validate(headers: headers, key: secKeyValue) {\n                handleError(error)\n                return\n            }\n            mutex.wait()\n            isConnecting = false\n            didUpgrade = true\n            canSend = true\n            mutex.signal()\n            compressionHandler?.load(headers: headers)\n            if let url = request.url {\n                HTTPCookie.cookies(withResponseHeaderFields: headers, for: url).forEach {\n                    HTTPCookieStorage.shared.setCookie($0)\n                }\n            }\n\n            broadcast(event: .connected(headers))\n        case .failure(let error):\n            handleError(error)\n        }\n    }\n    \n    // MARK: - FramerEventClient\n    \n    public func frameProcessed(event: FrameEvent) {\n        switch event {\n        case .frame(let frame):\n            frameHandler.add(frame: frame)\n        case .error(let error):\n            handleError(error)\n        }\n    }\n    \n    // MARK: - FrameCollectorDelegate\n    \n    public func decompress(data: Data, isFinal: Bool) -> Data? {\n        return compressionHandler?.decompress(data: data, isFinal: isFinal)\n    }\n    \n    public func didForm(event: FrameCollector.Event) {\n        switch event {\n        case .text(let string):\n            broadcast(event: .text(string))\n        case .binary(let data):\n            broadcast(event: .binary(data))\n        case .pong(let data):\n            broadcast(event: .pong(data))\n        case .ping(let data):\n            broadcast(event: .ping(data))\n            if respondToPingWithPong {\n                write(data: data ?? Data(), opcode: .pong, completion: nil)\n            }\n        case .closed(let reason, let code):\n            broadcast(event: .disconnected(reason, code))\n            stop(closeCode: code)\n        case .error(let error):\n            handleError(error)\n        }\n    }\n    \n    private func broadcast(event: WebSocketEvent) {\n        delegate?.didReceive(event: event)\n    }\n    \n    //This call can be coming from a lot of different queues/threads.\n    //be aware of that when modifying shared variables\n    private func handleError(_ error: Error?) {\n        if let wsError = error as? WSError {\n            stop(closeCode: wsError.code)\n        } else {\n            stop()\n        }\n        \n        delegate?.didReceive(event: .error(error))\n    }\n    \n    private func reset() {\n        mutex.wait()\n        isConnecting = false\n        canSend = false\n        didUpgrade = false\n        mutex.signal()\n    }\n    \n    \n}\n"
  },
  {
    "path": "Sources/Framer/FoundationHTTPHandler.swift",
    "content": "//////////////////////////////////////////////////////////////////////////////////////////////////\n//\n//  FoundationHTTPHandler.swift\n//  Starscream\n//\n//  Created by Dalton Cherry on 1/25/19.\n//  Copyright © 2019 Vluxe. All rights reserved.\n//\n//  Licensed under the Apache License, Version 2.0 (the \"License\");\n//  you may not use this file except in compliance with the License.\n//  You may obtain a copy of the License at\n//\n//  http://www.apache.org/licenses/LICENSE-2.0\n//\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n//\n//////////////////////////////////////////////////////////////////////////////////////////////////\n\nimport Foundation\n#if os(watchOS)\npublic typealias FoundationHTTPHandler = StringHTTPHandler\n#else\npublic class FoundationHTTPHandler: HTTPHandler {\n\n    var buffer = Data()\n    weak var delegate: HTTPHandlerDelegate?\n    \n    public init() {\n        \n    }\n    \n    public func convert(request: URLRequest) -> Data {\n        let msg = CFHTTPMessageCreateRequest(kCFAllocatorDefault, request.httpMethod! as CFString,\n                                             request.url! as CFURL, kCFHTTPVersion1_1).takeRetainedValue()\n        if let headers = request.allHTTPHeaderFields {\n            for (aKey, aValue) in headers {\n                CFHTTPMessageSetHeaderFieldValue(msg, aKey as CFString, aValue as CFString)\n            }\n        }\n        if let body = request.httpBody {\n            CFHTTPMessageSetBody(msg, body as CFData)\n        }\n        guard let data = CFHTTPMessageCopySerializedMessage(msg) else {\n            return Data()\n        }\n        return data.takeRetainedValue() as Data\n    }\n    \n    public func parse(data: Data) -> Int {\n        let offset = findEndOfHTTP(data: data)\n        if offset > 0 {\n            buffer.append(data.subdata(in: 0..<offset))\n        } else {\n            buffer.append(data)\n        }\n        if parseContent(data: buffer) {\n            buffer = Data()\n        }\n        return offset\n    }\n    \n    //returns true when the buffer should be cleared\n    func parseContent(data: Data) -> Bool {\n        var pointer = [UInt8]()\n        data.withUnsafeBytes { pointer.append(contentsOf: $0) }\n\n        let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, false).takeRetainedValue()\n        if !CFHTTPMessageAppendBytes(response, pointer, data.count) {\n            return false //not enough data, wait for more\n        }\n        if !CFHTTPMessageIsHeaderComplete(response) {\n            return false //not enough data, wait for more\n        }\n        \n        if let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response) {\n            let nsHeaders = cfHeaders.takeRetainedValue() as NSDictionary\n            var headers = [String: String]()\n            for (key, value) in nsHeaders {\n                if let key = key as? String, let value = value as? String {\n                    headers[key] = value\n                }\n            }\n            \n            let code = CFHTTPMessageGetResponseStatusCode(response)\n            if code != HTTPWSHeader.switchProtocolCode {\n                delegate?.didReceiveHTTP(event: .failure(HTTPUpgradeError.notAnUpgrade(code, headers)))\n                return true\n            }\n            \n            delegate?.didReceiveHTTP(event: .success(headers))\n            return true\n        }\n        \n        delegate?.didReceiveHTTP(event: .failure(HTTPUpgradeError.invalidData))\n        return true\n    }\n    \n    public func register(delegate: HTTPHandlerDelegate) {\n        self.delegate = delegate\n    }\n    \n    private func findEndOfHTTP(data: Data) -> Int {\n        let endBytes = [UInt8(ascii: \"\\r\"), UInt8(ascii: \"\\n\"), UInt8(ascii: \"\\r\"), UInt8(ascii: \"\\n\")]\n        var pointer = [UInt8]()\n        data.withUnsafeBytes { pointer.append(contentsOf: $0) }\n        var k = 0\n        for i in 0..<data.count {\n            if pointer[i] == endBytes[k] {\n                k += 1\n                if k == 4 {\n                    return i + 1\n                }\n            } else {\n                k = 0\n            }\n        }\n        return -1\n    }\n}\n#endif\n"
  },
  {
    "path": "Sources/Framer/FoundationHTTPServerHandler.swift",
    "content": "//////////////////////////////////////////////////////////////////////////////////////////////////\n//\n//  FoundationHTTPHandler.swift\n//  Starscream\n//\n//  Created by Dalton Cherry on 4/2/19.\n//  Copyright © 2019 Vluxe. All rights reserved.\n//\n//  Licensed under the Apache License, Version 2.0 (the \"License\");\n//  you may not use this file except in compliance with the License.\n//  You may obtain a copy of the License at\n//\n//  http://www.apache.org/licenses/LICENSE-2.0\n//\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n//\n//////////////////////////////////////////////////////////////////////////////////////////////////\n\nimport Foundation\n\npublic class FoundationHTTPServerHandler: HTTPServerHandler {\n    var buffer = Data()\n    weak var delegate: HTTPServerDelegate?\n    let getVerb: NSString = \"GET\"\n    \n    public func register(delegate: HTTPServerDelegate) {\n        self.delegate = delegate\n    }\n    \n    public func createResponse(headers: [String: String]) -> Data {\n        #if os(watchOS)\n        //TODO: build response header\n        return Data()\n        #else\n        let response = CFHTTPMessageCreateResponse(kCFAllocatorDefault, HTTPWSHeader.switchProtocolCode,\n                                                   nil, kCFHTTPVersion1_1).takeRetainedValue()\n        \n        //TODO: add other values to make a proper response here...\n        //TODO: also sec key thing (Sec-WebSocket-Key)\n        for (key, value) in headers {\n            CFHTTPMessageSetHeaderFieldValue(response, key as CFString, value as CFString)\n        }\n        guard let cfData = CFHTTPMessageCopySerializedMessage(response)?.takeRetainedValue() else {\n            return Data()\n        }\n        return cfData as Data\n        #endif\n    }\n    \n    public func parse(data: Data) {\n        buffer.append(data)\n        if parseContent(data: buffer) {\n            buffer = Data()\n        }\n    }\n    \n    //returns true when the buffer should be cleared\n    func parseContent(data: Data) -> Bool {\n        var pointer = [UInt8]()\n        data.withUnsafeBytes { pointer.append(contentsOf: $0) }\n        #if os(watchOS)\n        //TODO: parse data\n        return false\n        #else\n        let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, true).takeRetainedValue()\n        if !CFHTTPMessageAppendBytes(response, pointer, data.count) {\n            return false //not enough data, wait for more\n        }\n        if !CFHTTPMessageIsHeaderComplete(response) {\n            return false //not enough data, wait for more\n        }\n        if let method = CFHTTPMessageCopyRequestMethod(response)?.takeRetainedValue() {\n            if (method as NSString) != getVerb {\n                delegate?.didReceive(event: .failure(HTTPUpgradeError.invalidData))\n                return true\n            }\n        }\n        \n        if let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response) {\n            let nsHeaders = cfHeaders.takeRetainedValue() as NSDictionary\n            var headers = [String: String]()\n            for (key, value) in nsHeaders {\n                if let key = key as? String, let value = value as? String {\n                    headers[key] = value\n                }\n            }\n            delegate?.didReceive(event: .success(headers))\n            return true\n        }\n        \n        delegate?.didReceive(event: .failure(HTTPUpgradeError.invalidData))\n        return true\n        #endif\n    }\n}\n"
  },
  {
    "path": "Sources/Framer/FrameCollector.swift",
    "content": "//////////////////////////////////////////////////////////////////////////////////////////////////\n//\n//  FrameCollector.swift\n//  Starscream\n//\n//  Created by Dalton Cherry on 1/24/19.\n//  Copyright © 2019 Vluxe. All rights reserved.\n//\n//  Licensed under the Apache License, Version 2.0 (the \"License\");\n//  you may not use this file except in compliance with the License.\n//  You may obtain a copy of the License at\n//\n//  http://www.apache.org/licenses/LICENSE-2.0\n//\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n//\n//////////////////////////////////////////////////////////////////////////////////////////////////\n\nimport Foundation\n\npublic protocol FrameCollectorDelegate: AnyObject {\n    func didForm(event: FrameCollector.Event)\n    func decompress(data: Data, isFinal: Bool) -> Data?\n}\n\npublic class FrameCollector {\n    public enum Event {\n        case text(String)\n        case binary(Data)\n        case pong(Data?)\n        case ping(Data?)\n        case error(Error)\n        case closed(String, UInt16)\n    }\n    weak var delegate: FrameCollectorDelegate?\n    var buffer = Data()\n    var frameCount = 0\n    var isText = false //was the first frame a text frame or a binary frame?\n    var needsDecompression = false\n    \n    public func add(frame: Frame) {\n        //check single frame action and out of order frames\n        if frame.opcode == .connectionClose {\n            var code = frame.closeCode\n            var reason = \"connection closed by server\"\n            if let customCloseReason = String(data: frame.payload, encoding: .utf8) {\n                reason = customCloseReason\n            } else {\n                code = CloseCode.protocolError.rawValue\n            }\n            delegate?.didForm(event: .closed(reason, code))\n            return\n        } else if frame.opcode == .pong {\n            delegate?.didForm(event: .pong(frame.payload))\n            return\n        } else if frame.opcode == .ping {\n            delegate?.didForm(event: .ping(frame.payload))\n            return\n        } else if frame.opcode == .continueFrame && frameCount == 0 {\n            let errCode = CloseCode.protocolError.rawValue\n            delegate?.didForm(event: .error(WSError(type: .protocolError, message: \"first frame can't be a continue frame\", code: errCode)))\n            reset()\n            return\n        } else if frameCount > 0 && frame.opcode != .continueFrame {\n            let errCode = CloseCode.protocolError.rawValue\n            delegate?.didForm(event: .error(WSError(type: .protocolError, message: \"second and beyond of fragment message must be a continue frame\", code: errCode)))\n            reset()\n            return\n        }\n        if frameCount == 0 {\n            isText = frame.opcode == .textFrame\n            needsDecompression = frame.needsDecompression\n        }\n        \n        let payload: Data\n        if needsDecompression {\n            payload = delegate?.decompress(data: frame.payload, isFinal: frame.isFin) ?? frame.payload\n        } else {\n            payload = frame.payload\n        }\n        buffer.append(payload)\n        frameCount += 1\n\n        if frame.isFin {\n            if isText {\n                if let string = String(data: buffer, encoding: .utf8) {\n                    delegate?.didForm(event: .text(string))\n                } else {\n                    let errCode = CloseCode.protocolError.rawValue\n                    delegate?.didForm(event: .error(WSError(type: .protocolError, message: \"not valid UTF-8 data\", code: errCode)))\n                }\n            } else {\n                delegate?.didForm(event: .binary(buffer))\n            }\n            reset()\n        }\n    }\n    \n    func reset() {\n        buffer = Data()\n        frameCount = 0\n    }\n}\n"
  },
  {
    "path": "Sources/Framer/Framer.swift",
    "content": "//////////////////////////////////////////////////////////////////////////////////////////////////\n//\n//  Framer.swift\n//  Starscream\n//\n//  Created by Dalton Cherry on 1/23/19.\n//  Copyright © 2019 Vluxe. All rights reserved.\n//\n//  Licensed under the Apache License, Version 2.0 (the \"License\");\n//  you may not use this file except in compliance with the License.\n//  You may obtain a copy of the License at\n//\n//  http://www.apache.org/licenses/LICENSE-2.0\n//\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n//\n//////////////////////////////////////////////////////////////////////////////////////////////////\n\nimport Foundation\n\nlet FinMask: UInt8          = 0x80\nlet OpCodeMask: UInt8       = 0x0F\nlet RSVMask: UInt8          = 0x70\nlet RSV1Mask: UInt8         = 0x40\nlet MaskMask: UInt8         = 0x80\nlet PayloadLenMask: UInt8   = 0x7F\nlet MaxFrameSize: Int       = 32\n\n// Standard WebSocket close codes\npublic enum CloseCode: UInt16 {\n    case normal                 = 1000\n    case goingAway              = 1001\n    case protocolError          = 1002\n    case protocolUnhandledType  = 1003\n    // 1004 reserved.\n    case noStatusReceived       = 1005\n    //1006 reserved.\n    case encoding               = 1007\n    case policyViolated         = 1008\n    case messageTooBig          = 1009\n}\n\npublic enum FrameOpCode: UInt8 {\n    case continueFrame = 0x0\n    case textFrame = 0x1\n    case binaryFrame = 0x2\n    // 3-7 are reserved.\n    case connectionClose = 0x8\n    case ping = 0x9\n    case pong = 0xA\n    // B-F reserved.\n    case unknown = 100\n}\n\npublic struct Frame {\n    let isFin: Bool\n    let needsDecompression: Bool\n    let isMasked: Bool\n    let opcode: FrameOpCode\n    let payloadLength: UInt64\n    let payload: Data\n    let closeCode: UInt16 //only used by connectionClose opcode\n}\n\npublic enum FrameEvent {\n    case frame(Frame)\n    case error(Error)\n}\n\npublic protocol FramerEventClient: AnyObject {\n    func frameProcessed(event: FrameEvent)\n}\n\npublic protocol Framer {\n    func add(data: Data)\n    func register(delegate: FramerEventClient)\n    func createWriteFrame(opcode: FrameOpCode, payload: Data, isCompressed: Bool) -> Data\n    func updateCompression(supports: Bool)\n    func supportsCompression() -> Bool\n}\n\npublic class WSFramer: Framer {\n    private let queue = DispatchQueue(label: \"com.vluxe.starscream.wsframer\", attributes: [])\n    private weak var delegate: FramerEventClient?\n    private var buffer = Data()\n    public var compressionEnabled = false\n    private let isServer: Bool\n    \n    public init(isServer: Bool = false) {\n        self.isServer = isServer\n    }\n    \n    public func updateCompression(supports: Bool) {\n        compressionEnabled = supports\n    }\n    \n    public func supportsCompression() -> Bool {\n        return compressionEnabled\n    }\n    \n    enum ProcessEvent {\n        case needsMoreData\n        case processedFrame(Frame, Int)\n        case failed(Error)\n    }\n    \n    public func add(data: Data) {\n        queue.async { [weak self] in\n            self?.buffer.append(data)\n            while(true) {\n               let event = self?.process() ?? .needsMoreData\n                switch event {\n                case .needsMoreData:\n                    return\n                case .processedFrame(let frame, let split):\n                    guard let s = self else { return }\n                    s.delegate?.frameProcessed(event: .frame(frame))\n                    if split >= s.buffer.count {\n                        s.buffer = Data()\n                        return\n                    }\n                    s.buffer = s.buffer.advanced(by: split)\n                case .failed(let error):\n                    self?.delegate?.frameProcessed(event: .error(error))\n                    self?.buffer = Data()\n                    return\n                }\n            }\n        }\n    }\n\n    public func register(delegate: FramerEventClient) {\n        self.delegate = delegate\n    }\n    \n    private func process() -> ProcessEvent {\n        if buffer.count < 2 {\n            return .needsMoreData\n        }\n        var pointer = [UInt8]()\n        buffer.withUnsafeBytes { pointer.append(contentsOf: $0) }\n\n        let isFin = (FinMask & pointer[0])\n        let opcodeRawValue = (OpCodeMask & pointer[0])\n        let opcode = FrameOpCode(rawValue: opcodeRawValue) ?? .unknown\n        let isMasked = (MaskMask & pointer[1])\n        let payloadLen = (PayloadLenMask & pointer[1])\n        let RSV1 = (RSVMask & pointer[0])\n        var needsDecompression = false\n        \n        if compressionEnabled && opcode != .continueFrame {\n           needsDecompression = (RSV1Mask & pointer[0]) > 0\n        }\n        if !isServer && (isMasked > 0 || RSV1 > 0) && opcode != .pong && !needsDecompression {\n            let errCode = CloseCode.protocolError.rawValue\n            return .failed(WSError(type: .protocolError, message: \"masked and rsv data is not currently supported\", code: errCode))\n        }\n        let isControlFrame = (opcode == .connectionClose || opcode == .ping || opcode == .pong)\n        if !isControlFrame && (opcode != .binaryFrame && opcode != .continueFrame &&\n            opcode != .textFrame && opcode != .pong) {\n            let errCode = CloseCode.protocolError.rawValue\n            return .failed(WSError(type: .protocolError, message: \"unknown opcode: \\(opcodeRawValue)\", code: errCode))\n        }\n        if isControlFrame && isFin == 0 {\n            let errCode = CloseCode.protocolError.rawValue\n            return .failed(WSError(type: .protocolError, message: \"control frames can't be fragmented\", code: errCode))\n        }\n        \n        var offset = 2\n    \n        if isControlFrame && payloadLen > 125 {\n            return .failed(WSError(type: .protocolError, message: \"payload length is longer than allowed for a control frame\", code: CloseCode.protocolError.rawValue))\n        }\n        \n        var dataLength = UInt64(payloadLen)\n        var closeCode = CloseCode.normal.rawValue\n        if opcode == .connectionClose {\n            if payloadLen == 1 {\n                closeCode = CloseCode.protocolError.rawValue\n                dataLength = 0\n            } else if payloadLen > 1 {\n                if pointer.count < 4 {\n                    return .needsMoreData\n                }\n                let size = MemoryLayout<UInt16>.size\n                closeCode = pointer.readUint16(offset: offset)\n                offset += size\n                dataLength -= UInt64(size)\n                if closeCode < 1000 || (closeCode > 1003 && closeCode < 1007) || (closeCode > 1013 && closeCode < 3000) {\n                    closeCode = CloseCode.protocolError.rawValue\n                }\n            }\n        }\n        \n        if payloadLen == 127 {\n             let size = MemoryLayout<UInt64>.size\n            if size + offset > pointer.count {\n                return .needsMoreData\n            }\n            dataLength = pointer.readUint64(offset: offset)\n            offset += size\n        } else if payloadLen == 126 {\n            let size = MemoryLayout<UInt16>.size\n            if size + offset > pointer.count {\n                return .needsMoreData\n            }\n            dataLength = UInt64(pointer.readUint16(offset: offset))\n            offset += size\n        }\n        \n        let maskStart = offset\n        if isServer {\n            offset += MemoryLayout<UInt32>.size\n        }\n        \n        if dataLength > (pointer.count - offset) {\n            return .needsMoreData\n        }\n        \n        //I don't like this cast, but Data's count returns an Int.\n        //Might be a problem with huge payloads. Need to revisit.\n        let readDataLength = Int(dataLength)\n        \n        let payload: Data\n        if readDataLength == 0 {\n            payload = Data()\n        } else {\n            if isServer {\n                payload = pointer.unmaskData(maskStart: maskStart, offset: offset, length: readDataLength)\n            } else {\n                let end = offset + readDataLength\n                payload = Data(pointer[offset..<end])\n            }\n        }\n        offset += readDataLength\n\n        let frame = Frame(isFin: isFin > 0, needsDecompression: needsDecompression, isMasked: isMasked > 0, opcode: opcode, payloadLength: dataLength, payload: payload, closeCode: closeCode)\n        return .processedFrame(frame, offset)\n    }\n    \n    public func createWriteFrame(opcode: FrameOpCode, payload: Data, isCompressed: Bool) -> Data {\n        let payloadLength = payload.count\n        \n        let capacity = payloadLength + MaxFrameSize\n        var pointer = [UInt8](repeating: 0, count: capacity)\n        \n        //set the framing info\n        pointer[0] = FinMask | opcode.rawValue\n        if isCompressed {\n             pointer[0] |= RSV1Mask\n        }\n        \n        var offset = 2 //skip pass the framing info\n        if payloadLength < 126 {\n            pointer[1] = UInt8(payloadLength)\n        } else if payloadLength <= Int(UInt16.max) {\n            pointer[1] = 126\n            writeUint16(&pointer, offset: offset, value: UInt16(payloadLength))\n            offset += MemoryLayout<UInt16>.size\n        } else {\n            pointer[1] = 127\n            writeUint64(&pointer, offset: offset, value: UInt64(payloadLength))\n            offset += MemoryLayout<UInt64>.size\n        }\n        \n        //clients are required to mask the payload data, but server don't according to the RFC\n        if !isServer {\n            pointer[1] |= MaskMask\n            \n            //write the random mask key in\n            let maskKey: UInt32 = UInt32.random(in: 0...UInt32.max)\n            \n            writeUint32(&pointer, offset: offset, value: maskKey)\n            let maskStart = offset\n            offset += MemoryLayout<UInt32>.size\n            \n            //now write the payload data in\n            for i in 0..<payloadLength {\n                pointer[offset] = payload[i] ^ pointer[maskStart + (i % MemoryLayout<UInt32>.size)]\n                offset += 1\n            }\n        } else {\n            for i in 0..<payloadLength {\n                pointer[offset] = payload[i]\n                offset += 1\n            }\n        }\n        return Data(pointer[0..<offset])\n    }\n}\n\n/// MARK: - functions for simpler array buffer reading and writing\n\npublic protocol MyWSArrayType {}\nextension UInt8: MyWSArrayType {}\n\npublic extension Array where Element: MyWSArrayType & UnsignedInteger {\n    \n    /**\n     Read a UInt16 from a buffer.\n     - parameter offset: is the offset index to start the read from (e.g. buffer[0], buffer[1], etc).\n     - returns: a UInt16 of the value from the buffer\n     */\n    func readUint16(offset: Int) -> UInt16 {\n        return (UInt16(self[offset + 0]) << 8) | UInt16(self[offset + 1])\n    }\n    \n    /**\n     Read a UInt64 from a buffer.\n     - parameter offset: is the offset index to start the read from (e.g. buffer[0], buffer[1], etc).\n     - returns: a UInt64 of the value from the buffer\n     */\n    func readUint64(offset: Int) -> UInt64 {\n        var value = UInt64(0)\n        for i in 0...7 {\n            value = (value << 8) | UInt64(self[offset + i])\n        }\n        return value\n    }\n    \n    func unmaskData(maskStart: Int, offset: Int, length: Int) -> Data {\n        var unmaskedBytes = [UInt8](repeating: 0, count: length)\n        let maskSize = MemoryLayout<UInt32>.size\n        for i in 0..<length {\n            unmaskedBytes[i] = UInt8(self[offset + i] ^ self[maskStart + (i % maskSize)])\n        }\n        return Data(unmaskedBytes)\n    }\n}\n\n/**\n Write a UInt16 to the buffer. It fills the 2 array \"slots\" of the UInt8 array.\n - parameter buffer: is the UInt8 array (pointer) to write the value too.\n - parameter offset: is the offset index to start the write from (e.g. buffer[0], buffer[1], etc).\n */\npublic func writeUint16( _ buffer: inout [UInt8], offset: Int, value: UInt16) {\n    buffer[offset + 0] = UInt8(value >> 8)\n    buffer[offset + 1] = UInt8(value & 0xff)\n}\n\n/**\n Write a UInt32 to the buffer. It fills the 4 array \"slots\" of the UInt8 array.\n - parameter buffer: is the UInt8 array (pointer) to write the value too.\n - parameter offset: is the offset index to start the write from (e.g. buffer[0], buffer[1], etc).\n */\npublic func writeUint32( _ buffer: inout [UInt8], offset: Int, value: UInt32) {\n    for i in 0...3 {\n        buffer[offset + i] = UInt8((value >> (8*UInt32(3 - i))) & 0xff)\n    }\n}\n\n/**\n Write a UInt64 to the buffer. It fills the 8 array \"slots\" of the UInt8 array.\n - parameter buffer: is the UInt8 array (pointer) to write the value too.\n - parameter offset: is the offset index to start the write from (e.g. buffer[0], buffer[1], etc).\n */\npublic func writeUint64( _ buffer: inout [UInt8], offset: Int, value: UInt64) {\n    for i in 0...7 {\n        buffer[offset + i] = UInt8((value >> (8*UInt64(7 - i))) & 0xff)\n    }\n}\n"
  },
  {
    "path": "Sources/Framer/HTTPHandler.swift",
    "content": "//////////////////////////////////////////////////////////////////////////////////////////////////\n//\n//  HTTPHandler.swift\n//  Starscream\n//\n//  Created by Dalton Cherry on 1/24/19.\n//  Copyright © 2019 Vluxe. All rights reserved.\n//\n//  Licensed under the Apache License, Version 2.0 (the \"License\");\n//  you may not use this file except in compliance with the License.\n//  You may obtain a copy of the License at\n//\n//  http://www.apache.org/licenses/LICENSE-2.0\n//\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n//\n//////////////////////////////////////////////////////////////////////////////////////////////////\n\nimport Foundation\n\npublic enum HTTPUpgradeError: Error {\n    case notAnUpgrade(Int, [String: String])\n    case invalidData\n}\n\npublic struct HTTPWSHeader {\n    static let upgradeName        = \"Upgrade\"\n    static let upgradeValue       = \"websocket\"\n    static let hostName           = \"Host\"\n    static let connectionName     = \"Connection\"\n    static let connectionValue    = \"Upgrade\"\n    static let protocolName       = \"Sec-WebSocket-Protocol\"\n    static let versionName        = \"Sec-WebSocket-Version\"\n    static let versionValue       = \"13\"\n    static let extensionName      = \"Sec-WebSocket-Extensions\"\n    static let keyName            = \"Sec-WebSocket-Key\"\n    static let originName         = \"Origin\"\n    static let acceptName         = \"Sec-WebSocket-Accept\"\n    static let switchProtocolCode = 101\n    static let defaultSSLSchemes  = [\"wss\", \"https\"]\n    \n    /// Creates a new URLRequest based off the source URLRequest.\n    /// - Parameter request: the request to \"upgrade\" the WebSocket request by adding headers.\n    /// - Parameter supportsCompression: set if the client support text compression.\n    /// - Parameter secKeyName: the security key to use in the WebSocket request. https://tools.ietf.org/html/rfc6455#section-1.3\n    /// - returns: A URLRequest request to be converted to data and sent to the server.\n    public static func createUpgrade(request: URLRequest, supportsCompression: Bool, secKeyValue: String) -> URLRequest {\n        guard let url = request.url, let parts = url.getParts() else {\n            return request\n        }\n        \n        var req = request\n        if request.value(forHTTPHeaderField: HTTPWSHeader.originName) == nil {\n            var origin = url.absoluteString\n            if let hostUrl = URL (string: \"/\", relativeTo: url) {\n                origin = hostUrl.absoluteString\n                origin.remove(at: origin.index(before: origin.endIndex))\n            }\n            req.setValue(origin, forHTTPHeaderField: HTTPWSHeader.originName)\n        }\n        req.setValue(HTTPWSHeader.upgradeValue, forHTTPHeaderField: HTTPWSHeader.upgradeName)\n        req.setValue(HTTPWSHeader.connectionValue, forHTTPHeaderField: HTTPWSHeader.connectionName)\n        req.setValue(HTTPWSHeader.versionValue, forHTTPHeaderField: HTTPWSHeader.versionName)\n        req.setValue(secKeyValue, forHTTPHeaderField: HTTPWSHeader.keyName)\n        \n\t\tif req.allHTTPHeaderFields?[\"Cookie\"] == nil {\n            if let cookies = HTTPCookieStorage.shared.cookies(for: url), !cookies.isEmpty {\n                let headers = HTTPCookie.requestHeaderFields(with: cookies)\n                for (key, val) in headers {\n                    req.setValue(val, forHTTPHeaderField: key)\n                }\n            }\n\t     }\n        \n        if supportsCompression {\n            let val = \"permessage-deflate; client_max_window_bits; server_max_window_bits=15\"\n            req.setValue(val, forHTTPHeaderField: HTTPWSHeader.extensionName)\n        }\n        let hostValue = req.allHTTPHeaderFields?[HTTPWSHeader.hostName] ?? \"\\(parts.host):\\(parts.port)\"\n        req.setValue(hostValue, forHTTPHeaderField: HTTPWSHeader.hostName)\n        return req\n    }\n    \n    // generateWebSocketKey 16 random characters between a-z and return them as a base64 string\n    public static func generateWebSocketKey() -> String {\n        return Data((0..<16).map{ _ in UInt8.random(in: 97...122) }).base64EncodedString()\n    }\n}\n\npublic enum HTTPEvent {\n    case success([String: String])\n    case failure(Error)\n}\n\npublic protocol HTTPHandlerDelegate: AnyObject {\n    func didReceiveHTTP(event: HTTPEvent)\n}\n\npublic protocol HTTPHandler {\n    func register(delegate: HTTPHandlerDelegate)\n    func convert(request: URLRequest) -> Data\n    func parse(data: Data) -> Int\n}\n\npublic protocol HTTPServerDelegate: AnyObject {\n    func didReceive(event: HTTPEvent)\n}\n\npublic protocol HTTPServerHandler {\n    func register(delegate: HTTPServerDelegate)\n    func parse(data: Data)\n    func createResponse(headers: [String: String]) -> Data\n}\n\npublic struct URLParts {\n    let port: Int\n    let host: String\n    let isTLS: Bool\n}\n\npublic extension URL {\n    /// isTLSScheme returns true if the scheme is https or wss\n    var isTLSScheme: Bool {\n        guard let scheme = self.scheme else {\n            return false\n        }\n        return HTTPWSHeader.defaultSSLSchemes.contains(scheme)\n    }\n    \n    /// getParts pulls host and port from the url.\n    func getParts() -> URLParts? {\n        guard let host = self.host else {\n            return nil // no host, this isn't a valid url\n        }\n        let isTLS = isTLSScheme\n        var port = self.port ?? 0\n        if self.port == nil {\n            if isTLS {\n                port = 443\n            } else {\n                port = 80\n            }\n        }\n        return URLParts(port: port, host: host, isTLS: isTLS)\n    }\n}\n"
  },
  {
    "path": "Sources/Framer/StringHTTPHandler.swift",
    "content": "//////////////////////////////////////////////////////////////////////////////////////////////////\n//\n//  StringHTTPHandler.swift\n//  Starscream\n//\n//  Created by Dalton Cherry on 8/25/19.\n//  Copyright © 2019 Vluxe. All rights reserved.\n//\n//  Licensed under the Apache License, Version 2.0 (the \"License\");\n//  you may not use this file except in compliance with the License.\n//  You may obtain a copy of the License at\n//\n//  http://www.apache.org/licenses/LICENSE-2.0\n//\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n//\n//////////////////////////////////////////////////////////////////////////////////////////////////\n\nimport Foundation\n\npublic class StringHTTPHandler: HTTPHandler {\n    \n    var buffer = Data()\n    weak var delegate: HTTPHandlerDelegate?\n    \n    public init() {\n        \n    }\n    \n    public func convert(request: URLRequest) -> Data {\n        guard let url = request.url else {\n            return Data()\n        }\n        \n        var path = url.absoluteString\n        let offset = (url.scheme?.count ?? 2) + 3\n        path = String(path[path.index(path.startIndex, offsetBy: offset)..<path.endIndex])\n        if let range = path.range(of: \"/\") {\n            path = String(path[range.lowerBound..<path.endIndex])\n        } else {\n            path = \"/\"\n            if let query = url.query {\n                path += \"?\" + query\n            }\n        }\n        \n        var httpBody = \"\\(request.httpMethod ?? \"GET\") \\(path) HTTP/1.1\\r\\n\"\n        if let headers = request.allHTTPHeaderFields {\n            for (key, val) in headers {\n                httpBody += \"\\(key): \\(val)\\r\\n\"\n            }\n        }\n        httpBody += \"\\r\\n\"\n        \n        guard var data = httpBody.data(using: .utf8) else {\n            return Data()\n        }\n        \n        if let body = request.httpBody {\n            data.append(body)\n        }\n        \n        return data\n    }\n    \n    public func parse(data: Data) -> Int {\n        let offset = findEndOfHTTP(data: data)\n        if offset > 0 {\n            buffer.append(data.subdata(in: 0..<offset))\n            if parseContent(data: buffer) {\n                buffer = Data()\n            }\n        } else {\n            buffer.append(data)\n        }\n        return offset\n    }\n    \n    //returns true when the buffer should be cleared\n    func parseContent(data: Data) -> Bool {\n        guard let str = String(data: data, encoding: .utf8) else {\n            delegate?.didReceiveHTTP(event: .failure(HTTPUpgradeError.invalidData))\n            return true\n        }\n        let splitArr = str.components(separatedBy: \"\\r\\n\")\n        var code = -1\n        var i = 0\n        var headers = [String: String]()\n        for str in splitArr {\n            if i == 0 {\n                let responseSplit = str.components(separatedBy: .whitespaces)\n                guard responseSplit.count > 1 else {\n                    delegate?.didReceiveHTTP(event: .failure(HTTPUpgradeError.invalidData))\n                    return true\n                }\n                if let c = Int(responseSplit[1]) {\n                    code = c\n                }\n            } else {\n                guard let separatorIndex = str.firstIndex(of: \":\") else { break }\n                let key = str.prefix(upTo: separatorIndex).trimmingCharacters(in: .whitespaces)\n                let val = str.suffix(from: str.index(after: separatorIndex)).trimmingCharacters(in: .whitespaces)\n                headers[key.lowercased()] = val\n            }\n            i += 1\n        }\n        \n        if code != HTTPWSHeader.switchProtocolCode {\n            delegate?.didReceiveHTTP(event: .failure(HTTPUpgradeError.notAnUpgrade(code, headers)))\n            return true\n        }\n        \n        delegate?.didReceiveHTTP(event: .success(headers))\n        return true\n    }\n    \n    public func register(delegate: HTTPHandlerDelegate) {\n        self.delegate = delegate\n    }\n    \n    private func findEndOfHTTP(data: Data) -> Int {\n        let endBytes = [UInt8(ascii: \"\\r\"), UInt8(ascii: \"\\n\"), UInt8(ascii: \"\\r\"), UInt8(ascii: \"\\n\")]\n        var pointer = [UInt8]()\n        data.withUnsafeBytes { pointer.append(contentsOf: $0) }\n        var k = 0\n        for i in 0..<data.count {\n            if pointer[i] == endBytes[k] {\n                k += 1\n                if k == 4 {\n                    return i + 1\n                }\n            } else {\n                k = 0\n            }\n        }\n        return -1\n    }\n}\n\n"
  },
  {
    "path": "Sources/Info.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>CFBundleDevelopmentRegion</key>\n\t<string>en</string>\n\t<key>CFBundleExecutable</key>\n\t<string>$(EXECUTABLE_NAME)</string>\n\t<key>CFBundleIdentifier</key>\n\t<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>\n\t<key>CFBundleInfoDictionaryVersion</key>\n\t<string>6.0</string>\n\t<key>CFBundleName</key>\n\t<string>$(PRODUCT_NAME)</string>\n\t<key>CFBundlePackageType</key>\n\t<string>FMWK</string>\n\t<key>CFBundleShortVersionString</key>\n\t<string>$(MARKETING_VERSION)</string>\n\t<key>CFBundleSignature</key>\n\t<string>????</string>\n\t<key>CFBundleVersion</key>\n\t<string>$(CURRENT_PROJECT_VERSION)</string>\n\t<key>NSPrincipalClass</key>\n\t<string></string>\n</dict>\n</plist>\n"
  },
  {
    "path": "Sources/PrivacyInfo.xcprivacy",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n    <key>NSPrivacyTracking</key>\n    <false/>\n    <key>NSPrivacyTrackingDomains</key>\n    <array/>\n    <key>NSPrivacyCollectedDataTypes</key>\n    <array/>\n    <key>NSPrivacyAccessedAPITypes</key>\n    <array/>\n</dict>\n</plist>\n"
  },
  {
    "path": "Sources/Security/FoundationSecurity.swift",
    "content": "//////////////////////////////////////////////////////////////////////////////////////////////////\n//\n//  FoundationSecurity.swift\n//  Starscream\n//\n//  Created by Dalton Cherry on 3/16/19.\n//  Copyright © 2019 Vluxe. All rights reserved.\n//\n//  Licensed under the Apache License, Version 2.0 (the \"License\");\n//  you may not use this file except in compliance with the License.\n//  You may obtain a copy of the License at\n//\n//  http://www.apache.org/licenses/LICENSE-2.0\n//\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n//\n//////////////////////////////////////////////////////////////////////////////////////////////////\n\nimport Foundation\nimport CommonCrypto\n\npublic enum FoundationSecurityError: Error {\n    case invalidRequest\n}\n\npublic class FoundationSecurity  {\n    var allowSelfSigned = false\n    \n    public init(allowSelfSigned: Bool = false) {\n        self.allowSelfSigned = allowSelfSigned\n    }\n    \n    \n}\n\nextension FoundationSecurity: CertificatePinning {\n    public func evaluateTrust(trust: SecTrust, domain: String?, completion: ((PinningState) -> ())) {\n        if allowSelfSigned {\n            completion(.success)\n            return\n        }\n        \n        SecTrustSetPolicies(trust, SecPolicyCreateSSL(true, domain as NSString?))\n        \n        handleSecurityTrust(trust: trust, completion: completion)\n    }\n    \n    private func handleSecurityTrust(trust: SecTrust, completion: ((PinningState) -> ())) {\n        if #available(iOS 12.0, OSX 10.14, watchOS 5.0, tvOS 12.0, *) {\n            var error: CFError?\n            if SecTrustEvaluateWithError(trust, &error) {\n                completion(.success)\n            } else {\n                completion(.failed(error))\n            }\n        } else {\n            handleOldSecurityTrust(trust: trust, completion: completion)\n        }\n    }\n    \n    private func handleOldSecurityTrust(trust: SecTrust, completion: ((PinningState) -> ())) {\n        var result: SecTrustResultType = .unspecified\n        SecTrustEvaluate(trust, &result)\n        if result == .unspecified || result == .proceed {\n            completion(.success)\n        } else {\n            let e = CFErrorCreate(kCFAllocatorDefault, \"FoundationSecurityError\" as NSString?, Int(result.rawValue), nil)\n            completion(.failed(e))\n        }\n    }\n}\n\nextension FoundationSecurity: HeaderValidator {\n    public func validate(headers: [String: String], key: String) -> Error? {\n        if let acceptKey = headers[HTTPWSHeader.acceptName] {\n            let sha = \"\\(key)258EAFA5-E914-47DA-95CA-C5AB0DC85B11\".sha1Base64()\n            if sha != acceptKey {\n                return WSError(type: .securityError, message: \"accept header doesn't match\", code: SecurityErrorCode.acceptFailed.rawValue)\n            }\n        }\n        return nil\n    }\n}\n\nprivate extension String {\n    func sha1Base64() -> String {\n        let data = self.data(using: .utf8)!\n        let pointer = data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) -> [UInt8] in\n            var digest = [UInt8](repeating: 0, count:Int(CC_SHA1_DIGEST_LENGTH))\n            CC_SHA1(bytes.baseAddress, CC_LONG(data.count), &digest)\n            return digest\n        }\n        return Data(pointer).base64EncodedString()\n    }\n}\n"
  },
  {
    "path": "Sources/Security/Security.swift",
    "content": "//////////////////////////////////////////////////////////////////////////////////////////////////\n//\n//  Security.swift\n//  Starscream\n//\n//  Created by Dalton Cherry on 3/16/19.\n//  Copyright © 2019 Vluxe. All rights reserved.\n//\n//  Licensed under the Apache License, Version 2.0 (the \"License\");\n//  you may not use this file except in compliance with the License.\n//  You may obtain a copy of the License at\n//\n//  http://www.apache.org/licenses/LICENSE-2.0\n//\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n//\n//////////////////////////////////////////////////////////////////////////////////////////////////\n\nimport Foundation\n\npublic enum SecurityErrorCode: UInt16 {\n    case acceptFailed = 1\n    case pinningFailed = 2\n}\n\npublic enum PinningState {\n    case success\n    case failed(CFError?)\n}\n\n// CertificatePinning protocol provides an interface for Transports to handle Certificate\n// or Public Key Pinning.\npublic protocol CertificatePinning: AnyObject {\n    func evaluateTrust(trust: SecTrust, domain: String?, completion: ((PinningState) -> ()))\n}\n\n// validates the \"Sec-WebSocket-Accept\" header as defined 1.3 of the RFC 6455\n// https://tools.ietf.org/html/rfc6455#section-1.3\npublic protocol HeaderValidator: AnyObject {\n    func validate(headers: [String: String], key: String) -> Error?\n}\n"
  },
  {
    "path": "Sources/Server/Server.swift",
    "content": "//////////////////////////////////////////////////////////////////////////////////////////////////\n//\n//  Server.swift\n//  Starscream\n//\n//  Created by Dalton Cherry on 4/2/19.\n//  Copyright © 2019 Vluxe. All rights reserved.\n//\n//  Licensed under the Apache License, Version 2.0 (the \"License\");\n//  you may not use this file except in compliance with the License.\n//  You may obtain a copy of the License at\n//\n//  http://www.apache.org/licenses/LICENSE-2.0\n//\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n//\n//////////////////////////////////////////////////////////////////////////////////////////////////\n\nimport Foundation\n\npublic enum ConnectionEvent {\n    case connected([String: String])\n    case disconnected(String, UInt16)\n    case text(String)\n    case binary(Data)\n    case pong(Data?)\n    case ping(Data?)\n    case error(Error)\n}\n\npublic protocol Connection {\n    func write(data: Data, opcode: FrameOpCode)\n}\n\npublic protocol ConnectionDelegate: AnyObject {\n    func didReceive(event: ServerEvent)\n}\n\npublic enum ServerEvent {\n    case connected(Connection, [String: String])\n    case disconnected(Connection, String, UInt16)\n    case text(Connection, String)\n    case binary(Connection, Data)\n    case pong(Connection, Data?)\n    case ping(Connection, Data?)\n}\n\npublic protocol Server {\n    func start(address: String, port: UInt16) -> Error?\n}\n\n\n"
  },
  {
    "path": "Sources/Server/WebSocketServer.swift",
    "content": "//////////////////////////////////////////////////////////////////////////////////////////////////\n//\n//  WebSocketServer.swift\n//  Starscream\n//\n//  Created by Dalton Cherry on 4/5/19.\n//  Copyright © 2019 Vluxe. All rights reserved.\n//\n//  Licensed under the Apache License, Version 2.0 (the \"License\");\n//  you may not use this file except in compliance with the License.\n//  You may obtain a copy of the License at\n//\n//  http://www.apache.org/licenses/LICENSE-2.0\n//\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n//\n//////////////////////////////////////////////////////////////////////////////////////////////////\n\n#if canImport(Network)\nimport Foundation\nimport Network\n\n/// WebSocketServer is a Network.framework implementation of a WebSocket server\n@available(watchOS, unavailable)\n@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *)\npublic class WebSocketServer: Server, ConnectionDelegate {\n    public var onEvent: ((ServerEvent) -> Void)?\n    private var connections = [String: ServerConnection]()\n    private var listener: NWListener?\n    private let queue = DispatchQueue(label: \"com.vluxe.starscream.server.networkstream\", attributes: [])\n    \n    public init() {\n        \n    }\n    \n    public func start(address: String, port: UInt16) -> Error? {\n        //TODO: support TLS cert adding/binding\n        let parameters = NWParameters(tls: nil, tcp: NWProtocolTCP.Options())\n        let p = NWEndpoint.Port(rawValue: port)!\n        parameters.requiredLocalEndpoint = NWEndpoint.hostPort(host: NWEndpoint.Host.name(address, nil), port: p)\n        \n        guard let listener = try? NWListener(using: parameters, on: p) else {\n            return WSError(type: .serverError, message: \"unable to start the listener at: \\(address):\\(port)\", code: 0)\n        }\n        listener.newConnectionHandler = {[weak self] conn in\n            let transport = TCPTransport(connection: conn)\n            let c = ServerConnection(transport: transport)\n            c.delegate = self\n            self?.connections[c.uuid] = c\n        }\n//        listener.stateUpdateHandler = { state in\n//            switch state {\n//            case .ready:\n//                print(\"ready to get sockets!\")\n//            case .setup:\n//                print(\"setup to get sockets!\")\n//            case .cancelled:\n//                print(\"server cancelled!\")\n//            case .waiting(let error):\n//                print(\"waiting error: \\(error)\")\n//            case .failed(let error):\n//                print(\"server failed: \\(error)\")\n//            @unknown default:\n//                print(\"wat?\")\n//            }\n//        }\n        self.listener = listener\n        listener.start(queue: queue)\n        return nil\n    }\n    \n    public func didReceive(event: ServerEvent) {\n        onEvent?(event)\n        switch event {\n        case .disconnected(let conn, _, _):\n            guard let conn = conn as? ServerConnection else {\n                return\n            }\n            connections.removeValue(forKey: conn.uuid)\n        default:\n            break\n        }\n    }\n}\n\n@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *)\npublic class ServerConnection: Connection, HTTPServerDelegate, FramerEventClient, FrameCollectorDelegate, TransportEventClient {\n    let transport: TCPTransport\n    private let httpHandler = FoundationHTTPServerHandler()\n    private let framer = WSFramer(isServer: true)\n    private let frameHandler = FrameCollector()\n    private var didUpgrade = false\n    public var onEvent: ((ConnectionEvent) -> Void)?\n    public weak var delegate: ConnectionDelegate?\n    private let id: String\n    var uuid: String {\n        return id\n    }\n    \n    init(transport: TCPTransport) {\n        self.id = UUID().uuidString\n        self.transport = transport\n        transport.register(delegate: self)\n        httpHandler.register(delegate: self)\n        framer.register(delegate: self)\n        frameHandler.delegate = self\n    }\n    \n    public func write(data: Data, opcode: FrameOpCode) {\n        let wsData = framer.createWriteFrame(opcode: opcode, payload: data, isCompressed: false)\n        transport.write(data: wsData, completion: {_ in })\n    }\n    \n    // MARK: - TransportEventClient\n    \n    public func connectionChanged(state: ConnectionState) {\n        switch state {\n        case .connected:\n            break\n        case .waiting:\n            break\n        case .failed(let error):\n            print(\"server connection error: \\(error ?? WSError(type: .protocolError, message: \"default error, no extra data\", code: 0))\") //handleError(error)\n        case .viability(_):\n            break\n        case .shouldReconnect(_):\n            break\n        case .receive(let data):\n            if didUpgrade {\n                framer.add(data: data)\n            } else {\n                httpHandler.parse(data: data)\n            }\n        case .cancelled:\n            print(\"server connection cancelled!\")\n            //broadcast(event: .cancelled)\n        case .peerClosed:\n            delegate?.didReceive(event: .disconnected(self, \"Connection closed by peer\", UInt16(FrameOpCode.connectionClose.rawValue)))\n        }\n    }\n    \n    /// MARK: - HTTPServerDelegate\n    \n    public func didReceive(event: HTTPEvent) {\n        switch event {\n        case .success(let headers):\n            didUpgrade = true\n            let response = httpHandler.createResponse(headers: [:])\n            transport.write(data: response, completion: {_ in })\n            delegate?.didReceive(event: .connected(self, headers))\n            onEvent?(.connected(headers))\n        case .failure(let error):\n            onEvent?(.error(error))\n        }\n    }\n    \n    /// MARK: - FrameCollectorDelegate\n    \n    public func frameProcessed(event: FrameEvent) {\n        switch event {\n        case .frame(let frame):\n            frameHandler.add(frame: frame)\n        case .error(let error):\n            onEvent?(.error(error))\n        }\n    }\n    \n    public func didForm(event: FrameCollector.Event) {\n        switch event {\n        case .text(let string):\n            delegate?.didReceive(event: .text(self, string))\n            onEvent?(.text(string))\n        case .binary(let data):\n            delegate?.didReceive(event: .binary(self, data))\n            onEvent?(.binary(data))\n        case .pong(let data):\n            delegate?.didReceive(event: .pong(self, data))\n            onEvent?(.pong(data))\n        case .ping(let data):\n            delegate?.didReceive(event: .ping(self, data))\n            onEvent?(.ping(data))\n        case .closed(let reason, let code):\n            delegate?.didReceive(event: .disconnected(self, reason, code))\n            onEvent?(.disconnected(reason, code))\n        case .error(let error):\n            onEvent?(.error(error))\n        }\n    }\n    \n    public func decompress(data: Data, isFinal: Bool) -> Data? {\n        return nil\n    }\n}\n#endif\n"
  },
  {
    "path": "Sources/Starscream/WebSocket.swift",
    "content": "//////////////////////////////////////////////////////////////////////////////////////////////////\n//\n//  Websocket.swift\n//  Starscream\n//\n//  Created by Dalton Cherry on 7/16/14.\n//  Copyright (c) 2014-2019 Dalton Cherry.\n//\n//  Licensed under the Apache License, Version 2.0 (the \"License\");\n//  you may not use this file except in compliance with the License.\n//  You may obtain a copy of the License at\n//\n//  http://www.apache.org/licenses/LICENSE-2.0\n//\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n//\n//////////////////////////////////////////////////////////////////////////////////////////////////\n\nimport Foundation\n\npublic enum ErrorType: Error {\n    case compressionError\n    case securityError\n    case protocolError //There was an error parsing the WebSocket frames\n    case serverError\n}\n\npublic struct WSError: Error {\n    public let type: ErrorType\n    public let message: String\n    public let code: UInt16\n    \n    public init(type: ErrorType, message: String, code: UInt16) {\n        self.type = type\n        self.message = message\n        self.code = code\n    }\n}\n\npublic protocol WebSocketClient: AnyObject {\n    func connect()\n    func disconnect(closeCode: UInt16)\n    func write(string: String, completion: (() -> ())?)\n    func write(stringData: Data, completion: (() -> ())?)\n    func write(data: Data, completion: (() -> ())?)\n    func write(ping: Data, completion: (() -> ())?)\n    func write(pong: Data, completion: (() -> ())?)\n}\n\n//implements some of the base behaviors\nextension WebSocketClient {\n    public func write(string: String) {\n        write(string: string, completion: nil)\n    }\n    \n    public func write(data: Data) {\n        write(data: data, completion: nil)\n    }\n    \n    public func write(ping: Data) {\n        write(ping: ping, completion: nil)\n    }\n    \n    public func write(pong: Data) {\n        write(pong: pong, completion: nil)\n    }\n    \n    public func disconnect() {\n        disconnect(closeCode: CloseCode.normal.rawValue)\n    }\n}\n\npublic enum WebSocketEvent {\n    case connected([String: String])\n    case disconnected(String, UInt16)\n    case text(String)\n    case binary(Data)\n    case pong(Data?)\n    case ping(Data?)\n    case error(Error?)\n    case viabilityChanged(Bool)\n    case reconnectSuggested(Bool)\n    case cancelled\n    case peerClosed\n}\n\npublic protocol WebSocketDelegate: AnyObject {\n    func didReceive(event: WebSocketEvent, client: WebSocketClient)\n}\n\nopen class WebSocket: WebSocketClient, EngineDelegate {\n    private let engine: Engine\n    public weak var delegate: WebSocketDelegate?\n    public var onEvent: ((WebSocketEvent) -> Void)?\n    \n    public var request: URLRequest\n    // Where the callback is executed. It defaults to the main UI thread queue.\n    public var callbackQueue = DispatchQueue.main\n    public var respondToPingWithPong: Bool {\n        set {\n            guard let e = engine as? WSEngine else { return }\n            e.respondToPingWithPong = newValue\n        }\n        get {\n            guard let e = engine as? WSEngine else { return true }\n            return e.respondToPingWithPong\n        }\n    }\n    \n    public init(request: URLRequest, engine: Engine) {\n        self.request = request\n        self.engine = engine\n    }\n    \n    public convenience init(request: URLRequest, certPinner: CertificatePinning? = FoundationSecurity(), compressionHandler: CompressionHandler? = nil, useCustomEngine: Bool = true) {\n        if #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *), !useCustomEngine {\n            self.init(request: request, engine: NativeEngine())\n        } else if #available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) {\n            self.init(request: request, engine: WSEngine(transport: TCPTransport(), certPinner: certPinner, compressionHandler: compressionHandler))\n        } else {\n            self.init(request: request, engine: WSEngine(transport: FoundationTransport(), certPinner: certPinner, compressionHandler: compressionHandler))\n        }\n    }\n    \n    public func connect() {\n        engine.register(delegate: self)\n        engine.start(request: request)\n    }\n    \n    public func disconnect(closeCode: UInt16 = CloseCode.normal.rawValue) {\n        engine.stop(closeCode: closeCode)\n    }\n    \n    public func forceDisconnect() {\n        engine.forceStop()\n    }\n    \n    public func write(data: Data, completion: (() -> ())?) {\n         write(data: data, opcode: .binaryFrame, completion: completion)\n    }\n    \n    public func write(string: String, completion: (() -> ())?) {\n        engine.write(string: string, completion: completion)\n    }\n    \n    public func write(stringData: Data, completion: (() -> ())?) {\n        write(data: stringData, opcode: .textFrame, completion: completion)\n    }\n    \n    public func write(ping: Data, completion: (() -> ())?) {\n        write(data: ping, opcode: .ping, completion: completion)\n    }\n    \n    public func write(pong: Data, completion: (() -> ())?) {\n        write(data: pong, opcode: .pong, completion: completion)\n    }\n    \n    private func write(data: Data, opcode: FrameOpCode, completion: (() -> ())?) {\n        engine.write(data: data, opcode: opcode, completion: completion)\n    }\n    \n    // MARK: - EngineDelegate\n    public func didReceive(event: WebSocketEvent) {\n        callbackQueue.async { [weak self] in\n            guard let s = self else { return }\n            s.delegate?.didReceive(event: event, client: s)\n            s.onEvent?(event)\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Starscream.h",
    "content": "//////////////////////////////////////////////////////////////////////////////////////////////////\n//\n//  Starscream.h\n//  Starscream\n//\n//  Created by Austin Cherry on 9/25/14.\n//  Copyright © 2014 Vluxe. All rights reserved.\n//\n//  Licensed under the Apache License, Version 2.0 (the \"License\");\n//  you may not use this file except in compliance with the License.\n//  You may obtain a copy of the License at\n//\n//  http://www.apache.org/licenses/LICENSE-2.0\n//\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n//\n//////////////////////////////////////////////////////////////////////////////////////////////////\n\n#import <Foundation/Foundation.h>\n\n//! Project version number for Starscream.\nFOUNDATION_EXPORT double StarscreamVersionNumber;\n\n//! Project version string for Starscream.\nFOUNDATION_EXPORT const unsigned char StarscreamVersionString[];\n\n// In this header, you should import all the public headers of your framework using statements like #import <Starscream/PublicHeader.h>\n"
  },
  {
    "path": "Sources/Transport/FoundationTransport.swift",
    "content": "//////////////////////////////////////////////////////////////////////////////////////////////////\n//\n//  FoundationTransport.swift\n//  Starscream\n//\n//  Created by Dalton Cherry on 1/23/19.\n//  Copyright © 2019 Vluxe. All rights reserved.\n//\n//  Licensed under the Apache License, Version 2.0 (the \"License\");\n//  you may not use this file except in compliance with the License.\n//  You may obtain a copy of the License at\n//\n//  http://www.apache.org/licenses/LICENSE-2.0\n//\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n//\n//////////////////////////////////////////////////////////////////////////////////////////////////\n\nimport Foundation\n\npublic enum FoundationTransportError: Error {\n    case invalidRequest\n    case invalidOutputStream\n    case timeout\n}\n\npublic class FoundationTransport: NSObject, Transport, StreamDelegate {\n    private weak var delegate: TransportEventClient?\n    private let workQueue = DispatchQueue(label: \"com.vluxe.starscream.websocket\", attributes: [])\n    private var inputStream: InputStream?\n    private var outputStream: OutputStream?\n    private var isOpen = false\n    private var onConnect: ((InputStream, OutputStream) -> Void)?\n    private var isTLS = false\n    private var certPinner: CertificatePinning?\n    \n    public var usingTLS: Bool {\n        return self.isTLS\n    }\n    \n    public init(streamConfiguration: ((InputStream, OutputStream) -> Void)? = nil) {\n        super.init()\n        onConnect = streamConfiguration\n    }\n    \n    deinit {\n        inputStream?.delegate = nil\n        outputStream?.delegate = nil\n    }\n    \n    public func connect(url: URL, timeout: Double = 10, certificatePinning: CertificatePinning? = nil) {\n        guard let parts = url.getParts() else {\n            delegate?.connectionChanged(state: .failed(FoundationTransportError.invalidRequest))\n            return\n        }\n        self.certPinner = certificatePinning\n        self.isTLS = parts.isTLS\n        var readStream: Unmanaged<CFReadStream>?\n        var writeStream: Unmanaged<CFWriteStream>?\n        let h = parts.host as NSString\n        CFStreamCreatePairWithSocketToHost(nil, h, UInt32(parts.port), &readStream, &writeStream)\n        inputStream = readStream!.takeRetainedValue()\n        outputStream = writeStream!.takeRetainedValue()\n        guard let inStream = inputStream, let outStream = outputStream else {\n                return\n        }\n        inStream.delegate = self\n        outStream.delegate = self\n    \n        if isTLS {\n            let key = CFStreamPropertyKey(rawValue: kCFStreamPropertySocketSecurityLevel)\n            CFReadStreamSetProperty(inStream, key, kCFStreamSocketSecurityLevelNegotiatedSSL)\n            CFWriteStreamSetProperty(outStream, key, kCFStreamSocketSecurityLevelNegotiatedSSL)\n        }\n        \n        onConnect?(inStream, outStream)\n        \n        isOpen = false\n        CFReadStreamSetDispatchQueue(inStream, workQueue)\n        CFWriteStreamSetDispatchQueue(outStream, workQueue)\n        inStream.open()\n        outStream.open()\n        \n        \n        workQueue.asyncAfter(deadline: .now() + timeout, execute: { [weak self] in\n            guard let s = self else { return }\n            if !s.isOpen {\n                s.delegate?.connectionChanged(state: .failed(FoundationTransportError.timeout))\n            }\n        })\n    }\n    \n    public func disconnect() {\n        if let stream = inputStream {\n            stream.delegate = nil\n            CFReadStreamSetDispatchQueue(stream, nil)\n            stream.close()\n        }\n        if let stream = outputStream {\n            stream.delegate = nil\n            CFWriteStreamSetDispatchQueue(stream, nil)\n            stream.close()\n        }\n        isOpen = false\n        outputStream = nil\n        inputStream = nil\n    }\n    \n    public func register(delegate: TransportEventClient) {\n        self.delegate = delegate\n    }\n    \n    public func write(data: Data, completion: @escaping ((Error?) -> ())) {\n        guard let outStream = outputStream else {\n            completion(FoundationTransportError.invalidOutputStream)\n            return\n        }\n        var total = 0\n        let buffer = UnsafeRawPointer((data as NSData).bytes).assumingMemoryBound(to: UInt8.self)\n        //NOTE: this might need to be dispatched to the work queue instead of being written inline. TBD.\n        while total < data.count {\n            let written = outStream.write(buffer, maxLength: data.count)\n            if written < 0 {\n                completion(FoundationTransportError.invalidOutputStream)\n                return\n            }\n            total += written\n        }\n        completion(nil)\n    }\n    \n    private func getSecurityData() -> (SecTrust?, String?) {\n        #if os(watchOS)\n        return (nil, nil)\n        #else\n        guard let outputStream = outputStream else {\n            return (nil, nil)\n        }\n        let trust = outputStream.property(forKey: kCFStreamPropertySSLPeerTrust as Stream.PropertyKey) as! SecTrust?\n        var domain = outputStream.property(forKey: kCFStreamSSLPeerName as Stream.PropertyKey) as! String?\n        \n        if domain == nil,\n            let sslContextOut = CFWriteStreamCopyProperty(outputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext? {\n            var peerNameLen: Int = 0\n            SSLGetPeerDomainNameLength(sslContextOut, &peerNameLen)\n            var peerName = Data(count: peerNameLen)\n            let _ = peerName.withUnsafeMutableBytes { (peerNamePtr: UnsafeMutablePointer<Int8>) in\n                SSLGetPeerDomainName(sslContextOut, peerNamePtr, &peerNameLen)\n            }\n            if let peerDomain = String(bytes: peerName, encoding: .utf8), peerDomain.count > 0 {\n                domain = peerDomain\n            }\n        }\n        return (trust, domain)\n        #endif\n    }\n    \n    private func read() {\n        guard let stream = inputStream else {\n            return\n        }\n        let maxBuffer = 4096\n        let buf = NSMutableData(capacity: maxBuffer)\n        let buffer = UnsafeMutableRawPointer(mutating: buf!.bytes).assumingMemoryBound(to: UInt8.self)\n        let length = stream.read(buffer, maxLength: maxBuffer)\n        if length < 1 {\n            return\n        }\n        let data = Data(bytes: buffer, count: length)\n        delegate?.connectionChanged(state: .receive(data))\n    }\n    \n    // MARK: - StreamDelegate\n    \n    open func stream(_ aStream: Stream, handle eventCode: Stream.Event) {\n        switch eventCode {\n        case .hasBytesAvailable:\n            if aStream == inputStream {\n                read()\n            }\n        case .errorOccurred:\n            delegate?.connectionChanged(state: .failed(aStream.streamError))\n        case .endEncountered:\n            if aStream == inputStream {\n                delegate?.connectionChanged(state: .cancelled)\n            }\n        case .openCompleted:\n            if aStream == inputStream {\n                let (trust, domain) = getSecurityData()\n                if let pinner = certPinner, let trust = trust {\n                    pinner.evaluateTrust(trust: trust, domain:  domain, completion: { [weak self] (state) in\n                        switch state {\n                        case .success:\n                            self?.isOpen = true\n                            self?.delegate?.connectionChanged(state: .connected)\n                        case .failed(let error):\n                            self?.delegate?.connectionChanged(state: .failed(error))\n                        }\n                        \n                    })\n                } else {\n                    isOpen = true\n                    delegate?.connectionChanged(state: .connected)\n                }\n            }\n        case .endEncountered:\n            if aStream == inputStream {\n                delegate?.connectionChanged(state: .cancelled)\n            }\n        default:\n            break\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Transport/TCPTransport.swift",
    "content": "//////////////////////////////////////////////////////////////////////////////////////////////////\n//\n//  HTTPTransport.swift\n//  Starscream\n//\n//  Created by Dalton Cherry on 1/23/19.\n//  Copyright © 2019 Vluxe. All rights reserved.\n//\n//  Licensed under the Apache License, Version 2.0 (the \"License\");\n//  you may not use this file except in compliance with the License.\n//  You may obtain a copy of the License at\n//\n//  http://www.apache.org/licenses/LICENSE-2.0\n//\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n//\n//////////////////////////////////////////////////////////////////////////////////////////////////\n\n#if canImport(Network)\nimport Foundation\nimport Network\n\npublic enum TCPTransportError: Error {\n    case invalidRequest\n}\n\n@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *)\npublic class TCPTransport: Transport {\n    private var connection: NWConnection?\n    private let queue = DispatchQueue(label: \"com.vluxe.starscream.networkstream\", attributes: [])\n    private weak var delegate: TransportEventClient?\n    private var isRunning = false\n    private var isTLS = false\n   \n    deinit {\n        disconnect()\n    }\n \n    public var usingTLS: Bool {\n        return self.isTLS\n    }\n    \n    public init(connection: NWConnection) {\n        self.connection = connection\n        start()\n    }\n    \n    public init() {\n        //normal connection, will use the \"connect\" method below\n    }\n    \n    public func connect(url: URL, timeout: Double = 10, certificatePinning: CertificatePinning? = nil) {\n        guard let parts = url.getParts() else {\n            delegate?.connectionChanged(state: .failed(TCPTransportError.invalidRequest))\n            return\n        }\n        self.isTLS = parts.isTLS\n        let options = NWProtocolTCP.Options()\n        options.connectionTimeout = Int(timeout.rounded(.up))\n\n        let tlsOptions = isTLS ? NWProtocolTLS.Options() : nil\n        if let tlsOpts = tlsOptions {\n            sec_protocol_options_set_verify_block(tlsOpts.securityProtocolOptions, { (sec_protocol_metadata, sec_trust, sec_protocol_verify_complete) in\n                let trust = sec_trust_copy_ref(sec_trust).takeRetainedValue()\n                guard let pinner = certificatePinning else {\n                    sec_protocol_verify_complete(true)\n                    return\n                }\n                pinner.evaluateTrust(trust: trust, domain: parts.host, completion: { (state) in\n                    switch state {\n                    case .success:\n                        sec_protocol_verify_complete(true)\n                    case .failed(_):\n                        sec_protocol_verify_complete(false)\n                    }\n                })\n            }, queue)\n        }\n        let parameters = NWParameters(tls: tlsOptions, tcp: options)\n        let conn = NWConnection(host: NWEndpoint.Host.name(parts.host, nil), port: NWEndpoint.Port(rawValue: UInt16(parts.port))!, using: parameters)\n        connection = conn\n        start()\n    }\n    \n    public func disconnect() {\n        isRunning = false\n        connection?.cancel()\n        connection = nil\n    }\n    \n    public func register(delegate: TransportEventClient) {\n        self.delegate = delegate\n    }\n    \n    public func write(data: Data, completion: @escaping ((Error?) -> ())) {\n        connection?.send(content: data, completion: .contentProcessed { (error) in\n            completion(error)\n        })\n    }\n    \n    private func start() {\n        guard let conn = connection else {\n            return\n        }\n        conn.stateUpdateHandler = { [weak self] (newState) in\n            switch newState {\n            case .ready:\n                self?.delegate?.connectionChanged(state: .connected)\n            case .waiting:\n                self?.delegate?.connectionChanged(state: .waiting)\n            case .cancelled:\n                self?.delegate?.connectionChanged(state: .cancelled)\n            case .failed(let error):\n                self?.delegate?.connectionChanged(state: .failed(error))\n            case .setup, .preparing:\n                break\n            @unknown default:\n                break\n            }\n        }\n        \n        conn.viabilityUpdateHandler = { [weak self] (isViable) in\n            self?.delegate?.connectionChanged(state: .viability(isViable))\n        }\n        \n        conn.betterPathUpdateHandler = { [weak self] (isBetter) in\n            self?.delegate?.connectionChanged(state: .shouldReconnect(isBetter))\n        }\n        \n        conn.start(queue: queue)\n        isRunning = true\n        readLoop()\n    }\n    \n    //readLoop keeps reading from the connection to get the latest content\n    private func readLoop() {\n        if !isRunning {\n            return\n        }\n        connection?.receive(minimumIncompleteLength: 2, maximumLength: 4096, completion: {[weak self] (data, context, isComplete, error) in\n            guard let s = self else {return}\n            if let data = data {\n                s.delegate?.connectionChanged(state: .receive(data))\n            }\n            \n            // Refer to https://developer.apple.com/documentation/network/implementing_netcat_with_network_framework\n            if let context = context, context.isFinal, isComplete {\n                if let delegate = s.delegate {\n                    // Let the owner of this TCPTransport decide what to do next: disconnect or reconnect?\n                    delegate.connectionChanged(state: .peerClosed)\n                } else {\n                    // No use to keep connection alive\n                    s.disconnect()\n                }\n                return\n            }\n            \n            if error == nil {\n                s.readLoop()\n            }\n\n        })\n    }\n}\n#else\ntypealias TCPTransport = FoundationTransport\n#endif\n"
  },
  {
    "path": "Sources/Transport/Transport.swift",
    "content": "//////////////////////////////////////////////////////////////////////////////////////////////////\n//\n//  Transport.swift\n//  Starscream\n//\n//  Created by Dalton Cherry on 1/23/19.\n//  Copyright © 2019 Vluxe. All rights reserved.\n//\n//  Licensed under the Apache License, Version 2.0 (the \"License\");\n//  you may not use this file except in compliance with the License.\n//  You may obtain a copy of the License at\n//\n//  http://www.apache.org/licenses/LICENSE-2.0\n//\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n//\n//////////////////////////////////////////////////////////////////////////////////////////////////\n\nimport Foundation\n\npublic enum ConnectionState {\n    /// Ready connections can send and receive data\n    case connected\n    \n    /// Waiting connections have not yet been started, or do not have a viable network\n    case waiting\n    \n    /// Cancelled connections have been invalidated by the client and will send no more events\n    case cancelled\n    \n    /// Failed connections are disconnected and can no longer send or receive data\n    case failed(Error?)\n    \n    /// Viability (connection status) of the connection has updated\n    /// e.g. connection is down, connection came back up, etc.\n    case viability(Bool)\n    \n    /// Connection ca be upgraded to wifi from cellular.\n    /// You should consider reconnecting to take advantage of this.\n    case shouldReconnect(Bool)\n    \n    /// Received data\n    case receive(Data)\n    \n    /// Remote peer has closed the network connection.\n    case peerClosed\n}\n\npublic protocol TransportEventClient: AnyObject {\n    func connectionChanged(state: ConnectionState)\n}\n\npublic protocol Transport: AnyObject {\n    func register(delegate: TransportEventClient)\n    func connect(url: URL, timeout: Double, certificatePinning: CertificatePinning?)\n    func disconnect()\n    func write(data: Data, completion: @escaping ((Error?) -> ()))\n    var usingTLS: Bool { get }\n}\n"
  },
  {
    "path": "Starscream.podspec",
    "content": "Pod::Spec.new do |s|\n  s.name         = \"Starscream\"\n  s.version      = \"4.0.4\"\n  s.summary      = \"A conforming WebSocket RFC 6455 client library in Swift.\"\n  s.homepage     = \"https://github.com/daltoniam/Starscream\"\n  s.license      = 'Apache License, Version 2.0'\n  s.author       = {'Dalton Cherry' => 'http://daltoniam.com', 'Austin Cherry' => 'http://austincherry.me'}\n  s.source       = { :git => 'https://github.com/daltoniam/Starscream.git',  :tag => \"#{s.version}\"}\n  s.social_media_url = 'http://twitter.com/daltoniam'\n  s.ios.deployment_target = '12.0'\n  s.osx.deployment_target = '10.13'\n  s.tvos.deployment_target = '12.0'\n  s.watchos.deployment_target = '2.0'\n  s.source_files = 'Sources/**/*.swift'\n  s.swift_version = '5.0'\n  s.resource_bundles = {\n    'Starscream_Privacy' => ['Sources/PrivacyInfo.xcprivacy'],\n  }\nend\n"
  },
  {
    "path": "Tests/CompressionTests.swift",
    "content": "//////////////////////////////////////////////////////////////////////////////////////////////////\n//\n//  CompressionTests.swift\n//\n//  Created by Joseph Ross on 7/16/14.\n//  Copyright © 2017 Joseph Ross.\n//\n//  Licensed under the Apache License, Version 2.0 (the \"License\");\n//  you may not use this file except in compliance with the License.\n//  You may obtain a copy of the License at\n//\n//  http://www.apache.org/licenses/LICENSE-2.0\n//\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n//\n//////////////////////////////////////////////////////////////////////////////////////////////////\n\nimport XCTest\n@testable import Starscream\n\nclass CompressionTests: XCTestCase {\n    \n    override func setUp() {\n        super.setUp()\n        // Put setup code here. This method is called before the invocation of each test method in the class.\n    }\n    \n    override func tearDown() {\n        // Put teardown code here. This method is called after the invocation of each test method in the class.\n        super.tearDown()\n    }\n    \n    func testBasic() {\n        let compressor = Compressor(windowBits: 15)!\n        let decompressor = Decompressor(windowBits: 15)!\n        \n        let rawData = \"Hello, World! Hello, World! Hello, World! Hello, World! Hello, World!\".data(using: .utf8)!\n        \n        let compressed = try! compressor.compress(rawData)\n        let uncompressed = try! decompressor.decompress(compressed, finish: true)\n        \n        XCTAssert(rawData == uncompressed)\n    }\n    \n    func testHugeData() {\n        let compressor = Compressor(windowBits: 15)!\n        let decompressor = Decompressor(windowBits: 15)!\n        \n        // 2 Gigs!\n//        var rawData = Data(repeating: 0, count: 0x80000000)\n        var rawData = Data(repeating: 0, count: 0x80000)\n        let rawDataLen = rawData.count\n        rawData.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) -> Void in\n            arc4random_buf(ptr, rawDataLen)\n        }\n        \n        let compressed = try! compressor.compress(rawData)\n        let uncompressed = try! decompressor.decompress(compressed, finish: true)\n        \n        XCTAssert(rawData == uncompressed)\n    }\n    \n}\n"
  },
  {
    "path": "Tests/FuzzingTests.swift",
    "content": "//////////////////////////////////////////////////////////////////////////////////////////////////\n//\n//  FuzzingTests.swift\n//  Starscream\n//\n//  Created by Dalton Cherry on 1/28/19.\n//  Copyright © 2019 Vluxe. All rights reserved.\n//\n//  Licensed under the Apache License, Version 2.0 (the \"License\");\n//  you may not use this file except in compliance with the License.\n//  You may obtain a copy of the License at\n//\n//  http://www.apache.org/licenses/LICENSE-2.0\n//\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n//\n//////////////////////////////////////////////////////////////////////////////////////////////////\n\nimport XCTest\n@testable import Starscream\n\nclass FuzzingTests: XCTestCase {\n    \n    var websocket: WebSocket!\n    var server: MockServer!\n    var uuid = \"\"\n    \n    override func setUp() {\n        super.setUp()\n        \n        let s = MockServer()\n        let _ = s.start(address: \"\", port: 0)\n        server = s\n        \n        let transport = MockTransport(server: s)\n        uuid = transport.uuid\n        \n        let url = URL(string: \"http://vluxe.io/ws\")! //domain doesn't matter with the mock transport\n        let request = URLRequest(url: url)        \n        websocket = WebSocket(request: request, engine: WSEngine(transport: transport))\n        \n    }\n    \n    override func tearDown() {\n        super.tearDown()\n    }\n    \n    func runWebsocket(timeout: TimeInterval = 10, serverAction: @escaping ((ServerEvent) -> Bool)) {\n        let e = expectation(description: \"Websocket event timeout\")\n        server.onEvent = { event in\n            let done = serverAction(event)\n            if done {\n                e.fulfill()\n            }\n        }\n        \n        websocket.onEvent = { event in\n            switch event {\n            case .text(let string):\n                self.websocket.write(string: string)\n            case .binary(let data):\n                self.websocket.write(data: data)\n            case .ping(_):\n                break\n            case .pong(_):\n                break\n            case .connected(_):\n                break\n            case .disconnected(let reason, let code):\n                print(\"reason: \\(reason) code: \\(code)\")\n            case .error(_):\n                break\n            case .viabilityChanged(_):\n                break\n            case .reconnectSuggested(_):\n                break\n            case .cancelled:\n                break\n            case .peerClosed:\n                break\n            }\n        }\n        websocket.connect()\n        waitForExpectations(timeout: timeout) { error in\n            if let error = error {\n                XCTFail(\"waitForExpectationsWithTimeout errored: \\(error)\")\n            }\n        }\n    }\n    \n    func sendMessage(string: String, isBinary: Bool) {\n        let payload = string.data(using: .utf8)!\n        let code: FrameOpCode = isBinary ? .binaryFrame : .textFrame\n        runWebsocket { event in\n            switch event {\n            case .connected(let conn, _):\n                conn.write(data: payload, opcode: code)\n            case .text(let conn, let text):\n                if text == string && !isBinary {\n                    conn.write(data: Data(), opcode: .connectionClose)\n                    return true //success!\n                } else {\n                    XCTFail(\"text does not match: source: [\\(string)] response: [\\(text)]\")\n                }\n            case .binary(let conn, let data):\n                if payload.count == data.count && isBinary {\n                    conn.write(data: Data(), opcode: .connectionClose)\n                    return true //success!\n                } else {\n                    XCTFail(\"binary does not match: source: [\\(payload.count)] response: [\\(data.count)]\")\n                }\n                case .disconnected(_, _, _):\n                    return false\n            default:\n                XCTFail(\"recieved unexpected server event: \\(event)\")\n            }\n            return false\n        }\n    }\n    \n    //These are the Autobahn test cases as unit tests\n    \n    \n    /// MARK : - Framing cases\n    \n    // case 1.1.1\n    func testCase1() {\n        sendMessage(string: \"\", isBinary: false)\n    }\n    \n    // case 1.1.2\n    func testCase2() {\n        sendMessage(string: String(repeating: \"*\", count: 125), isBinary: false)\n    }\n    \n    // case 1.1.3\n    func testCase3() {\n        sendMessage(string: String(repeating: \"*\", count: 126), isBinary: false)\n    }\n    \n    // case 1.1.4\n    func testCase4() {\n        sendMessage(string: String(repeating: \"*\", count: 127), isBinary: false)\n    }\n    \n    // case 1.1.5\n    func testCase5() {\n        sendMessage(string: String(repeating: \"*\", count: 128), isBinary: false)\n    }\n    \n    // case 1.1.6\n    func testCase6() {\n        sendMessage(string: String(repeating: \"*\", count: 65535), isBinary: false)\n    }\n    \n    // case 1.1.7, 1.1.8\n    func testCase7() {\n        sendMessage(string: String(repeating: \"*\", count: 65536), isBinary: false)\n    }\n    \n    // case 1.2.1\n    func testCase9() {\n        sendMessage(string: \"\", isBinary: true)\n    }\n    \n    // case 1.2.2\n    func testCase10() {\n        sendMessage(string: String(repeating: \"*\", count: 125), isBinary: true)\n    }\n    \n    // case 1.2.3\n    func testCase11() {\n        sendMessage(string: String(repeating: \"*\", count: 126), isBinary: true)\n    }\n    \n    // case 1.2.4\n    func testCase12() {\n        sendMessage(string: String(repeating: \"*\", count: 127), isBinary: true)\n    }\n    \n    // case 1.2.5\n    func testCase13() {\n        sendMessage(string: String(repeating: \"*\", count: 128), isBinary: true)\n    }\n    \n    // case 1.2.6\n    func testCase14() {\n        sendMessage(string: String(repeating: \"*\", count: 65535), isBinary: true)\n    }\n    \n    // case 1.2.7, 1.2.8\n    func testCase15() {\n        sendMessage(string: String(repeating: \"*\", count: 65536), isBinary: true)\n    }\n    \n    //TODO: the rest of them.\n}\n"
  },
  {
    "path": "Tests/Info.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>CFBundleDevelopmentRegion</key>\n\t<string>en</string>\n\t<key>CFBundleExecutable</key>\n\t<string>$(EXECUTABLE_NAME)</string>\n\t<key>CFBundleIdentifier</key>\n\t<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>\n\t<key>CFBundleInfoDictionaryVersion</key>\n\t<string>6.0</string>\n\t<key>CFBundleName</key>\n\t<string>$(PRODUCT_NAME)</string>\n\t<key>CFBundlePackageType</key>\n\t<string>BNDL</string>\n\t<key>CFBundleShortVersionString</key>\n\t<string>1.0</string>\n\t<key>CFBundleSignature</key>\n\t<string>????</string>\n\t<key>CFBundleVersion</key>\n\t<string>1</string>\n</dict>\n</plist>\n"
  },
  {
    "path": "Tests/MockServer.swift",
    "content": "//////////////////////////////////////////////////////////////////////////////////////////////////\n//\n//  MockServer.swift\n//  Starscream\n//\n//  Created by Dalton Cherry on 1/29/19.\n//  Copyright © 2019 Vluxe. All rights reserved.\n//\n//  Licensed under the Apache License, Version 2.0 (the \"License\");\n//  you may not use this file except in compliance with the License.\n//  You may obtain a copy of the License at\n//\n//  http://www.apache.org/licenses/LICENSE-2.0\n//\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n//\n//////////////////////////////////////////////////////////////////////////////////////////////////\n\nimport Foundation\n@testable import Starscream\n\npublic class MockConnection: Connection, HTTPServerDelegate, FramerEventClient, FrameCollectorDelegate {\n    let transport: MockTransport\n    private let httpHandler = FoundationHTTPServerHandler()\n    private let framer = WSFramer(isServer: true)\n    private let frameHandler = FrameCollector()\n    private var didUpgrade = false\n    public var onEvent: ((ConnectionEvent) -> Void)?\n    fileprivate weak var delegate: ConnectionDelegate?\n    \n    init(transport: MockTransport) {\n        self.transport = transport\n        httpHandler.register(delegate: self)\n        framer.register(delegate: self)\n        frameHandler.delegate = self\n    }\n    \n    func add(data: Data) {\n        if !didUpgrade {\n            httpHandler.parse(data: data)\n        } else {\n            framer.add(data: data)\n        }\n    }\n    \n    public func write(data: Data, opcode: FrameOpCode) {\n        let wsData = framer.createWriteFrame(opcode: opcode, payload: data, isCompressed: false)\n        transport.received(data: wsData)\n    }\n    \n    /// MARK: - HTTPServerDelegate\n    \n    public func didReceive(event: HTTPEvent) {\n        switch event {\n        case .success(let headers):\n            didUpgrade = true\n            //TODO: add headers and key check?\n            let response = httpHandler.createResponse(headers: [:])\n            transport.received(data: response)\n            delegate?.didReceive(event: .connected(self, headers))\n            onEvent?(.connected(headers))\n        case .failure(let error):\n            onEvent?(.error(error))\n        }\n    }\n    \n    /// MARK: - FrameCollectorDelegate\n    \n    public func frameProcessed(event: FrameEvent) {\n        switch event {\n        case .frame(let frame):\n            frameHandler.add(frame: frame)\n        case .error(let error):\n            onEvent?(.error(error))\n        }\n    }\n    \n    public func didForm(event: FrameCollector.Event) {\n        switch event {\n        case .text(let string):\n            delegate?.didReceive(event: .text(self, string))\n            onEvent?(.text(string))\n        case .binary(let data):\n            delegate?.didReceive(event: .binary(self, data))\n            onEvent?(.binary(data))\n        case .pong(let data):\n            delegate?.didReceive(event: .pong(self, data))\n            onEvent?(.pong(data))\n        case .ping(let data):\n            delegate?.didReceive(event: .ping(self, data))\n            onEvent?(.ping(data))\n        case .closed(let reason, let code):\n            delegate?.didReceive(event: .disconnected(self, reason, code))\n            onEvent?(.disconnected(reason, code))\n        case .error(let error):\n            onEvent?(.error(error))\n        }\n    }\n    \n    public func decompress(data: Data, isFinal: Bool) -> Data? {\n        return nil\n    }\n}\n    \n\npublic class MockServer: Server, ConnectionDelegate {\n    fileprivate var connections = [String: MockConnection]()\n    \n    public var onEvent: ((ServerEvent) -> Void)?\n    \n    public func start(address: String, port: UInt16) -> Error? {\n        return nil\n    }\n    \n    public func connect(transport: MockTransport) {\n        let conn = MockConnection(transport: transport)\n        conn.delegate = self\n        connections[transport.uuid] = conn\n    }\n    \n    public func disconnect(uuid: String) {\n//        guard let conn = connections[uuid] else {\n//            return\n//        }\n        //TODO: force disconnect\n        connections.removeValue(forKey: uuid)\n    }\n    \n    public func write(data: Data, uuid: String) {\n        guard let conn = connections[uuid] else {\n            return\n        }\n        conn.add(data: data)\n    }\n    \n    /// MARK: - MockConnectionDelegate\n    public func didReceive(event: ServerEvent) {\n        onEvent?(event)\n    }\n}\n"
  },
  {
    "path": "Tests/MockTransport.swift",
    "content": "//////////////////////////////////////////////////////////////////////////////////////////////////\n//\n//  MockTransport.swift\n//  Starscream\n//\n//  Created by Dalton Cherry on 1/29/19.\n//  Copyright © 2019 Vluxe. All rights reserved.\n//\n//  Licensed under the Apache License, Version 2.0 (the \"License\");\n//  you may not use this file except in compliance with the License.\n//  You may obtain a copy of the License at\n//\n//  http://www.apache.org/licenses/LICENSE-2.0\n//\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n//\n//////////////////////////////////////////////////////////////////////////////////////////////////\n\nimport Foundation\n@testable import Starscream\n\npublic class MockTransport: Transport {\n    \n    public var usingTLS: Bool {\n        return false\n    }\n    private weak var delegate: TransportEventClient?\n    \n    private let id: String\n    weak var server: MockServer?\n    var uuid: String {\n        return id\n    }\n    \n    public init(server: MockServer) {\n        self.server = server\n        self.id = UUID().uuidString\n    }\n    \n    public func register(delegate: TransportEventClient) {\n        self.delegate = delegate\n    }\n    \n   public func connect(url: URL, timeout: Double, certificatePinning: CertificatePinning?) {\n        server?.connect(transport: self)\n        delegate?.connectionChanged(state: .connected)\n    }\n    \n    public func disconnect() {\n        server?.disconnect(uuid: uuid)\n    }\n    \n    public func write(data: Data, completion: @escaping ((Error?) -> ())) {\n        server?.write(data: data, uuid: uuid)\n    }\n    \n    public func received(data: Data) {\n        delegate?.connectionChanged(state: .receive(data))\n    }\n    \n    public func getSecurityData() -> (SecTrust?, String?) {\n        return (nil, nil)\n    }\n}\n\npublic class MockSecurity: CertificatePinning, HeaderValidator {\n    \n    public func evaluateTrust(trust: SecTrust, domain: String?, completion: ((PinningState) -> ())) {\n        completion(.success)\n    }\n\n    public func validate(headers: [String: String], key: String) -> Error? {\n        return nil\n    }\n}\n"
  },
  {
    "path": "Tests/StarscreamTests/StarscreamTests.swift",
    "content": "//////////////////////////////////////////////////////////////////////////////////////////////////\n//\n//  StarscreamTests.swift\n//  StarscreamTests\n//\n//  Created by Austin Cherry on 9/25/14.\n//  Copyright © 2014 Vluxe. All rights reserved.\n//\n//  Licensed under the Apache License, Version 2.0 (the \"License\");\n//  you may not use this file except in compliance with the License.\n//  You may obtain a copy of the License at\n//\n//  http://www.apache.org/licenses/LICENSE-2.0\n//\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n//\n//////////////////////////////////////////////////////////////////////////////////////////////////\n\nimport XCTest\n\nclass StarscreamTests: XCTestCase {\n    \n    override func setUp() {\n        super.setUp()\n        // Put setup code here. This method is called before the invocation of each test method in the class.\n    }\n    \n    override func tearDown() {\n        // Put teardown code here. This method is called after the invocation of each test method in the class.\n        super.tearDown()\n    }\n    \n    func testExample() {\n        // This is an example of a functional test case.\n        XCTAssert(true, \"Pass\")\n    }\n    \n    func testPerformanceExample() {\n        // This is an example of a performance test case.\n        self.measure() {\n            // Put the code you want to measure the time of here.\n        }\n    }\n    \n}\n"
  },
  {
    "path": "examples/AutobahnTest/.gitignore",
    "content": "# CocoaPods\n#\n# We recommend against adding the Pods directory to your .gitignore. However\n# you should judge for yourself, the pros and cons are mentioned at:\n# http://guides.cocoapods.org/using/using-cocoapods.html#should-i-ignore-the-pods-directory-in-source-control?\n#\n# Pods/\n\n# Xcode\n.DS_Store\nbuild\n*.pbxuser\n!default.pbxuser\n*.mode1v3\n!default.mode1v3\n*.mode2v3\n!default.mode2v3\n*.perspectivev3\n!default.perspectivev3\nxcuserdata\nprofile\n*.moved-aside\nDerivedData\n.idea/\n*.hmap\n*.xccheckout\n*.xcodeproj/*.xcworkspace"
  },
  {
    "path": "examples/AutobahnTest/Autobahn/AppDelegate.swift",
    "content": "//\n//  AppDelegate.swift\n//  Autobahn\n//\n//  Created by Dalton Cherry on 7/24/15.\n//  Copyright (c) 2015 vluxe. All rights reserved.\n//\n\nimport UIKit\n\n@UIApplicationMain\nclass AppDelegate: UIResponder, UIApplicationDelegate {\n\n    var window: UIWindow?\n\n\n    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {\n        // Override point for customization after application launch.\n        return true\n    }\n\n    func applicationWillResignActive(_ application: UIApplication) {\n        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.\n        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.\n    }\n\n    func applicationDidEnterBackground(_ application: UIApplication) {\n        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.\n        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.\n    }\n\n    func applicationWillEnterForeground(_ application: UIApplication) {\n        // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.\n    }\n\n    func applicationDidBecomeActive(_ application: UIApplication) {\n        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.\n    }\n\n    func applicationWillTerminate(_ application: UIApplication) {\n        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.\n    }\n\n\n}\n\n"
  },
  {
    "path": "examples/AutobahnTest/Autobahn/Base.lproj/LaunchScreen.xib",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n<document type=\"com.apple.InterfaceBuilder3.CocoaTouch.XIB\" version=\"3.0\" toolsVersion=\"6214\" systemVersion=\"14A314h\" targetRuntime=\"iOS.CocoaTouch\" propertyAccessControl=\"none\" useAutolayout=\"YES\" launchScreen=\"YES\" useTraitCollections=\"YES\">\n    <dependencies>\n        <plugIn identifier=\"com.apple.InterfaceBuilder.IBCocoaTouchPlugin\" version=\"6207\"/>\n        <capability name=\"Constraints with non-1.0 multipliers\" minToolsVersion=\"5.1\"/>\n    </dependencies>\n    <objects>\n        <placeholder placeholderIdentifier=\"IBFilesOwner\" id=\"-1\" userLabel=\"File's Owner\"/>\n        <placeholder placeholderIdentifier=\"IBFirstResponder\" id=\"-2\" customClass=\"UIResponder\"/>\n        <view contentMode=\"scaleToFill\" id=\"iN0-l3-epB\">\n            <rect key=\"frame\" x=\"0.0\" y=\"0.0\" width=\"480\" height=\"480\"/>\n            <autoresizingMask key=\"autoresizingMask\" widthSizable=\"YES\" heightSizable=\"YES\"/>\n            <subviews>\n                <label opaque=\"NO\" clipsSubviews=\"YES\" userInteractionEnabled=\"NO\" contentMode=\"left\" horizontalHuggingPriority=\"251\" verticalHuggingPriority=\"251\" text=\"  Copyright (c) 2015 vluxe. All rights reserved.\" textAlignment=\"center\" lineBreakMode=\"tailTruncation\" baselineAdjustment=\"alignBaselines\" minimumFontSize=\"9\" translatesAutoresizingMaskIntoConstraints=\"NO\" id=\"8ie-xW-0ye\">\n                    <rect key=\"frame\" x=\"20\" y=\"439\" width=\"441\" height=\"21\"/>\n                    <fontDescription key=\"fontDescription\" type=\"system\" pointSize=\"17\"/>\n                    <color key=\"textColor\" cocoaTouchSystemColor=\"darkTextColor\"/>\n                    <nil key=\"highlightedColor\"/>\n                </label>\n                <label opaque=\"NO\" clipsSubviews=\"YES\" userInteractionEnabled=\"NO\" contentMode=\"left\" horizontalHuggingPriority=\"251\" verticalHuggingPriority=\"251\" text=\"Autobahn\" textAlignment=\"center\" lineBreakMode=\"middleTruncation\" baselineAdjustment=\"alignBaselines\" minimumFontSize=\"18\" translatesAutoresizingMaskIntoConstraints=\"NO\" id=\"kId-c2-rCX\">\n                    <rect key=\"frame\" x=\"20\" y=\"140\" width=\"441\" height=\"43\"/>\n                    <fontDescription key=\"fontDescription\" type=\"boldSystem\" pointSize=\"36\"/>\n                    <color key=\"textColor\" cocoaTouchSystemColor=\"darkTextColor\"/>\n                    <nil key=\"highlightedColor\"/>\n                </label>\n            </subviews>\n            <color key=\"backgroundColor\" white=\"1\" alpha=\"1\" colorSpace=\"custom\" customColorSpace=\"calibratedWhite\"/>\n            <constraints>\n                <constraint firstItem=\"kId-c2-rCX\" firstAttribute=\"centerY\" secondItem=\"iN0-l3-epB\" secondAttribute=\"bottom\" multiplier=\"1/3\" constant=\"1\" id=\"5cJ-9S-tgC\"/>\n                <constraint firstAttribute=\"centerX\" secondItem=\"kId-c2-rCX\" secondAttribute=\"centerX\" id=\"Koa-jz-hwk\"/>\n                <constraint firstAttribute=\"bottom\" secondItem=\"8ie-xW-0ye\" secondAttribute=\"bottom\" constant=\"20\" id=\"Kzo-t9-V3l\"/>\n                <constraint firstItem=\"8ie-xW-0ye\" firstAttribute=\"leading\" secondItem=\"iN0-l3-epB\" secondAttribute=\"leading\" constant=\"20\" symbolic=\"YES\" id=\"MfP-vx-nX0\"/>\n                <constraint firstAttribute=\"centerX\" secondItem=\"8ie-xW-0ye\" secondAttribute=\"centerX\" id=\"ZEH-qu-HZ9\"/>\n                <constraint firstItem=\"kId-c2-rCX\" firstAttribute=\"leading\" secondItem=\"iN0-l3-epB\" secondAttribute=\"leading\" constant=\"20\" symbolic=\"YES\" id=\"fvb-Df-36g\"/>\n            </constraints>\n            <nil key=\"simulatedStatusBarMetrics\"/>\n            <freeformSimulatedSizeMetrics key=\"simulatedDestinationMetrics\"/>\n            <point key=\"canvasLocation\" x=\"548\" y=\"455\"/>\n        </view>\n    </objects>\n</document>\n"
  },
  {
    "path": "examples/AutobahnTest/Autobahn/Base.lproj/Main.storyboard",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n<document type=\"com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB\" version=\"3.0\" toolsVersion=\"9531\" systemVersion=\"15C50\" targetRuntime=\"iOS.CocoaTouch\" propertyAccessControl=\"none\" useAutolayout=\"YES\" useTraitCollections=\"YES\" initialViewController=\"BYZ-38-t0r\">\n    <dependencies>\n        <deployment identifier=\"iOS\"/>\n        <plugIn identifier=\"com.apple.InterfaceBuilder.IBCocoaTouchPlugin\" version=\"9529\"/>\n    </dependencies>\n    <scenes>\n        <!--View Controller-->\n        <scene sceneID=\"tne-QT-ifu\">\n            <objects>\n                <viewController id=\"BYZ-38-t0r\" customClass=\"ViewController\" customModule=\"Autobahn\" customModuleProvider=\"target\" sceneMemberID=\"viewController\">\n                    <layoutGuides>\n                        <viewControllerLayoutGuide type=\"top\" id=\"y3c-jy-aDJ\"/>\n                        <viewControllerLayoutGuide type=\"bottom\" id=\"wfy-db-euE\"/>\n                    </layoutGuides>\n                    <view key=\"view\" contentMode=\"scaleToFill\" id=\"8bC-Xf-vdC\">\n                        <rect key=\"frame\" x=\"0.0\" y=\"0.0\" width=\"600\" height=\"600\"/>\n                        <autoresizingMask key=\"autoresizingMask\" widthSizable=\"YES\" heightSizable=\"YES\"/>\n                        <color key=\"backgroundColor\" white=\"1\" alpha=\"1\" colorSpace=\"custom\" customColorSpace=\"calibratedWhite\"/>\n                    </view>\n                </viewController>\n                <placeholder placeholderIdentifier=\"IBFirstResponder\" id=\"dkx-z0-nzr\" sceneMemberID=\"firstResponder\"/>\n            </objects>\n        </scene>\n    </scenes>\n</document>\n"
  },
  {
    "path": "examples/AutobahnTest/Autobahn/Images.xcassets/AppIcon.appiconset/Contents.json",
    "content": "{\n  \"images\" : [\n    {\n      \"idiom\" : \"iphone\",\n      \"size\" : \"20x20\",\n      \"scale\" : \"2x\"\n    },\n    {\n      \"idiom\" : \"iphone\",\n      \"size\" : \"20x20\",\n      \"scale\" : \"3x\"\n    },\n    {\n      \"idiom\" : \"iphone\",\n      \"size\" : \"29x29\",\n      \"scale\" : \"2x\"\n    },\n    {\n      \"idiom\" : \"iphone\",\n      \"size\" : \"29x29\",\n      \"scale\" : \"3x\"\n    },\n    {\n      \"idiom\" : \"iphone\",\n      \"size\" : \"40x40\",\n      \"scale\" : \"2x\"\n    },\n    {\n      \"idiom\" : \"iphone\",\n      \"size\" : \"40x40\",\n      \"scale\" : \"3x\"\n    },\n    {\n      \"idiom\" : \"iphone\",\n      \"size\" : \"60x60\",\n      \"scale\" : \"2x\"\n    },\n    {\n      \"idiom\" : \"iphone\",\n      \"size\" : \"60x60\",\n      \"scale\" : \"3x\"\n    },\n    {\n      \"idiom\" : \"ipad\",\n      \"size\" : \"20x20\",\n      \"scale\" : \"1x\"\n    },\n    {\n      \"idiom\" : \"ipad\",\n      \"size\" : \"20x20\",\n      \"scale\" : \"2x\"\n    },\n    {\n      \"idiom\" : \"ipad\",\n      \"size\" : \"29x29\",\n      \"scale\" : \"1x\"\n    },\n    {\n      \"idiom\" : \"ipad\",\n      \"size\" : \"29x29\",\n      \"scale\" : \"2x\"\n    },\n    {\n      \"idiom\" : \"ipad\",\n      \"size\" : \"40x40\",\n      \"scale\" : \"1x\"\n    },\n    {\n      \"idiom\" : \"ipad\",\n      \"size\" : \"40x40\",\n      \"scale\" : \"2x\"\n    },\n    {\n      \"idiom\" : \"ipad\",\n      \"size\" : \"76x76\",\n      \"scale\" : \"1x\"\n    },\n    {\n      \"idiom\" : \"ipad\",\n      \"size\" : \"76x76\",\n      \"scale\" : \"2x\"\n    },\n    {\n      \"idiom\" : \"ipad\",\n      \"size\" : \"83.5x83.5\",\n      \"scale\" : \"2x\"\n    },\n    {\n      \"idiom\" : \"ios-marketing\",\n      \"size\" : \"1024x1024\",\n      \"scale\" : \"1x\"\n    }\n  ],\n  \"info\" : {\n    \"version\" : 1,\n    \"author\" : \"xcode\"\n  }\n}"
  },
  {
    "path": "examples/AutobahnTest/Autobahn/Info.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>CFBundleDevelopmentRegion</key>\n\t<string>en</string>\n\t<key>CFBundleExecutable</key>\n\t<string>$(EXECUTABLE_NAME)</string>\n\t<key>CFBundleIdentifier</key>\n\t<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>\n\t<key>CFBundleInfoDictionaryVersion</key>\n\t<string>6.0</string>\n\t<key>CFBundleName</key>\n\t<string>$(PRODUCT_NAME)</string>\n\t<key>CFBundlePackageType</key>\n\t<string>APPL</string>\n\t<key>CFBundleShortVersionString</key>\n\t<string>1.0</string>\n\t<key>CFBundleSignature</key>\n\t<string>????</string>\n\t<key>CFBundleVersion</key>\n\t<string>1</string>\n\t<key>LSRequiresIPhoneOS</key>\n\t<true/>\n\t<key>UILaunchStoryboardName</key>\n\t<string>LaunchScreen</string>\n\t<key>UIMainStoryboardFile</key>\n\t<string>Main</string>\n\t<key>UIRequiredDeviceCapabilities</key>\n\t<array>\n\t\t<string>armv7</string>\n\t</array>\n\t<key>UISupportedInterfaceOrientations</key>\n\t<array>\n\t\t<string>UIInterfaceOrientationPortrait</string>\n\t\t<string>UIInterfaceOrientationLandscapeLeft</string>\n\t\t<string>UIInterfaceOrientationLandscapeRight</string>\n\t</array>\n\t<key>UISupportedInterfaceOrientations~ipad</key>\n\t<array>\n\t\t<string>UIInterfaceOrientationPortrait</string>\n\t\t<string>UIInterfaceOrientationPortraitUpsideDown</string>\n\t\t<string>UIInterfaceOrientationLandscapeLeft</string>\n\t\t<string>UIInterfaceOrientationLandscapeRight</string>\n\t</array>\n</dict>\n</plist>\n"
  },
  {
    "path": "examples/AutobahnTest/Autobahn/ViewController.swift",
    "content": "//\n//  ViewController.swift\n//  Autobahn\n//\n//  Created by Dalton Cherry on 7/24/15.\n//  Copyright (c) 2015 vluxe. All rights reserved.\n//\n\nimport UIKit\nimport Starscream\n\nclass ViewController: UIViewController {\n    \n    let host = \"localhost:9001\"\n    var socketArray = [WebSocket]()\n    var caseCount = 300 //starting cases\n    override func viewDidLoad() {\n        super.viewDidLoad()\n        getCaseCount()\n        //getTestInfo(1)\n        //runTest(304)\n    }\n    \n    func removeSocket(_ s: WebSocket?) {\n        guard let s = s else {return}\n        socketArray = socketArray.filter{$0 !== s}\n    }\n    \n    func getCaseCount() {\n        let req = URLRequest(url: URL(string: \"ws://\\(host)/getCaseCount\")!)\n        let s = WebSocket(request: req)\n        socketArray.append(s)\n        s.onEvent = { [weak self] event in\n            switch event {\n            case .text(let string):\n                if let c = Int(string) {\n                    print(\"number of cases is: \\(c)\")\n                    self?.caseCount = c\n                }\n            case .disconnected(_, _):\n                self?.runTest(1)\n                self?.removeSocket(s)\n            default:\n                break\n            }\n        }\n        s.connect()\n    }\n    \n    func getTestInfo(_ caseNum: Int) {\n        let s = createSocket(\"getCaseInfo\",caseNum)\n        socketArray.append(s)\n//        s.onText = { (text: String) in\n//            let data = text.dataUsingEncoding(NSUTF8StringEncoding)\n//            do {\n//                let resp: AnyObject? = try NSJSONSerialization.JSONObjectWithData(data!,\n//                    options: NSJSONReadingOptions())\n//                if let dict = resp as? Dictionary<String,String> {\n//                    let num = dict[\"id\"]\n//                    let summary = dict[\"description\"]\n//                    if let n = num, let sum = summary {\n//                        print(\"running case:\\(caseNum) id:\\(n) summary: \\(sum)\")\n//                    }\n//                }\n//            } catch {\n//                print(\"error parsing the json\")\n//            }\n\n//        }\n        var once = false\n        s.onEvent = { [weak self] event in\n            switch event {\n            case .disconnected(_, _), .error(_):\n                if !once {\n                    once = true\n                    self?.runTest(caseNum)\n                }\n                self?.removeSocket(s)\n            default:\n                break\n            }\n        }\n        s.connect()\n    }\n    \n    func runTest(_ caseNum: Int) {\n        let s = createSocket(\"runCase\",caseNum)\n        self.socketArray.append(s)\n        \n        var once = false\n        s.onEvent = { [weak self, weak s] event in\n            switch event {\n            case .disconnected(_, _), .error(_):\n                if !once {\n                    once = true\n                    print(\"case:\\(caseNum) finished\")\n                    //self?.verifyTest(caseNum) //disabled since it slows down the tests\n                    let nextCase = caseNum+1\n                    if nextCase <= (self?.caseCount)! {\n                        self?.runTest(nextCase)\n                        //self?.getTestInfo(nextCase) //disabled since it slows down the tests\n                    } else {\n                        self?.finishReports()\n                    }\n                    self?.removeSocket(s)\n                }\n                self?.removeSocket(s)\n            case .text(let string):\n               s?.write(string: string)\n            case .binary(let data):\n               s?.write(data: data)\n//            case .error(let error):\n//                print(\"got an error: \\(error)\")\n            default:\n                break\n            }\n        }\n        s.connect()\n    }\n    \n//    func verifyTest(_ caseNum: Int) {\n//        let s = createSocket(\"getCaseStatus\",caseNum)\n//        self.socketArray.append(s)\n//        s.onText = { (text: String) in\n//            let data = text.data(using: String.Encoding.utf8)\n//            do {\n//                let resp: Any? = try JSONSerialization.jsonObject(with: data!,\n//                    options: JSONSerialization.ReadingOptions())\n//                if let dict = resp as? Dictionary<String,String> {\n//                    if let status = dict[\"behavior\"] {\n//                        if status == \"OK\" {\n//                            print(\"SUCCESS: \\(caseNum)\")\n//                            return\n//                        }\n//                    }\n//                    print(\"FAILURE: \\(caseNum)\")\n//                }\n//            } catch {\n//               print(\"error parsing the json\")\n//            }\n//        }\n//        var once = false\n//        s.onDisconnect = { [weak self, weak s]  (error: Error?) in\n//            if !once {\n//                once = true\n//                let nextCase = caseNum+1\n//                print(\"next test is: \\(nextCase)\")\n//                if nextCase <= (self?.caseCount)! {\n//                    self?.getTestInfo(nextCase)\n//                } else {\n//                    self?.finishReports()\n//                }\n//            }\n//            self?.removeSocket(s)\n//        }\n//        s.connect()\n//    }\n    \n    func finishReports() {\n        let s = createSocket(\"updateReports\",0)\n        self.socketArray.append(s)\n        s.onEvent = { [weak self, weak s] event in\n            switch event {\n            case .disconnected(_, _):\n                print(\"finished all the tests!\")\n                self?.removeSocket(s)\n            default:\n                break\n            }\n        }\n        s.connect()\n    }\n    \n    func createSocket(_ cmd: String, _ caseNum: Int) -> WebSocket {\n        let req = URLRequest(url: URL(string: \"ws://\\(host)\\(buildPath(cmd,caseNum))\")!)\n        //return WebSocket(request: req, compressionHandler: WSCompression())\n        return WebSocket(request: req)\n    }\n    \n    func buildPath(_ cmd: String, _ caseNum: Int) -> String {\n        return \"/\\(cmd)?case=\\(caseNum)&agent=Starscream\"\n    }\n}\n\n"
  },
  {
    "path": "examples/SimpleTest/.gitignore",
    "content": "# CocoaPods\n#\n# We recommend against adding the Pods directory to your .gitignore. However\n# you should judge for yourself, the pros and cons are mentioned at:\n# http://guides.cocoapods.org/using/using-cocoapods.html#should-i-ignore-the-pods-directory-in-source-control?\n#\n# Pods/\n\n# Xcode\n.DS_Store\nbuild\n*.pbxuser\n!default.pbxuser\n*.mode1v3\n!default.mode1v3\n*.mode2v3\n!default.mode2v3\n*.perspectivev3\n!default.perspectivev3\nxcuserdata\nprofile\n*.moved-aside\nDerivedData\n.idea/\n*.hmap\n*.xccheckout\n*.xcodeproj/*.xcworkspace"
  },
  {
    "path": "examples/SimpleTest/README.md",
    "content": "# Simple Test\n\nThis is a very simple example on how to use Starscream.\n\n# Usage\n\nFirst make sure you have the gem dependencies of websocket server.\n\n```\ngem install em-websocket\ngem install faker\n```\n\nNext simply run:\n\n```\nruby ws-server.rb\n```\n\nAfter that, start and run the xCode project. Echo to your heart's desire."
  },
  {
    "path": "examples/SimpleTest/SimpleTest/AppDelegate.swift",
    "content": "//////////////////////////////////////////////////////////////////////////////////////////////////\n//\n//  AppDelegate.swift\n//  SimpleTest\n//\n//  Created by Dalton Cherry on 8/12/14.\n//  Copyright © 2014 Vluxe. All rights reserved.\n//\n//  Licensed under the Apache License, Version 2.0 (the \"License\");\n//  you may not use this file except in compliance with the License.\n//  You may obtain a copy of the License at\n//\n//  http://www.apache.org/licenses/LICENSE-2.0\n//\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n//\n//////////////////////////////////////////////////////////////////////////////////////////////////\n\nimport UIKit\n\n@UIApplicationMain\nclass AppDelegate: UIResponder, UIApplicationDelegate {\n                            \n    var window: UIWindow?\n\n\n    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {\n        // Override point for customization after application launch.\n        return true\n    }\n\n    func applicationWillResignActive(_ application: UIApplication) {\n        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.\n        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.\n    }\n\n    func applicationDidEnterBackground(_ application: UIApplication) {\n        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.\n        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.\n    }\n\n    func applicationWillEnterForeground(_ application: UIApplication) {\n        // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.\n    }\n\n    func applicationDidBecomeActive(_ application: UIApplication) {\n        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.\n    }\n\n    func applicationWillTerminate(_ application: UIApplication) {\n        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.\n    }\n\n\n}\n\n"
  },
  {
    "path": "examples/SimpleTest/SimpleTest/Base.lproj/Main.storyboard",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n<document type=\"com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB\" version=\"3.0\" toolsVersion=\"6245\" systemVersion=\"13E28\" targetRuntime=\"iOS.CocoaTouch\" propertyAccessControl=\"none\" useAutolayout=\"YES\" useTraitCollections=\"YES\" initialViewController=\"gXF-XR-CbL\">\n    <dependencies>\n        <plugIn identifier=\"com.apple.InterfaceBuilder.IBCocoaTouchPlugin\" version=\"6238\"/>\n    </dependencies>\n    <scenes>\n        <!--Navigation Controller-->\n        <scene sceneID=\"z5V-aR-Hjx\">\n            <objects>\n                <navigationController id=\"gXF-XR-CbL\" sceneMemberID=\"viewController\">\n                    <navigationBar key=\"navigationBar\" contentMode=\"scaleToFill\" id=\"D35-o5-RTx\">\n                        <rect key=\"frame\" x=\"0.0\" y=\"0.0\" width=\"320\" height=\"44\"/>\n                        <autoresizingMask key=\"autoresizingMask\"/>\n                    </navigationBar>\n                    <connections>\n                        <segue destination=\"N3B-eU-fDA\" kind=\"relationship\" relationship=\"rootViewController\" id=\"2Dx-au-NvB\"/>\n                    </connections>\n                </navigationController>\n                <placeholder placeholderIdentifier=\"IBFirstResponder\" id=\"sXu-Hp-mO4\" userLabel=\"First Responder\" sceneMemberID=\"firstResponder\"/>\n            </objects>\n            <point key=\"canvasLocation\" x=\"-646\" y=\"295\"/>\n        </scene>\n        <!--Test-->\n        <scene sceneID=\"d1c-mj-3av\">\n            <objects>\n                <viewController id=\"N3B-eU-fDA\" customClass=\"ViewController\" customModule=\"SimpleTest\" customModuleProvider=\"target\" sceneMemberID=\"viewController\">\n                    <layoutGuides>\n                        <viewControllerLayoutGuide type=\"top\" id=\"AfF-mb-jqd\"/>\n                        <viewControllerLayoutGuide type=\"bottom\" id=\"ZA3-Ac-gEF\"/>\n                    </layoutGuides>\n                    <view key=\"view\" contentMode=\"scaleToFill\" id=\"Sgl-3h-sU4\">\n                        <rect key=\"frame\" x=\"0.0\" y=\"0.0\" width=\"600\" height=\"600\"/>\n                        <autoresizingMask key=\"autoresizingMask\" widthSizable=\"YES\" heightSizable=\"YES\"/>\n                        <color key=\"backgroundColor\" white=\"1\" alpha=\"1\" colorSpace=\"calibratedWhite\"/>\n                    </view>\n                    <navigationItem key=\"navigationItem\" title=\"Test\" id=\"jdv-zM-Apy\">\n                        <barButtonItem key=\"leftBarButtonItem\" title=\"Disconnect\" id=\"ByR-Ln-P6Z\">\n                            <connections>\n                                <action selector=\"disconnect:\" destination=\"N3B-eU-fDA\" id=\"k8L-AE-Ini\"/>\n                            </connections>\n                        </barButtonItem>\n                        <barButtonItem key=\"rightBarButtonItem\" title=\"Write Text\" id=\"gjf-vP-Wu5\">\n                            <connections>\n                                <action selector=\"writeText:\" destination=\"N3B-eU-fDA\" id=\"fyJ-Ys-gvh\"/>\n                            </connections>\n                        </barButtonItem>\n                    </navigationItem>\n                </viewController>\n                <placeholder placeholderIdentifier=\"IBFirstResponder\" id=\"zrK-cf-cjD\" userLabel=\"First Responder\" sceneMemberID=\"firstResponder\"/>\n            </objects>\n            <point key=\"canvasLocation\" x=\"175\" y=\"295\"/>\n        </scene>\n    </scenes>\n</document>\n"
  },
  {
    "path": "examples/SimpleTest/SimpleTest/Images.xcassets/AppIcon.appiconset/Contents.json",
    "content": "{\n  \"images\" : [\n    {\n      \"idiom\" : \"iphone\",\n      \"size\" : \"29x29\",\n      \"scale\" : \"2x\"\n    },\n    {\n      \"idiom\" : \"iphone\",\n      \"size\" : \"40x40\",\n      \"scale\" : \"2x\"\n    },\n    {\n      \"idiom\" : \"iphone\",\n      \"size\" : \"60x60\",\n      \"scale\" : \"2x\"\n    },\n    {\n      \"idiom\" : \"iphone\",\n      \"size\" : \"60x60\",\n      \"scale\" : \"3x\"\n    },\n    {\n      \"idiom\" : \"ipad\",\n      \"size\" : \"29x29\",\n      \"scale\" : \"1x\"\n    },\n    {\n      \"idiom\" : \"ipad\",\n      \"size\" : \"29x29\",\n      \"scale\" : \"2x\"\n    },\n    {\n      \"idiom\" : \"ipad\",\n      \"size\" : \"40x40\",\n      \"scale\" : \"1x\"\n    },\n    {\n      \"idiom\" : \"ipad\",\n      \"size\" : \"40x40\",\n      \"scale\" : \"2x\"\n    },\n    {\n      \"idiom\" : \"ipad\",\n      \"size\" : \"76x76\",\n      \"scale\" : \"1x\"\n    },\n    {\n      \"idiom\" : \"ipad\",\n      \"size\" : \"76x76\",\n      \"scale\" : \"2x\"\n    }\n  ],\n  \"info\" : {\n    \"version\" : 1,\n    \"author\" : \"xcode\"\n  }\n}"
  },
  {
    "path": "examples/SimpleTest/SimpleTest/Images.xcassets/LaunchImage.launchimage/Contents.json",
    "content": "{\n  \"images\" : [\n    {\n      \"orientation\" : \"portrait\",\n      \"idiom\" : \"iphone\",\n      \"extent\" : \"full-screen\",\n      \"minimum-system-version\" : \"7.0\",\n      \"scale\" : \"2x\"\n    },\n    {\n      \"orientation\" : \"portrait\",\n      \"idiom\" : \"iphone\",\n      \"subtype\" : \"retina4\",\n      \"extent\" : \"full-screen\",\n      \"minimum-system-version\" : \"7.0\",\n      \"scale\" : \"2x\"\n    },\n    {\n      \"orientation\" : \"portrait\",\n      \"idiom\" : \"ipad\",\n      \"extent\" : \"full-screen\",\n      \"minimum-system-version\" : \"7.0\",\n      \"scale\" : \"1x\"\n    },\n    {\n      \"orientation\" : \"landscape\",\n      \"idiom\" : \"ipad\",\n      \"extent\" : \"full-screen\",\n      \"minimum-system-version\" : \"7.0\",\n      \"scale\" : \"1x\"\n    },\n    {\n      \"orientation\" : \"portrait\",\n      \"idiom\" : \"ipad\",\n      \"extent\" : \"full-screen\",\n      \"minimum-system-version\" : \"7.0\",\n      \"scale\" : \"2x\"\n    },\n    {\n      \"orientation\" : \"landscape\",\n      \"idiom\" : \"ipad\",\n      \"extent\" : \"full-screen\",\n      \"minimum-system-version\" : \"7.0\",\n      \"scale\" : \"2x\"\n    }\n  ],\n  \"info\" : {\n    \"version\" : 1,\n    \"author\" : \"xcode\"\n  }\n}"
  },
  {
    "path": "examples/SimpleTest/SimpleTest/Info.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>CFBundleDevelopmentRegion</key>\n\t<string>en</string>\n\t<key>CFBundleExecutable</key>\n\t<string>$(EXECUTABLE_NAME)</string>\n\t<key>CFBundleIdentifier</key>\n\t<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>\n\t<key>CFBundleInfoDictionaryVersion</key>\n\t<string>6.0</string>\n\t<key>CFBundleName</key>\n\t<string>$(PRODUCT_NAME)</string>\n\t<key>CFBundlePackageType</key>\n\t<string>APPL</string>\n\t<key>CFBundleShortVersionString</key>\n\t<string>1.0</string>\n\t<key>CFBundleSignature</key>\n\t<string>????</string>\n\t<key>CFBundleVersion</key>\n\t<string>1</string>\n\t<key>LSRequiresIPhoneOS</key>\n\t<true/>\n\t<key>NSAppTransportSecurity</key>\n\t<dict>\n\t\t<key>NSAllowsArbitraryLoads</key>\n\t\t<true/>\n\t</dict>\n\t<key>UIMainStoryboardFile</key>\n\t<string>Main</string>\n\t<key>UIRequiredDeviceCapabilities</key>\n\t<array>\n\t\t<string>armv7</string>\n\t</array>\n\t<key>UISupportedInterfaceOrientations</key>\n\t<array>\n\t\t<string>UIInterfaceOrientationPortrait</string>\n\t\t<string>UIInterfaceOrientationLandscapeLeft</string>\n\t\t<string>UIInterfaceOrientationLandscapeRight</string>\n\t</array>\n\t<key>UISupportedInterfaceOrientations~ipad</key>\n\t<array>\n\t\t<string>UIInterfaceOrientationPortrait</string>\n\t\t<string>UIInterfaceOrientationPortraitUpsideDown</string>\n\t\t<string>UIInterfaceOrientationLandscapeLeft</string>\n\t\t<string>UIInterfaceOrientationLandscapeRight</string>\n\t</array>\n</dict>\n</plist>\n"
  },
  {
    "path": "examples/SimpleTest/SimpleTest/ViewController.swift",
    "content": "//////////////////////////////////////////////////////////////////////////////////////////////////\n//\n//  ViewController.swift\n//  SimpleTest\n//\n//  Created by Dalton Cherry on 8/12/14.\n//  Copyright © 2014 Vluxe. All rights reserved.\n//\n//  Licensed under the Apache License, Version 2.0 (the \"License\");\n//  you may not use this file except in compliance with the License.\n//  You may obtain a copy of the License at\n//\n//  http://www.apache.org/licenses/LICENSE-2.0\n//\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n//\n//////////////////////////////////////////////////////////////////////////////////////////////////\n\nimport UIKit\nimport Starscream\n\nclass ViewController: UIViewController, WebSocketDelegate {\n    var socket: WebSocket!\n    var isConnected = false\n    let server = WebSocketServer()\n    \n    override func viewDidLoad() {\n        super.viewDidLoad()\n        //https://echo.websocket.org\n        var request = URLRequest(url: URL(string: \"http://localhost:8080\")!) //https://localhost:8080\n        request.timeoutInterval = 5\n        socket = WebSocket(request: request)\n        socket.delegate = self\n        socket.connect()\n    }\n    \n    // MARK: - WebSocketDelegate\n    func didReceive(event: Starscream.WebSocketEvent, client: Starscream.WebSocketClient) {\n        switch event {\n        case .connected(let headers):\n            isConnected = true\n            print(\"websocket is connected: \\(headers)\")\n        case .disconnected(let reason, let code):\n            isConnected = false\n            print(\"websocket is disconnected: \\(reason) with code: \\(code)\")\n        case .text(let string):\n            print(\"Received text: \\(string)\")\n        case .binary(let data):\n            print(\"Received data: \\(data.count)\")\n        case .ping(_):\n            break\n        case .pong(_):\n            break\n        case .viabilityChanged(_):\n            break\n        case .reconnectSuggested(_):\n            break\n        case .cancelled:\n            isConnected = false\n        case .error(let error):\n            isConnected = false\n            handleError(error)\n        case .peerClosed:\n            break\n        }\n    }\n    \n    func handleError(_ error: Error?) {\n        if let e = error as? WSError {\n            print(\"websocket encountered an error: \\(e.message)\")\n        } else if let e = error {\n            print(\"websocket encountered an error: \\(e.localizedDescription)\")\n        } else {\n            print(\"websocket encountered an error\")\n        }\n    }\n    \n    // MARK: Write Text Action\n    \n    @IBAction func writeText(_ sender: UIBarButtonItem) {\n        socket.write(string: \"hello there!\")\n    }\n    \n    // MARK: Disconnect Action\n    \n    @IBAction func disconnect(_ sender: UIBarButtonItem) {\n        if isConnected {\n            sender.title = \"Connect\"\n            socket.disconnect()\n        } else {\n            sender.title = \"Disconnect\"\n            socket.connect()\n        }\n    }\n    \n}\n\n"
  },
  {
    "path": "examples/SimpleTest/ws-server.rb",
    "content": "require 'em-websocket'\nrequire 'faker'\n\nEM.run {\n  EM::WebSocket.run(:host => \"0.0.0.0\", :port => 8080) do |ws|\n    ws.onopen { |handshake|\n      puts \"WebSocket connection open\"\n      puts \"origin: #{handshake.origin}\"\n      puts \"headers: #{handshake.headers}\"\n\n      ws.send \"Hello Client, you connected to #{handshake.path}\"\n    }\n\n    ws.onerror do |error|\n      puts \"[error] #{error}\"\n    end\n\n    ws.onclose { puts \"Connection closed\" }\n\n    ws.onmessage { |msg|\n      puts \"message from client: #{msg}\"\n      ws.send +Faker::Hacker.say_something_smart\n    }\n  end\n}\n"
  },
  {
    "path": "examples/WebSocketsOrgEcho/Podfile",
    "content": "# Uncomment the next line to define a global platform for your project\n# platform :ios, '9.0'\n\ntarget 'WebSocketsOrgEcho' do\n  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks\n  use_frameworks!\n\n  # Pods for WebSocketsOrgEcho\n  \n  pod 'Starscream', :path => '../../'\nend\n"
  },
  {
    "path": "examples/WebSocketsOrgEcho/WebSocketsOrgEcho/AppDelegate.swift",
    "content": "//\n//  AppDelegate.swift\n//  WebSocketsOrgEcho\n//\n//  Created by Kristaps Grinbergs on 08/10/2018.\n//  Copyright © 2018 Starscream. All rights reserved.\n//\n\nimport UIKit\n\n@UIApplicationMain\nclass AppDelegate: UIResponder, UIApplicationDelegate {\n    \n    var window: UIWindow?\n    \n    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {\n        return true\n    }\n    \n}\n\n"
  },
  {
    "path": "examples/WebSocketsOrgEcho/WebSocketsOrgEcho/Assets.xcassets/AppIcon.appiconset/Contents.json",
    "content": "{\n  \"images\" : [\n    {\n      \"idiom\" : \"iphone\",\n      \"size\" : \"20x20\",\n      \"scale\" : \"2x\"\n    },\n    {\n      \"idiom\" : \"iphone\",\n      \"size\" : \"20x20\",\n      \"scale\" : \"3x\"\n    },\n    {\n      \"idiom\" : \"iphone\",\n      \"size\" : \"29x29\",\n      \"scale\" : \"2x\"\n    },\n    {\n      \"idiom\" : \"iphone\",\n      \"size\" : \"29x29\",\n      \"scale\" : \"3x\"\n    },\n    {\n      \"idiom\" : \"iphone\",\n      \"size\" : \"40x40\",\n      \"scale\" : \"2x\"\n    },\n    {\n      \"idiom\" : \"iphone\",\n      \"size\" : \"40x40\",\n      \"scale\" : \"3x\"\n    },\n    {\n      \"idiom\" : \"iphone\",\n      \"size\" : \"60x60\",\n      \"scale\" : \"2x\"\n    },\n    {\n      \"idiom\" : \"iphone\",\n      \"size\" : \"60x60\",\n      \"scale\" : \"3x\"\n    },\n    {\n      \"idiom\" : \"ipad\",\n      \"size\" : \"20x20\",\n      \"scale\" : \"1x\"\n    },\n    {\n      \"idiom\" : \"ipad\",\n      \"size\" : \"20x20\",\n      \"scale\" : \"2x\"\n    },\n    {\n      \"idiom\" : \"ipad\",\n      \"size\" : \"29x29\",\n      \"scale\" : \"1x\"\n    },\n    {\n      \"idiom\" : \"ipad\",\n      \"size\" : \"29x29\",\n      \"scale\" : \"2x\"\n    },\n    {\n      \"idiom\" : \"ipad\",\n      \"size\" : \"40x40\",\n      \"scale\" : \"1x\"\n    },\n    {\n      \"idiom\" : \"ipad\",\n      \"size\" : \"40x40\",\n      \"scale\" : \"2x\"\n    },\n    {\n      \"idiom\" : \"ipad\",\n      \"size\" : \"76x76\",\n      \"scale\" : \"1x\"\n    },\n    {\n      \"idiom\" : \"ipad\",\n      \"size\" : \"76x76\",\n      \"scale\" : \"2x\"\n    },\n    {\n      \"idiom\" : \"ipad\",\n      \"size\" : \"83.5x83.5\",\n      \"scale\" : \"2x\"\n    },\n    {\n      \"idiom\" : \"ios-marketing\",\n      \"size\" : \"1024x1024\",\n      \"scale\" : \"1x\"\n    }\n  ],\n  \"info\" : {\n    \"version\" : 1,\n    \"author\" : \"xcode\"\n  }\n}"
  },
  {
    "path": "examples/WebSocketsOrgEcho/WebSocketsOrgEcho/Assets.xcassets/Contents.json",
    "content": "{\n  \"info\" : {\n    \"version\" : 1,\n    \"author\" : \"xcode\"\n  }\n}"
  },
  {
    "path": "examples/WebSocketsOrgEcho/WebSocketsOrgEcho/Base.lproj/LaunchScreen.storyboard",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n<document type=\"com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB\" version=\"3.0\" toolsVersion=\"13122.16\" targetRuntime=\"iOS.CocoaTouch\" propertyAccessControl=\"none\" useAutolayout=\"YES\" launchScreen=\"YES\" useTraitCollections=\"YES\" useSafeAreas=\"YES\" colorMatched=\"YES\" initialViewController=\"01J-lp-oVM\">\n    <dependencies>\n        <plugIn identifier=\"com.apple.InterfaceBuilder.IBCocoaTouchPlugin\" version=\"13104.12\"/>\n        <capability name=\"Safe area layout guides\" minToolsVersion=\"9.0\"/>\n        <capability name=\"documents saved in the Xcode 8 format\" minToolsVersion=\"8.0\"/>\n    </dependencies>\n    <scenes>\n        <!--View Controller-->\n        <scene sceneID=\"EHf-IW-A2E\">\n            <objects>\n                <viewController id=\"01J-lp-oVM\" sceneMemberID=\"viewController\">\n                    <view key=\"view\" contentMode=\"scaleToFill\" id=\"Ze5-6b-2t3\">\n                        <rect key=\"frame\" x=\"0.0\" y=\"0.0\" width=\"375\" height=\"667\"/>\n                        <autoresizingMask key=\"autoresizingMask\" widthSizable=\"YES\" heightSizable=\"YES\"/>\n                        <color key=\"backgroundColor\" red=\"1\" green=\"1\" blue=\"1\" alpha=\"1\" colorSpace=\"custom\" customColorSpace=\"sRGB\"/>\n                        <viewLayoutGuide key=\"safeArea\" id=\"6Tk-OE-BBY\"/>\n                    </view>\n                </viewController>\n                <placeholder placeholderIdentifier=\"IBFirstResponder\" id=\"iYj-Kq-Ea1\" userLabel=\"First Responder\" sceneMemberID=\"firstResponder\"/>\n            </objects>\n            <point key=\"canvasLocation\" x=\"53\" y=\"375\"/>\n        </scene>\n    </scenes>\n</document>\n"
  },
  {
    "path": "examples/WebSocketsOrgEcho/WebSocketsOrgEcho/Base.lproj/Main.storyboard",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<document type=\"com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB\" version=\"3.0\" toolsVersion=\"14313.18\" targetRuntime=\"iOS.CocoaTouch\" propertyAccessControl=\"none\" useAutolayout=\"YES\" useTraitCollections=\"YES\" useSafeAreas=\"YES\" colorMatched=\"YES\" initialViewController=\"BYZ-38-t0r\">\n    <device id=\"retina4_7\" orientation=\"portrait\">\n        <adaptation id=\"fullscreen\"/>\n    </device>\n    <dependencies>\n        <plugIn identifier=\"com.apple.InterfaceBuilder.IBCocoaTouchPlugin\" version=\"14283.14\"/>\n        <capability name=\"Safe area layout guides\" minToolsVersion=\"9.0\"/>\n        <capability name=\"documents saved in the Xcode 8 format\" minToolsVersion=\"8.0\"/>\n    </dependencies>\n    <scenes>\n        <!--View Controller-->\n        <scene sceneID=\"tne-QT-ifu\">\n            <objects>\n                <viewController id=\"BYZ-38-t0r\" customClass=\"ViewController\" customModule=\"WebSocketsOrgEcho\" customModuleProvider=\"target\" sceneMemberID=\"viewController\">\n                    <view key=\"view\" contentMode=\"scaleToFill\" id=\"8bC-Xf-vdC\">\n                        <rect key=\"frame\" x=\"0.0\" y=\"0.0\" width=\"375\" height=\"667\"/>\n                        <autoresizingMask key=\"autoresizingMask\" widthSizable=\"YES\" heightSizable=\"YES\"/>\n                        <subviews>\n                            <button opaque=\"NO\" contentMode=\"scaleToFill\" contentHorizontalAlignment=\"center\" contentVerticalAlignment=\"center\" buttonType=\"roundedRect\" lineBreakMode=\"middleTruncation\" translatesAutoresizingMaskIntoConstraints=\"NO\" id=\"ysb-Wt-xJQ\">\n                                <rect key=\"frame\" x=\"158\" y=\"318.5\" width=\"59\" height=\"30\"/>\n                                <state key=\"normal\" title=\"Connect\"/>\n                                <connections>\n                                    <action selector=\"connect:\" destination=\"BYZ-38-t0r\" eventType=\"touchUpInside\" id=\"JK8-oU-5uC\"/>\n                                </connections>\n                            </button>\n                        </subviews>\n                        <color key=\"backgroundColor\" red=\"1\" green=\"1\" blue=\"1\" alpha=\"1\" colorSpace=\"custom\" customColorSpace=\"sRGB\"/>\n                        <constraints>\n                            <constraint firstItem=\"ysb-Wt-xJQ\" firstAttribute=\"centerX\" secondItem=\"8bC-Xf-vdC\" secondAttribute=\"centerX\" id=\"2YK-eB-LZR\"/>\n                            <constraint firstItem=\"ysb-Wt-xJQ\" firstAttribute=\"centerY\" secondItem=\"8bC-Xf-vdC\" secondAttribute=\"centerY\" id=\"iGG-QS-5FX\"/>\n                        </constraints>\n                        <viewLayoutGuide key=\"safeArea\" id=\"6Tk-OE-BBY\"/>\n                    </view>\n                </viewController>\n                <placeholder placeholderIdentifier=\"IBFirstResponder\" id=\"dkx-z0-nzr\" sceneMemberID=\"firstResponder\"/>\n            </objects>\n        </scene>\n    </scenes>\n</document>\n"
  },
  {
    "path": "examples/WebSocketsOrgEcho/WebSocketsOrgEcho/Info.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>CFBundleDevelopmentRegion</key>\n\t<string>$(DEVELOPMENT_LANGUAGE)</string>\n\t<key>CFBundleExecutable</key>\n\t<string>$(EXECUTABLE_NAME)</string>\n\t<key>CFBundleIdentifier</key>\n\t<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>\n\t<key>CFBundleInfoDictionaryVersion</key>\n\t<string>6.0</string>\n\t<key>CFBundleName</key>\n\t<string>$(PRODUCT_NAME)</string>\n\t<key>CFBundlePackageType</key>\n\t<string>APPL</string>\n\t<key>CFBundleShortVersionString</key>\n\t<string>1.0</string>\n\t<key>CFBundleVersion</key>\n\t<string>1</string>\n\t<key>LSRequiresIPhoneOS</key>\n\t<true/>\n\t<key>UILaunchStoryboardName</key>\n\t<string>LaunchScreen</string>\n\t<key>UIMainStoryboardFile</key>\n\t<string>Main</string>\n\t<key>UIRequiredDeviceCapabilities</key>\n\t<array>\n\t\t<string>armv7</string>\n\t</array>\n\t<key>UISupportedInterfaceOrientations</key>\n\t<array>\n\t\t<string>UIInterfaceOrientationPortrait</string>\n\t\t<string>UIInterfaceOrientationLandscapeLeft</string>\n\t\t<string>UIInterfaceOrientationLandscapeRight</string>\n\t</array>\n\t<key>UISupportedInterfaceOrientations~ipad</key>\n\t<array>\n\t\t<string>UIInterfaceOrientationPortrait</string>\n\t\t<string>UIInterfaceOrientationPortraitUpsideDown</string>\n\t\t<string>UIInterfaceOrientationLandscapeLeft</string>\n\t\t<string>UIInterfaceOrientationLandscapeRight</string>\n\t</array>\n</dict>\n</plist>\n"
  },
  {
    "path": "examples/WebSocketsOrgEcho/WebSocketsOrgEcho/URL+Extensions.swift",
    "content": "//\n//  URL+Extensions.swift\n//  Example\n//\n//  Created by Kristaps Grinbergs on 08/10/2018.\n//  Copyright © 2018 Kristaps Grinbergs. All rights reserved.\n//\n\nimport Foundation\n\nextension URL {\n    init(staticString string: StaticString) {\n        guard let url = URL(string: \"\\(string)\") else {\n            preconditionFailure(\"Invalid static URL string: \\(string)\")\n        }\n        \n        self = url\n    }\n}\n"
  },
  {
    "path": "examples/WebSocketsOrgEcho/WebSocketsOrgEcho/ViewController.swift",
    "content": "//\n//  ViewController.swift\n//  WebSocketsOrgEcho\n//\n//  Created by Kristaps Grinbergs on 08/10/2018.\n//  Copyright © 2018 Starscream. All rights reserved.\n//\n\nimport UIKit\n\nimport Starscream\n\nclass ViewController: UIViewController, WebSocketDelegate {\n    \n    var socket: WebSocket = WebSocket(url: URL(staticString: \"wss://echo.websocket.org\"))\n    \n    func websocketDidConnect(socket: WebSocketClient) {\n        print(\"websocketDidConnect\")\n    }\n    \n    func websocketDidDisconnect(socket: WebSocketClient, error: Error?) {\n        print(\"websocketDidDisconnect\", error ?? \"\")\n    }\n    \n    func websocketDidReceiveMessage(socket: WebSocketClient, text: String) {\n        print(\"websocketDidReceiveMessage\", text)\n    }\n    \n    func websocketDidReceiveData(socket: WebSocketClient, data: Data) {\n        print(\"websocketDidReceiveData\", data)\n    }\n    \n    override func viewDidLoad() {\n        super.viewDidLoad()\n        \n        socket.delegate = self\n    }\n    \n    @IBAction func connect(_ sender: Any) {\n        socket.connect()\n    }\n}\n"
  },
  {
    "path": "examples/WebSocketsOrgEcho/WebSocketsOrgEcho.xcworkspace/contents.xcworkspacedata",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Workspace\n   version = \"1.0\">\n   <FileRef\n      location = \"group:WebSocketsOrgEcho.xcodeproj\">\n   </FileRef>\n   <FileRef\n      location = \"group:Pods/Pods.xcodeproj\">\n   </FileRef>\n</Workspace>\n"
  },
  {
    "path": "examples/WebSocketsOrgEcho/WebSocketsOrgEcho.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>IDEDidComputeMac32BitWarning</key>\n\t<true/>\n</dict>\n</plist>\n"
  },
  {
    "path": "fastlane/Fastfile",
    "content": "default_platform(:ios)\n\nupdate_fastlane\n\n\ndesc \"Run tests\"\nlane :test do\n  run_tests(\n    devices: [\"iPhone 14 Pro\", \"iPad Pro (11-inch) (4th generation)\"],\n  )\nend\n\nplatform :ios do\n  desc \"Deploy new version\"\n  lane :release do\n    version = version_bump_podspec(path: \"Starscream.podspec\", version_number: ENV[\"TAG\"])\n    changelog = changelog_from_git_commits(merge_commit_filtering: \"exclude_merges\")\n\n    github_release = set_github_release(\n      repository_name: \"daltoniam/starscream\",\n      api_token: ENV[\"GITHUB_TOKEN\"],\n      name: version,\n      tag_name: version,\n      description: changelog,\n      commitish: \"master\"\n    )\n    pod_push(allow_warnings: false, verbose: true)\n  end\nend\n"
  },
  {
    "path": "fastlane/README.md",
    "content": "fastlane documentation\n----\n\n# Installation\n\nMake sure you have the latest version of the Xcode command line tools installed:\n\n```sh\nxcode-select --install\n```\n\nFor _fastlane_ installation instructions, see [Installing _fastlane_](https://docs.fastlane.tools/#installing-fastlane)\n\n# Available Actions\n\n### test\n\n```sh\n[bundle exec] fastlane test\n```\n\nRun tests\n\n----\n\n\n## iOS\n\n### ios release\n\n```sh\n[bundle exec] fastlane ios release\n```\n\nDeploy new version\n\n----\n\nThis README.md is auto-generated and will be re-generated every time [_fastlane_](https://fastlane.tools) is run.\n\nMore information about _fastlane_ can be found on [fastlane.tools](https://fastlane.tools).\n\nThe documentation of _fastlane_ can be found on [docs.fastlane.tools](https://docs.fastlane.tools).\n"
  }
]