pingerchips-js 1.0.0-a

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (434) hide show
  1. package/.editorconfig +14 -0
  2. package/.github/ISSUE_TEMPLATE.md +11 -0
  3. package/.github/PULL_REQUEST_TEMPLATE.md +14 -0
  4. package/.github/dependabot.yml +14 -0
  5. package/.github/stale.yml +26 -0
  6. package/.github/workflows/release.yml +112 -0
  7. package/.github/workflows/release_pr.yml +43 -0
  8. package/.github/workflows/run-tests.yml +62 -0
  9. package/.gitmodules +3 -0
  10. package/.prettierrc +2 -0
  11. package/CHANGELOG.md +924 -0
  12. package/LICENCE +19 -0
  13. package/Makefile +78 -0
  14. package/README.md +707 -0
  15. package/bower.json +28 -0
  16. package/dist/node/pusher.js +10870 -0
  17. package/dist/node/pusher.js.map +1 -0
  18. package/dist/react-native/pusher.js +9 -0
  19. package/dist/react-native/pusher.js.map +1 -0
  20. package/dist/web/json2.js +486 -0
  21. package/dist/web/json2.min.js +1 -0
  22. package/dist/web/pusher-with-encryption.js +7009 -0
  23. package/dist/web/pusher-with-encryption.js.map +1 -0
  24. package/dist/web/pusher-with-encryption.min.js +9 -0
  25. package/dist/web/pusher-with-encryption.min.js.map +1 -0
  26. package/dist/web/pusher.js +4587 -0
  27. package/dist/web/pusher.js.map +1 -0
  28. package/dist/web/pusher.min.js +9 -0
  29. package/dist/web/pusher.min.js.map +1 -0
  30. package/dist/web/sockjs.js +2435 -0
  31. package/dist/web/sockjs.min.js +89 -0
  32. package/dist/worker/pusher-with-encryption.worker.js +6622 -0
  33. package/dist/worker/pusher-with-encryption.worker.js.map +1 -0
  34. package/dist/worker/pusher-with-encryption.worker.min.js +9 -0
  35. package/dist/worker/pusher-with-encryption.worker.min.js.map +1 -0
  36. package/dist/worker/pusher.worker.js +4200 -0
  37. package/dist/worker/pusher.worker.js.map +1 -0
  38. package/dist/worker/pusher.worker.min.js +9 -0
  39. package/dist/worker/pusher.worker.min.js.map +1 -0
  40. package/index.d.ts +29 -0
  41. package/integration_tests_server/index.js +176 -0
  42. package/integration_tests_server/package-lock.json +1177 -0
  43. package/integration_tests_server/package.json +15 -0
  44. package/node.js +1 -0
  45. package/package.json +70 -0
  46. package/pusher-with-encryption/index.js +1 -0
  47. package/react-native/index.d.ts +29 -0
  48. package/react-native/index.js +1 -0
  49. package/spec/config/jasmine/helpers/reporter.js +14 -0
  50. package/spec/config/jasmine/integration.json +13 -0
  51. package/spec/config/jasmine/unit.json +13 -0
  52. package/spec/config/jasmine/webpack.integration.js +33 -0
  53. package/spec/config/jasmine/webpack.unit.js +30 -0
  54. package/spec/config/karma/available_browsers.json +4957 -0
  55. package/spec/config/karma/config.ci.js +25 -0
  56. package/spec/config/karma/config.common.js +50 -0
  57. package/spec/config/karma/config.integration.js +26 -0
  58. package/spec/config/karma/config.unit.js +10 -0
  59. package/spec/config/karma/config.worker.js +34 -0
  60. package/spec/config/karma/integration.js +24 -0
  61. package/spec/config/karma/unit.js +20 -0
  62. package/spec/javascripts/helpers/mocks.js +274 -0
  63. package/spec/javascripts/helpers/node/integration.js +33 -0
  64. package/spec/javascripts/helpers/node/mock-dom-dependencies.ts +1 -0
  65. package/spec/javascripts/helpers/pusher_integration.js +1 -0
  66. package/spec/javascripts/helpers/pusher_integration_class.ts +12 -0
  67. package/spec/javascripts/helpers/timers/promises.js +9 -0
  68. package/spec/javascripts/helpers/waitsFor.js +37 -0
  69. package/spec/javascripts/helpers/web/integration.js +44 -0
  70. package/spec/javascripts/helpers/worker/mock-dom-dependencies.js +1 -0
  71. package/spec/javascripts/integration/core/cluster_config_spec.js +153 -0
  72. package/spec/javascripts/integration/core/falling_back_spec.js +195 -0
  73. package/spec/javascripts/integration/core/pusher_spec/index.js +68 -0
  74. package/spec/javascripts/integration/core/pusher_spec/test_builder.js +715 -0
  75. package/spec/javascripts/integration/core/timeout_configuration_spec.js +200 -0
  76. package/spec/javascripts/integration/core/transport_lists_spec.js +103 -0
  77. package/spec/javascripts/integration/index.node.js +12 -0
  78. package/spec/javascripts/integration/index.web.js +63 -0
  79. package/spec/javascripts/integration/index.worker.js +13 -0
  80. package/spec/javascripts/integration/web/dom/jsonp_spec.js +97 -0
  81. package/spec/javascripts/integration/web/dom/script_request_spec.js +90 -0
  82. package/spec/javascripts/polyfills/index.js +105 -0
  83. package/spec/javascripts/unit/core/channels/channel_spec.js +355 -0
  84. package/spec/javascripts/unit/core/channels/channels_spec.js +94 -0
  85. package/spec/javascripts/unit/core/channels/encrypted_channel_spec.js +343 -0
  86. package/spec/javascripts/unit/core/channels/presence_channel_spec.js +553 -0
  87. package/spec/javascripts/unit/core/channels/private_channel_spec.js +182 -0
  88. package/spec/javascripts/unit/core/config_spec.js +507 -0
  89. package/spec/javascripts/unit/core/connection/connection_manager_spec.js +656 -0
  90. package/spec/javascripts/unit/core/connection/connection_spec.js +286 -0
  91. package/spec/javascripts/unit/core/connection/handshake_spec.js +160 -0
  92. package/spec/javascripts/unit/core/connection/protocol_spec.js +420 -0
  93. package/spec/javascripts/unit/core/defaults_spec.js +26 -0
  94. package/spec/javascripts/unit/core/events_dispatcher_spec.js +385 -0
  95. package/spec/javascripts/unit/core/http/http_polling_socket_spec.js +60 -0
  96. package/spec/javascripts/unit/core/http/http_request_spec.js +185 -0
  97. package/spec/javascripts/unit/core/http/http_socket_spec.js +370 -0
  98. package/spec/javascripts/unit/core/http/http_streaming_socket_spec.js +56 -0
  99. package/spec/javascripts/unit/core/http/http_xhr_request_spec.js +164 -0
  100. package/spec/javascripts/unit/core/logger_spec.js +133 -0
  101. package/spec/javascripts/unit/core/pusher_spec.js +613 -0
  102. package/spec/javascripts/unit/core/pusher_with_encryption_spec.js +18 -0
  103. package/spec/javascripts/unit/core/strategies/best_connected_ever_strategy_spec.js +104 -0
  104. package/spec/javascripts/unit/core/strategies/delayed_strategy_spec.js +95 -0
  105. package/spec/javascripts/unit/core/strategies/first_connected_strategy_spec.js +68 -0
  106. package/spec/javascripts/unit/core/strategies/if_strategy_spec.js +165 -0
  107. package/spec/javascripts/unit/core/strategies/sequential_strategy_spec.js +213 -0
  108. package/spec/javascripts/unit/core/strategies/transport_strategy_spec.js +250 -0
  109. package/spec/javascripts/unit/core/strategies/websocket_prioritized_cached_strategy_spec.js +400 -0
  110. package/spec/javascripts/unit/core/timeline/timeline_spec.js +153 -0
  111. package/spec/javascripts/unit/core/transports/assistant_to_the_transport_manager_spec.js +223 -0
  112. package/spec/javascripts/unit/core/transports/hosts_and_ports_spec.js +85 -0
  113. package/spec/javascripts/unit/core/transports/transport_connection_spec.js +585 -0
  114. package/spec/javascripts/unit/core/transports/transport_manager_spec.js +64 -0
  115. package/spec/javascripts/unit/core/user_spec.js +303 -0
  116. package/spec/javascripts/unit/core/utils/periodic_timer_spec.js +74 -0
  117. package/spec/javascripts/unit/core/utils/timers_spec.js +157 -0
  118. package/spec/javascripts/unit/core/utils/url_store_spec.js +14 -0
  119. package/spec/javascripts/unit/core/watchlist_spec.js +48 -0
  120. package/spec/javascripts/unit/core_with_runtime/auth/channel_authorizer_spec.js +137 -0
  121. package/spec/javascripts/unit/core_with_runtime/auth/deprecated_channel_authorizer_spec.js +48 -0
  122. package/spec/javascripts/unit/core_with_runtime/auth/user_authorizer_spec.js +128 -0
  123. package/spec/javascripts/unit/core_with_runtime/readme.md +5 -0
  124. package/spec/javascripts/unit/index.node.js +11 -0
  125. package/spec/javascripts/unit/index.web.js +12 -0
  126. package/spec/javascripts/unit/index.worker.js +11 -0
  127. package/spec/javascripts/unit/isomorphic/transports/hosts_and_ports_spec.js +82 -0
  128. package/spec/javascripts/unit/isomorphic/transports/transports_spec.js +202 -0
  129. package/spec/javascripts/unit/node/timeline_sender_spec.js +83 -0
  130. package/spec/javascripts/unit/web/dom/dependency_loader_spec.js +249 -0
  131. package/spec/javascripts/unit/web/dom/jsonp_request_spec.js +130 -0
  132. package/spec/javascripts/unit/web/dom/script_receiver_factory_spec.js +68 -0
  133. package/spec/javascripts/unit/web/http/http_xdomain_request_spec.js +222 -0
  134. package/spec/javascripts/unit/web/pusher_authorizer_spec.js +64 -0
  135. package/spec/javascripts/unit/web/timeline/timeline_sender_spec.js +131 -0
  136. package/spec/javascripts/unit/web/transports/hosts_and_ports_spec.js +127 -0
  137. package/spec/javascripts/unit/web/transports/transports_spec.js +444 -0
  138. package/spec/javascripts/unit/worker/channel_authorizer_spec.js +156 -0
  139. package/spec/javascripts/unit/worker/timeline_sender_spec.js +76 -0
  140. package/src/core/auth/auth_transports.ts +18 -0
  141. package/src/core/auth/channel_authorizer.ts +64 -0
  142. package/src/core/auth/deprecated_channel_authorizer.ts +58 -0
  143. package/src/core/auth/options.ts +78 -0
  144. package/src/core/auth/user_authenticator.ts +62 -0
  145. package/src/core/base64.ts +49 -0
  146. package/src/core/channels/channel.ts +163 -0
  147. package/src/core/channels/channel_table.ts +7 -0
  148. package/src/core/channels/channels.ts +85 -0
  149. package/src/core/channels/encrypted_channel.ts +149 -0
  150. package/src/core/channels/members.ts +80 -0
  151. package/src/core/channels/metadata.ts +5 -0
  152. package/src/core/channels/presence_channel.ts +113 -0
  153. package/src/core/channels/private_channel.ts +25 -0
  154. package/src/core/config.ts +189 -0
  155. package/src/core/connection/callbacks.ts +21 -0
  156. package/src/core/connection/connection.ts +160 -0
  157. package/src/core/connection/connection_manager.ts +371 -0
  158. package/src/core/connection/connection_manager_options.ts +14 -0
  159. package/src/core/connection/handshake/handshake_payload.ts +10 -0
  160. package/src/core/connection/handshake/index.ts +90 -0
  161. package/src/core/connection/protocol/action.ts +8 -0
  162. package/src/core/connection/protocol/message-types.ts +8 -0
  163. package/src/core/connection/protocol/protocol.ts +154 -0
  164. package/src/core/defaults.ts +66 -0
  165. package/src/core/errors.ts +69 -0
  166. package/src/core/events/callback.ts +6 -0
  167. package/src/core/events/callback_registry.ts +75 -0
  168. package/src/core/events/callback_table.ts +7 -0
  169. package/src/core/events/dispatcher.ts +84 -0
  170. package/src/core/http/ajax.ts +24 -0
  171. package/src/core/http/http_factory.ts +16 -0
  172. package/src/core/http/http_polling_socket.ts +24 -0
  173. package/src/core/http/http_request.ts +81 -0
  174. package/src/core/http/http_socket.ts +220 -0
  175. package/src/core/http/http_streaming_socket.ts +19 -0
  176. package/src/core/http/request_hooks.ts +9 -0
  177. package/src/core/http/socket_hooks.ts +11 -0
  178. package/src/core/http/state.ts +7 -0
  179. package/src/core/http/url_location.ts +6 -0
  180. package/src/core/logger.ts +53 -0
  181. package/src/core/options.ts +59 -0
  182. package/src/core/pusher-licence.js +7 -0
  183. package/src/core/pusher-with-encryption.js +1 -0
  184. package/src/core/pusher-with-encryption.ts +14 -0
  185. package/src/core/pusher.js +2 -0
  186. package/src/core/pusher.ts +249 -0
  187. package/src/core/reachability.ts +7 -0
  188. package/src/core/socket.ts +14 -0
  189. package/src/core/strategies/best_connected_ever_strategy.ts +81 -0
  190. package/src/core/strategies/delayed_strategy.ts +48 -0
  191. package/src/core/strategies/first_connected_strategy.ts +28 -0
  192. package/src/core/strategies/if_strategy.ts +34 -0
  193. package/src/core/strategies/sequential_strategy.ts +129 -0
  194. package/src/core/strategies/strategy.ts +8 -0
  195. package/src/core/strategies/strategy_builder.ts +67 -0
  196. package/src/core/strategies/strategy_options.ts +18 -0
  197. package/src/core/strategies/strategy_runner.ts +6 -0
  198. package/src/core/strategies/transport_strategy.ts +144 -0
  199. package/src/core/strategies/websocket_prioritized_cached_strategy.ts +157 -0
  200. package/src/core/timeline/level.ts +7 -0
  201. package/src/core/timeline/timeline.ts +90 -0
  202. package/src/core/timeline/timeline_sender.ts +33 -0
  203. package/src/core/timeline/timeline_transport.ts +11 -0
  204. package/src/core/transports/assistant_to_the_transport_manager.ts +104 -0
  205. package/src/core/transports/ping_delay_options.ts +7 -0
  206. package/src/core/transports/transport.ts +54 -0
  207. package/src/core/transports/transport_connection.ts +241 -0
  208. package/src/core/transports/transport_connection_options.ts +8 -0
  209. package/src/core/transports/transport_hooks.ts +16 -0
  210. package/src/core/transports/transport_manager.ts +52 -0
  211. package/src/core/transports/transports_table.ts +12 -0
  212. package/src/core/transports/url_scheme.ts +13 -0
  213. package/src/core/transports/url_schemes.ts +47 -0
  214. package/src/core/user.ts +186 -0
  215. package/src/core/util.ts +34 -0
  216. package/src/core/utils/collections.ts +353 -0
  217. package/src/core/utils/factory.ts +75 -0
  218. package/src/core/utils/flat_promise.ts +10 -0
  219. package/src/core/utils/timers/abstract_timer.ts +39 -0
  220. package/src/core/utils/timers/index.ts +39 -0
  221. package/src/core/utils/timers/scheduling.ts +11 -0
  222. package/src/core/utils/timers/timed_callback.ts +5 -0
  223. package/src/core/utils/url_store.ts +48 -0
  224. package/src/core/watchlist.ts +31 -0
  225. package/src/d.ts/constants/index.d.ts +5 -0
  226. package/src/d.ts/faye-websocket/faye-websocket.d.ts +21 -0
  227. package/src/d.ts/global/global.d.ts +1 -0
  228. package/src/d.ts/module/module.d.ts +12 -0
  229. package/src/d.ts/tweetnacl-util/index.d.ts +6 -0
  230. package/src/d.ts/window/events.d.ts +4 -0
  231. package/src/d.ts/window/sockjs.d.ts +3 -0
  232. package/src/d.ts/window/websocket.d.ts +4 -0
  233. package/src/d.ts/window/xmlhttprequest.d.ts +3 -0
  234. package/src/runtimes/interface.ts +59 -0
  235. package/src/runtimes/isomorphic/auth/xhr_auth.ts +90 -0
  236. package/src/runtimes/isomorphic/default_strategy.ts +155 -0
  237. package/src/runtimes/isomorphic/http/http.ts +32 -0
  238. package/src/runtimes/isomorphic/http/http_xhr_request.ts +35 -0
  239. package/src/runtimes/isomorphic/runtime.ts +62 -0
  240. package/src/runtimes/isomorphic/timeline/xhr_timeline.ts +50 -0
  241. package/src/runtimes/isomorphic/transports/transport_connection_initializer.ts +19 -0
  242. package/src/runtimes/isomorphic/transports/transports.ts +81 -0
  243. package/src/runtimes/node/net_info.ts +10 -0
  244. package/src/runtimes/node/runtime.ts +68 -0
  245. package/src/runtimes/react-native/net_info.ts +42 -0
  246. package/src/runtimes/react-native/runtime.ts +65 -0
  247. package/src/runtimes/web/auth/jsonp_auth.ts +51 -0
  248. package/src/runtimes/web/browser.ts +24 -0
  249. package/src/runtimes/web/default_strategy.ts +201 -0
  250. package/src/runtimes/web/dom/dependencies.ts +16 -0
  251. package/src/runtimes/web/dom/dependency_loader.ts +93 -0
  252. package/src/runtimes/web/dom/json2.js +486 -0
  253. package/src/runtimes/web/dom/jsonp_request.ts +52 -0
  254. package/src/runtimes/web/dom/script_receiver.ts +8 -0
  255. package/src/runtimes/web/dom/script_receiver_factory.ts +57 -0
  256. package/src/runtimes/web/dom/script_request.ts +85 -0
  257. package/src/runtimes/web/dom/sockjs/COPYING +11 -0
  258. package/src/runtimes/web/dom/sockjs/Changelog +147 -0
  259. package/src/runtimes/web/dom/sockjs/LICENSE-MIT-SockJS +19 -0
  260. package/src/runtimes/web/dom/sockjs/Makefile +109 -0
  261. package/src/runtimes/web/dom/sockjs/README.md +388 -0
  262. package/src/runtimes/web/dom/sockjs/VERSION-GEN +17 -0
  263. package/src/runtimes/web/dom/sockjs/bin/render.coffee +111 -0
  264. package/src/runtimes/web/dom/sockjs/bin/run_testling.sh +135 -0
  265. package/src/runtimes/web/dom/sockjs/lib/all.js +9 -0
  266. package/src/runtimes/web/dom/sockjs/lib/dom.js +185 -0
  267. package/src/runtimes/web/dom/sockjs/lib/dom2.js +280 -0
  268. package/src/runtimes/web/dom/sockjs/lib/eventemitter.js +57 -0
  269. package/src/runtimes/web/dom/sockjs/lib/heartbeater.js +70 -0
  270. package/src/runtimes/web/dom/sockjs/lib/index.js +41 -0
  271. package/src/runtimes/web/dom/sockjs/lib/info.js +117 -0
  272. package/src/runtimes/web/dom/sockjs/lib/json2.min.js +1 -0
  273. package/src/runtimes/web/dom/sockjs/lib/reventtarget.js +55 -0
  274. package/src/runtimes/web/dom/sockjs/lib/simpleevent.js +28 -0
  275. package/src/runtimes/web/dom/sockjs/lib/sockjs.js +288 -0
  276. package/src/runtimes/web/dom/sockjs/lib/test-hooks.js +16 -0
  277. package/src/runtimes/web/dom/sockjs/lib/trans-iframe-eventsource.js +29 -0
  278. package/src/runtimes/web/dom/sockjs/lib/trans-iframe-htmlfile.js +35 -0
  279. package/src/runtimes/web/dom/sockjs/lib/trans-iframe-within.js +100 -0
  280. package/src/runtimes/web/dom/sockjs/lib/trans-iframe-xhr-polling.js +30 -0
  281. package/src/runtimes/web/dom/sockjs/lib/trans-iframe.js +103 -0
  282. package/src/runtimes/web/dom/sockjs/lib/trans-jsonp-polling.js +106 -0
  283. package/src/runtimes/web/dom/sockjs/lib/trans-jsonp-receiver.js +116 -0
  284. package/src/runtimes/web/dom/sockjs/lib/trans-polling.js +44 -0
  285. package/src/runtimes/web/dom/sockjs/lib/trans-receiver-eventsource.js +41 -0
  286. package/src/runtimes/web/dom/sockjs/lib/trans-receiver-htmlfile.js +65 -0
  287. package/src/runtimes/web/dom/sockjs/lib/trans-receiver-xhr.js +42 -0
  288. package/src/runtimes/web/dom/sockjs/lib/trans-sender.js +138 -0
  289. package/src/runtimes/web/dom/sockjs/lib/trans-xhr.js +29 -0
  290. package/src/runtimes/web/dom/sockjs/lib/utils.js +297 -0
  291. package/src/runtimes/web/dom/sockjs/package.json +18 -0
  292. package/src/runtimes/web/dom/sockjs/version +1 -0
  293. package/src/runtimes/web/http/http.ts +8 -0
  294. package/src/runtimes/web/http/http_xdomain_request.ts +37 -0
  295. package/src/runtimes/web/net_info.ts +50 -0
  296. package/src/runtimes/web/runtime.ts +174 -0
  297. package/src/runtimes/web/timeline/jsonp_timeline.ts +34 -0
  298. package/src/runtimes/web/transports/transport_connection_initializer.ts +39 -0
  299. package/src/runtimes/web/transports/transports.ts +65 -0
  300. package/src/runtimes/worker/auth/fetch_auth.ts +69 -0
  301. package/src/runtimes/worker/net_info.ts +10 -0
  302. package/src/runtimes/worker/runtime.ts +75 -0
  303. package/src/runtimes/worker/timeline/fetch_timeline.ts +39 -0
  304. package/tsconfig.json +26 -0
  305. package/types/spec/javascripts/helpers/node/mock-dom-dependencies.d.ts +1 -0
  306. package/types/spec/javascripts/helpers/pusher_integration_class.d.ts +4 -0
  307. package/types/src/core/auth/auth_transports.d.ts +9 -0
  308. package/types/src/core/auth/channel_authorizer.d.ts +3 -0
  309. package/types/src/core/auth/deprecated_channel_authorizer.d.ts +18 -0
  310. package/types/src/core/auth/options.d.ts +48 -0
  311. package/types/src/core/auth/user_authenticator.d.ts +3 -0
  312. package/types/src/core/base64.d.ts +1 -0
  313. package/types/src/core/channels/channel.d.ts +23 -0
  314. package/types/src/core/channels/channel_table.d.ts +5 -0
  315. package/types/src/core/channels/channels.d.ts +12 -0
  316. package/types/src/core/channels/encrypted_channel.d.ts +15 -0
  317. package/types/src/core/channels/members.d.ts +14 -0
  318. package/types/src/core/channels/metadata.d.ts +4 -0
  319. package/types/src/core/channels/presence_channel.d.ts +13 -0
  320. package/types/src/core/channels/private_channel.d.ts +5 -0
  321. package/types/src/core/config.d.ts +31 -0
  322. package/types/src/core/connection/callbacks.d.ts +18 -0
  323. package/types/src/core/connection/connection.d.ts +16 -0
  324. package/types/src/core/connection/connection_manager.d.ts +50 -0
  325. package/types/src/core/connection/connection_manager_options.d.ts +11 -0
  326. package/types/src/core/connection/handshake/handshake_payload.d.ts +8 -0
  327. package/types/src/core/connection/handshake/index.d.ts +12 -0
  328. package/types/src/core/connection/protocol/action.d.ts +7 -0
  329. package/types/src/core/connection/protocol/message-types.d.ts +7 -0
  330. package/types/src/core/connection/protocol/protocol.d.ts +10 -0
  331. package/types/src/core/defaults.d.ts +26 -0
  332. package/types/src/core/errors.d.ts +28 -0
  333. package/types/src/core/events/callback.d.ts +5 -0
  334. package/types/src/core/events/callback_registry.d.ts +11 -0
  335. package/types/src/core/events/callback_table.d.ts +5 -0
  336. package/types/src/core/events/dispatcher.d.ts +14 -0
  337. package/types/src/core/http/ajax.d.ts +16 -0
  338. package/types/src/core/http/http_factory.d.ts +13 -0
  339. package/types/src/core/http/http_polling_socket.d.ts +3 -0
  340. package/types/src/core/http/http_request.d.ts +17 -0
  341. package/types/src/core/http/http_socket.d.ts +32 -0
  342. package/types/src/core/http/http_streaming_socket.d.ts +3 -0
  343. package/types/src/core/http/request_hooks.d.ts +6 -0
  344. package/types/src/core/http/socket_hooks.d.ts +8 -0
  345. package/types/src/core/http/state.d.ts +6 -0
  346. package/types/src/core/http/url_location.d.ts +5 -0
  347. package/types/src/core/logger.d.ts +11 -0
  348. package/types/src/core/options.d.ts +34 -0
  349. package/types/src/core/pusher-with-encryption.d.ts +5 -0
  350. package/types/src/core/pusher.d.ts +49 -0
  351. package/types/src/core/reachability.d.ts +5 -0
  352. package/types/src/core/socket.d.ts +12 -0
  353. package/types/src/core/strategies/best_connected_ever_strategy.d.ts +10 -0
  354. package/types/src/core/strategies/delayed_strategy.d.ts +15 -0
  355. package/types/src/core/strategies/first_connected_strategy.d.ts +8 -0
  356. package/types/src/core/strategies/if_strategy.d.ts +10 -0
  357. package/types/src/core/strategies/sequential_strategy.d.ts +16 -0
  358. package/types/src/core/strategies/strategy.d.ts +6 -0
  359. package/types/src/core/strategies/strategy_builder.d.ts +5 -0
  360. package/types/src/core/strategies/strategy_options.d.ts +16 -0
  361. package/types/src/core/strategies/strategy_runner.d.ts +5 -0
  362. package/types/src/core/strategies/transport_strategy.d.ts +15 -0
  363. package/types/src/core/strategies/websocket_prioritized_cached_strategy.d.ts +20 -0
  364. package/types/src/core/timeline/level.d.ts +6 -0
  365. package/types/src/core/timeline/timeline.d.ts +25 -0
  366. package/types/src/core/timeline/timeline_sender.d.ts +13 -0
  367. package/types/src/core/timeline/timeline_transport.d.ts +6 -0
  368. package/types/src/core/transports/assistant_to_the_transport_manager.d.ts +14 -0
  369. package/types/src/core/transports/ping_delay_options.d.ts +6 -0
  370. package/types/src/core/transports/transport.d.ts +8 -0
  371. package/types/src/core/transports/transport_connection.d.ts +35 -0
  372. package/types/src/core/transports/transport_connection_options.d.ts +6 -0
  373. package/types/src/core/transports/transport_hooks.d.ts +13 -0
  374. package/types/src/core/transports/transport_manager.d.ts +14 -0
  375. package/types/src/core/transports/transports_table.d.ts +10 -0
  376. package/types/src/core/transports/url_scheme.d.ts +11 -0
  377. package/types/src/core/transports/url_schemes.d.ts +4 -0
  378. package/types/src/core/user.d.ts +21 -0
  379. package/types/src/core/util.d.ts +8 -0
  380. package/types/src/core/utils/collections.d.ts +18 -0
  381. package/types/src/core/utils/factory.d.ts +29 -0
  382. package/types/src/core/utils/flat_promise.d.ts +6 -0
  383. package/types/src/core/utils/timers/abstract_timer.d.ts +10 -0
  384. package/types/src/core/utils/timers/index.d.ts +9 -0
  385. package/types/src/core/utils/timers/scheduling.d.ts +8 -0
  386. package/types/src/core/utils/timers/timed_callback.d.ts +4 -0
  387. package/types/src/core/utils/url_store.d.ts +4 -0
  388. package/types/src/core/watchlist.d.ts +8 -0
  389. package/types/src/runtimes/interface.d.ts +43 -0
  390. package/types/src/runtimes/isomorphic/auth/xhr_auth.d.ts +3 -0
  391. package/types/src/runtimes/isomorphic/default_strategy.d.ts +5 -0
  392. package/types/src/runtimes/isomorphic/http/http.d.ts +3 -0
  393. package/types/src/runtimes/isomorphic/http/http_xhr_request.d.ts +3 -0
  394. package/types/src/runtimes/isomorphic/runtime.d.ts +2 -0
  395. package/types/src/runtimes/isomorphic/timeline/xhr_timeline.d.ts +6 -0
  396. package/types/src/runtimes/isomorphic/transports/transport_connection_initializer.d.ts +1 -0
  397. package/types/src/runtimes/isomorphic/transports/transports.d.ts +5 -0
  398. package/types/src/runtimes/node/net_info.d.ts +6 -0
  399. package/types/src/runtimes/node/runtime.d.ts +3 -0
  400. package/types/src/runtimes/react-native/net_info.d.ts +8 -0
  401. package/types/src/runtimes/react-native/runtime.d.ts +3 -0
  402. package/types/src/runtimes/web/auth/jsonp_auth.d.ts +3 -0
  403. package/types/src/runtimes/web/browser.d.ts +19 -0
  404. package/types/src/runtimes/web/default_strategy.d.ts +5 -0
  405. package/types/src/runtimes/web/dom/dependencies.d.ts +4 -0
  406. package/types/src/runtimes/web/dom/dependency_loader.d.ts +10 -0
  407. package/types/src/runtimes/web/dom/jsonp_request.d.ts +10 -0
  408. package/types/src/runtimes/web/dom/script_receiver.d.ts +7 -0
  409. package/types/src/runtimes/web/dom/script_receiver_factory.d.ts +10 -0
  410. package/types/src/runtimes/web/dom/script_request.d.ts +9 -0
  411. package/types/src/runtimes/web/http/http.d.ts +2 -0
  412. package/types/src/runtimes/web/http/http_xdomain_request.d.ts +3 -0
  413. package/types/src/runtimes/web/net_info.d.ts +7 -0
  414. package/types/src/runtimes/web/runtime.d.ts +3 -0
  415. package/types/src/runtimes/web/timeline/jsonp_timeline.d.ts +6 -0
  416. package/types/src/runtimes/web/transports/transport_connection_initializer.d.ts +1 -0
  417. package/types/src/runtimes/web/transports/transports.d.ts +2 -0
  418. package/types/src/runtimes/worker/auth/fetch_auth.d.ts +3 -0
  419. package/types/src/runtimes/worker/net_info.d.ts +6 -0
  420. package/types/src/runtimes/worker/runtime.d.ts +3 -0
  421. package/types/src/runtimes/worker/timeline/fetch_timeline.d.ts +6 -0
  422. package/webpack/config.node.js +26 -0
  423. package/webpack/config.react-native.js +35 -0
  424. package/webpack/config.shared.js +50 -0
  425. package/webpack/config.web.js +36 -0
  426. package/webpack/config.worker.js +42 -0
  427. package/webpack/dev.server.js +17 -0
  428. package/webpack/hosting_config.js +6 -0
  429. package/with-encryption/index.d.ts +29 -0
  430. package/with-encryption/index.js +4 -0
  431. package/worker/index.d.ts +29 -0
  432. package/worker/index.js +1 -0
  433. package/worker/with-encryption/index.d.ts +29 -0
  434. package/worker/with-encryption/index.js +1 -0
@@ -0,0 +1,4200 @@
1
+ /*!
2
+ * Pusher JavaScript Library v8.3.0
3
+ * https://pusher.com/
4
+ *
5
+ * Copyright 2020, Pusher
6
+ * Released under the MIT licence.
7
+ */
8
+
9
+ (function webpackUniversalModuleDefinition(root, factory) {
10
+ if(typeof exports === 'object' && typeof module === 'object')
11
+ module.exports = factory();
12
+ else if(typeof define === 'function' && define.amd)
13
+ define([], factory);
14
+ else if(typeof exports === 'object')
15
+ exports["Pusher"] = factory();
16
+ else
17
+ root["Pusher"] = factory();
18
+ })(this, function() {
19
+ return /******/ (function(modules) { // webpackBootstrap
20
+ /******/ // The module cache
21
+ /******/ var installedModules = {};
22
+ /******/
23
+ /******/ // The require function
24
+ /******/ function __webpack_require__(moduleId) {
25
+ /******/
26
+ /******/ // Check if module is in cache
27
+ /******/ if(installedModules[moduleId]) {
28
+ /******/ return installedModules[moduleId].exports;
29
+ /******/ }
30
+ /******/ // Create a new module (and put it into the cache)
31
+ /******/ var module = installedModules[moduleId] = {
32
+ /******/ i: moduleId,
33
+ /******/ l: false,
34
+ /******/ exports: {}
35
+ /******/ };
36
+ /******/
37
+ /******/ // Execute the module function
38
+ /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
39
+ /******/
40
+ /******/ // Flag the module as loaded
41
+ /******/ module.l = true;
42
+ /******/
43
+ /******/ // Return the exports of the module
44
+ /******/ return module.exports;
45
+ /******/ }
46
+ /******/
47
+ /******/
48
+ /******/ // expose the modules object (__webpack_modules__)
49
+ /******/ __webpack_require__.m = modules;
50
+ /******/
51
+ /******/ // expose the module cache
52
+ /******/ __webpack_require__.c = installedModules;
53
+ /******/
54
+ /******/ // define getter function for harmony exports
55
+ /******/ __webpack_require__.d = function(exports, name, getter) {
56
+ /******/ if(!__webpack_require__.o(exports, name)) {
57
+ /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
58
+ /******/ }
59
+ /******/ };
60
+ /******/
61
+ /******/ // define __esModule on exports
62
+ /******/ __webpack_require__.r = function(exports) {
63
+ /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
64
+ /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
65
+ /******/ }
66
+ /******/ Object.defineProperty(exports, '__esModule', { value: true });
67
+ /******/ };
68
+ /******/
69
+ /******/ // create a fake namespace object
70
+ /******/ // mode & 1: value is a module id, require it
71
+ /******/ // mode & 2: merge all properties of value into the ns
72
+ /******/ // mode & 4: return value when already ns object
73
+ /******/ // mode & 8|1: behave like require
74
+ /******/ __webpack_require__.t = function(value, mode) {
75
+ /******/ if(mode & 1) value = __webpack_require__(value);
76
+ /******/ if(mode & 8) return value;
77
+ /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
78
+ /******/ var ns = Object.create(null);
79
+ /******/ __webpack_require__.r(ns);
80
+ /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
81
+ /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
82
+ /******/ return ns;
83
+ /******/ };
84
+ /******/
85
+ /******/ // getDefaultExport function for compatibility with non-harmony modules
86
+ /******/ __webpack_require__.n = function(module) {
87
+ /******/ var getter = module && module.__esModule ?
88
+ /******/ function getDefault() { return module['default']; } :
89
+ /******/ function getModuleExports() { return module; };
90
+ /******/ __webpack_require__.d(getter, 'a', getter);
91
+ /******/ return getter;
92
+ /******/ };
93
+ /******/
94
+ /******/ // Object.prototype.hasOwnProperty.call
95
+ /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
96
+ /******/
97
+ /******/ // __webpack_public_path__
98
+ /******/ __webpack_require__.p = "";
99
+ /******/
100
+ /******/
101
+ /******/ // Load entry module and return exports
102
+ /******/ return __webpack_require__(__webpack_require__.s = 2);
103
+ /******/ })
104
+ /************************************************************************/
105
+ /******/ ([
106
+ /* 0 */
107
+ /***/ (function(module, exports, __webpack_require__) {
108
+
109
+ "use strict";
110
+
111
+ // Copyright (C) 2016 Dmitry Chestnykh
112
+ // MIT License. See LICENSE file for details.
113
+ var __extends = (this && this.__extends) || (function () {
114
+ var extendStatics = function (d, b) {
115
+ extendStatics = Object.setPrototypeOf ||
116
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
117
+ function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
118
+ return extendStatics(d, b);
119
+ };
120
+ return function (d, b) {
121
+ extendStatics(d, b);
122
+ function __() { this.constructor = d; }
123
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
124
+ };
125
+ })();
126
+ Object.defineProperty(exports, "__esModule", { value: true });
127
+ /**
128
+ * Package base64 implements Base64 encoding and decoding.
129
+ */
130
+ // Invalid character used in decoding to indicate
131
+ // that the character to decode is out of range of
132
+ // alphabet and cannot be decoded.
133
+ var INVALID_BYTE = 256;
134
+ /**
135
+ * Implements standard Base64 encoding.
136
+ *
137
+ * Operates in constant time.
138
+ */
139
+ var Coder = /** @class */ (function () {
140
+ // TODO(dchest): methods to encode chunk-by-chunk.
141
+ function Coder(_paddingCharacter) {
142
+ if (_paddingCharacter === void 0) { _paddingCharacter = "="; }
143
+ this._paddingCharacter = _paddingCharacter;
144
+ }
145
+ Coder.prototype.encodedLength = function (length) {
146
+ if (!this._paddingCharacter) {
147
+ return (length * 8 + 5) / 6 | 0;
148
+ }
149
+ return (length + 2) / 3 * 4 | 0;
150
+ };
151
+ Coder.prototype.encode = function (data) {
152
+ var out = "";
153
+ var i = 0;
154
+ for (; i < data.length - 2; i += 3) {
155
+ var c = (data[i] << 16) | (data[i + 1] << 8) | (data[i + 2]);
156
+ out += this._encodeByte((c >>> 3 * 6) & 63);
157
+ out += this._encodeByte((c >>> 2 * 6) & 63);
158
+ out += this._encodeByte((c >>> 1 * 6) & 63);
159
+ out += this._encodeByte((c >>> 0 * 6) & 63);
160
+ }
161
+ var left = data.length - i;
162
+ if (left > 0) {
163
+ var c = (data[i] << 16) | (left === 2 ? data[i + 1] << 8 : 0);
164
+ out += this._encodeByte((c >>> 3 * 6) & 63);
165
+ out += this._encodeByte((c >>> 2 * 6) & 63);
166
+ if (left === 2) {
167
+ out += this._encodeByte((c >>> 1 * 6) & 63);
168
+ }
169
+ else {
170
+ out += this._paddingCharacter || "";
171
+ }
172
+ out += this._paddingCharacter || "";
173
+ }
174
+ return out;
175
+ };
176
+ Coder.prototype.maxDecodedLength = function (length) {
177
+ if (!this._paddingCharacter) {
178
+ return (length * 6 + 7) / 8 | 0;
179
+ }
180
+ return length / 4 * 3 | 0;
181
+ };
182
+ Coder.prototype.decodedLength = function (s) {
183
+ return this.maxDecodedLength(s.length - this._getPaddingLength(s));
184
+ };
185
+ Coder.prototype.decode = function (s) {
186
+ if (s.length === 0) {
187
+ return new Uint8Array(0);
188
+ }
189
+ var paddingLength = this._getPaddingLength(s);
190
+ var length = s.length - paddingLength;
191
+ var out = new Uint8Array(this.maxDecodedLength(length));
192
+ var op = 0;
193
+ var i = 0;
194
+ var haveBad = 0;
195
+ var v0 = 0, v1 = 0, v2 = 0, v3 = 0;
196
+ for (; i < length - 4; i += 4) {
197
+ v0 = this._decodeChar(s.charCodeAt(i + 0));
198
+ v1 = this._decodeChar(s.charCodeAt(i + 1));
199
+ v2 = this._decodeChar(s.charCodeAt(i + 2));
200
+ v3 = this._decodeChar(s.charCodeAt(i + 3));
201
+ out[op++] = (v0 << 2) | (v1 >>> 4);
202
+ out[op++] = (v1 << 4) | (v2 >>> 2);
203
+ out[op++] = (v2 << 6) | v3;
204
+ haveBad |= v0 & INVALID_BYTE;
205
+ haveBad |= v1 & INVALID_BYTE;
206
+ haveBad |= v2 & INVALID_BYTE;
207
+ haveBad |= v3 & INVALID_BYTE;
208
+ }
209
+ if (i < length - 1) {
210
+ v0 = this._decodeChar(s.charCodeAt(i));
211
+ v1 = this._decodeChar(s.charCodeAt(i + 1));
212
+ out[op++] = (v0 << 2) | (v1 >>> 4);
213
+ haveBad |= v0 & INVALID_BYTE;
214
+ haveBad |= v1 & INVALID_BYTE;
215
+ }
216
+ if (i < length - 2) {
217
+ v2 = this._decodeChar(s.charCodeAt(i + 2));
218
+ out[op++] = (v1 << 4) | (v2 >>> 2);
219
+ haveBad |= v2 & INVALID_BYTE;
220
+ }
221
+ if (i < length - 3) {
222
+ v3 = this._decodeChar(s.charCodeAt(i + 3));
223
+ out[op++] = (v2 << 6) | v3;
224
+ haveBad |= v3 & INVALID_BYTE;
225
+ }
226
+ if (haveBad !== 0) {
227
+ throw new Error("Base64Coder: incorrect characters for decoding");
228
+ }
229
+ return out;
230
+ };
231
+ // Standard encoding have the following encoded/decoded ranges,
232
+ // which we need to convert between.
233
+ //
234
+ // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 + /
235
+ // Index: 0 - 25 26 - 51 52 - 61 62 63
236
+ // ASCII: 65 - 90 97 - 122 48 - 57 43 47
237
+ //
238
+ // Encode 6 bits in b into a new character.
239
+ Coder.prototype._encodeByte = function (b) {
240
+ // Encoding uses constant time operations as follows:
241
+ //
242
+ // 1. Define comparison of A with B using (A - B) >>> 8:
243
+ // if A > B, then result is positive integer
244
+ // if A <= B, then result is 0
245
+ //
246
+ // 2. Define selection of C or 0 using bitwise AND: X & C:
247
+ // if X == 0, then result is 0
248
+ // if X != 0, then result is C
249
+ //
250
+ // 3. Start with the smallest comparison (b >= 0), which is always
251
+ // true, so set the result to the starting ASCII value (65).
252
+ //
253
+ // 4. Continue comparing b to higher ASCII values, and selecting
254
+ // zero if comparison isn't true, otherwise selecting a value
255
+ // to add to result, which:
256
+ //
257
+ // a) undoes the previous addition
258
+ // b) provides new value to add
259
+ //
260
+ var result = b;
261
+ // b >= 0
262
+ result += 65;
263
+ // b > 25
264
+ result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);
265
+ // b > 51
266
+ result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);
267
+ // b > 61
268
+ result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 43);
269
+ // b > 62
270
+ result += ((62 - b) >>> 8) & ((62 - 43) - 63 + 47);
271
+ return String.fromCharCode(result);
272
+ };
273
+ // Decode a character code into a byte.
274
+ // Must return 256 if character is out of alphabet range.
275
+ Coder.prototype._decodeChar = function (c) {
276
+ // Decoding works similar to encoding: using the same comparison
277
+ // function, but now it works on ranges: result is always incremented
278
+ // by value, but this value becomes zero if the range is not
279
+ // satisfied.
280
+ //
281
+ // Decoding starts with invalid value, 256, which is then
282
+ // subtracted when the range is satisfied. If none of the ranges
283
+ // apply, the function returns 256, which is then checked by
284
+ // the caller to throw error.
285
+ var result = INVALID_BYTE; // start with invalid character
286
+ // c == 43 (c > 42 and c < 44)
287
+ result += (((42 - c) & (c - 44)) >>> 8) & (-INVALID_BYTE + c - 43 + 62);
288
+ // c == 47 (c > 46 and c < 48)
289
+ result += (((46 - c) & (c - 48)) >>> 8) & (-INVALID_BYTE + c - 47 + 63);
290
+ // c > 47 and c < 58
291
+ result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);
292
+ // c > 64 and c < 91
293
+ result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);
294
+ // c > 96 and c < 123
295
+ result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);
296
+ return result;
297
+ };
298
+ Coder.prototype._getPaddingLength = function (s) {
299
+ var paddingLength = 0;
300
+ if (this._paddingCharacter) {
301
+ for (var i = s.length - 1; i >= 0; i--) {
302
+ if (s[i] !== this._paddingCharacter) {
303
+ break;
304
+ }
305
+ paddingLength++;
306
+ }
307
+ if (s.length < 4 || paddingLength > 2) {
308
+ throw new Error("Base64Coder: incorrect padding");
309
+ }
310
+ }
311
+ return paddingLength;
312
+ };
313
+ return Coder;
314
+ }());
315
+ exports.Coder = Coder;
316
+ var stdCoder = new Coder();
317
+ function encode(data) {
318
+ return stdCoder.encode(data);
319
+ }
320
+ exports.encode = encode;
321
+ function decode(s) {
322
+ return stdCoder.decode(s);
323
+ }
324
+ exports.decode = decode;
325
+ /**
326
+ * Implements URL-safe Base64 encoding.
327
+ * (Same as Base64, but '+' is replaced with '-', and '/' with '_').
328
+ *
329
+ * Operates in constant time.
330
+ */
331
+ var URLSafeCoder = /** @class */ (function (_super) {
332
+ __extends(URLSafeCoder, _super);
333
+ function URLSafeCoder() {
334
+ return _super !== null && _super.apply(this, arguments) || this;
335
+ }
336
+ // URL-safe encoding have the following encoded/decoded ranges:
337
+ //
338
+ // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 - _
339
+ // Index: 0 - 25 26 - 51 52 - 61 62 63
340
+ // ASCII: 65 - 90 97 - 122 48 - 57 45 95
341
+ //
342
+ URLSafeCoder.prototype._encodeByte = function (b) {
343
+ var result = b;
344
+ // b >= 0
345
+ result += 65;
346
+ // b > 25
347
+ result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);
348
+ // b > 51
349
+ result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);
350
+ // b > 61
351
+ result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 45);
352
+ // b > 62
353
+ result += ((62 - b) >>> 8) & ((62 - 45) - 63 + 95);
354
+ return String.fromCharCode(result);
355
+ };
356
+ URLSafeCoder.prototype._decodeChar = function (c) {
357
+ var result = INVALID_BYTE;
358
+ // c == 45 (c > 44 and c < 46)
359
+ result += (((44 - c) & (c - 46)) >>> 8) & (-INVALID_BYTE + c - 45 + 62);
360
+ // c == 95 (c > 94 and c < 96)
361
+ result += (((94 - c) & (c - 96)) >>> 8) & (-INVALID_BYTE + c - 95 + 63);
362
+ // c > 47 and c < 58
363
+ result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);
364
+ // c > 64 and c < 91
365
+ result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);
366
+ // c > 96 and c < 123
367
+ result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);
368
+ return result;
369
+ };
370
+ return URLSafeCoder;
371
+ }(Coder));
372
+ exports.URLSafeCoder = URLSafeCoder;
373
+ var urlSafeCoder = new URLSafeCoder();
374
+ function encodeURLSafe(data) {
375
+ return urlSafeCoder.encode(data);
376
+ }
377
+ exports.encodeURLSafe = encodeURLSafe;
378
+ function decodeURLSafe(s) {
379
+ return urlSafeCoder.decode(s);
380
+ }
381
+ exports.decodeURLSafe = decodeURLSafe;
382
+ exports.encodedLength = function (length) {
383
+ return stdCoder.encodedLength(length);
384
+ };
385
+ exports.maxDecodedLength = function (length) {
386
+ return stdCoder.maxDecodedLength(length);
387
+ };
388
+ exports.decodedLength = function (s) {
389
+ return stdCoder.decodedLength(s);
390
+ };
391
+
392
+
393
+ /***/ }),
394
+ /* 1 */
395
+ /***/ (function(module, exports, __webpack_require__) {
396
+
397
+ "use strict";
398
+
399
+ // Copyright (C) 2016 Dmitry Chestnykh
400
+ // MIT License. See LICENSE file for details.
401
+ Object.defineProperty(exports, "__esModule", { value: true });
402
+ /**
403
+ * Package utf8 implements UTF-8 encoding and decoding.
404
+ */
405
+ var INVALID_UTF16 = "utf8: invalid string";
406
+ var INVALID_UTF8 = "utf8: invalid source encoding";
407
+ /**
408
+ * Encodes the given string into UTF-8 byte array.
409
+ * Throws if the source string has invalid UTF-16 encoding.
410
+ */
411
+ function encode(s) {
412
+ // Calculate result length and allocate output array.
413
+ // encodedLength() also validates string and throws errors,
414
+ // so we don't need repeat validation here.
415
+ var arr = new Uint8Array(encodedLength(s));
416
+ var pos = 0;
417
+ for (var i = 0; i < s.length; i++) {
418
+ var c = s.charCodeAt(i);
419
+ if (c < 0x80) {
420
+ arr[pos++] = c;
421
+ }
422
+ else if (c < 0x800) {
423
+ arr[pos++] = 0xc0 | c >> 6;
424
+ arr[pos++] = 0x80 | c & 0x3f;
425
+ }
426
+ else if (c < 0xd800) {
427
+ arr[pos++] = 0xe0 | c >> 12;
428
+ arr[pos++] = 0x80 | (c >> 6) & 0x3f;
429
+ arr[pos++] = 0x80 | c & 0x3f;
430
+ }
431
+ else {
432
+ i++; // get one more character
433
+ c = (c & 0x3ff) << 10;
434
+ c |= s.charCodeAt(i) & 0x3ff;
435
+ c += 0x10000;
436
+ arr[pos++] = 0xf0 | c >> 18;
437
+ arr[pos++] = 0x80 | (c >> 12) & 0x3f;
438
+ arr[pos++] = 0x80 | (c >> 6) & 0x3f;
439
+ arr[pos++] = 0x80 | c & 0x3f;
440
+ }
441
+ }
442
+ return arr;
443
+ }
444
+ exports.encode = encode;
445
+ /**
446
+ * Returns the number of bytes required to encode the given string into UTF-8.
447
+ * Throws if the source string has invalid UTF-16 encoding.
448
+ */
449
+ function encodedLength(s) {
450
+ var result = 0;
451
+ for (var i = 0; i < s.length; i++) {
452
+ var c = s.charCodeAt(i);
453
+ if (c < 0x80) {
454
+ result += 1;
455
+ }
456
+ else if (c < 0x800) {
457
+ result += 2;
458
+ }
459
+ else if (c < 0xd800) {
460
+ result += 3;
461
+ }
462
+ else if (c <= 0xdfff) {
463
+ if (i >= s.length - 1) {
464
+ throw new Error(INVALID_UTF16);
465
+ }
466
+ i++; // "eat" next character
467
+ result += 4;
468
+ }
469
+ else {
470
+ throw new Error(INVALID_UTF16);
471
+ }
472
+ }
473
+ return result;
474
+ }
475
+ exports.encodedLength = encodedLength;
476
+ /**
477
+ * Decodes the given byte array from UTF-8 into a string.
478
+ * Throws if encoding is invalid.
479
+ */
480
+ function decode(arr) {
481
+ var chars = [];
482
+ for (var i = 0; i < arr.length; i++) {
483
+ var b = arr[i];
484
+ if (b & 0x80) {
485
+ var min = void 0;
486
+ if (b < 0xe0) {
487
+ // Need 1 more byte.
488
+ if (i >= arr.length) {
489
+ throw new Error(INVALID_UTF8);
490
+ }
491
+ var n1 = arr[++i];
492
+ if ((n1 & 0xc0) !== 0x80) {
493
+ throw new Error(INVALID_UTF8);
494
+ }
495
+ b = (b & 0x1f) << 6 | (n1 & 0x3f);
496
+ min = 0x80;
497
+ }
498
+ else if (b < 0xf0) {
499
+ // Need 2 more bytes.
500
+ if (i >= arr.length - 1) {
501
+ throw new Error(INVALID_UTF8);
502
+ }
503
+ var n1 = arr[++i];
504
+ var n2 = arr[++i];
505
+ if ((n1 & 0xc0) !== 0x80 || (n2 & 0xc0) !== 0x80) {
506
+ throw new Error(INVALID_UTF8);
507
+ }
508
+ b = (b & 0x0f) << 12 | (n1 & 0x3f) << 6 | (n2 & 0x3f);
509
+ min = 0x800;
510
+ }
511
+ else if (b < 0xf8) {
512
+ // Need 3 more bytes.
513
+ if (i >= arr.length - 2) {
514
+ throw new Error(INVALID_UTF8);
515
+ }
516
+ var n1 = arr[++i];
517
+ var n2 = arr[++i];
518
+ var n3 = arr[++i];
519
+ if ((n1 & 0xc0) !== 0x80 || (n2 & 0xc0) !== 0x80 || (n3 & 0xc0) !== 0x80) {
520
+ throw new Error(INVALID_UTF8);
521
+ }
522
+ b = (b & 0x0f) << 18 | (n1 & 0x3f) << 12 | (n2 & 0x3f) << 6 | (n3 & 0x3f);
523
+ min = 0x10000;
524
+ }
525
+ else {
526
+ throw new Error(INVALID_UTF8);
527
+ }
528
+ if (b < min || (b >= 0xd800 && b <= 0xdfff)) {
529
+ throw new Error(INVALID_UTF8);
530
+ }
531
+ if (b >= 0x10000) {
532
+ // Surrogate pair.
533
+ if (b > 0x10ffff) {
534
+ throw new Error(INVALID_UTF8);
535
+ }
536
+ b -= 0x10000;
537
+ chars.push(String.fromCharCode(0xd800 | (b >> 10)));
538
+ b = 0xdc00 | (b & 0x3ff);
539
+ }
540
+ }
541
+ chars.push(String.fromCharCode(b));
542
+ }
543
+ return chars.join("");
544
+ }
545
+ exports.decode = decode;
546
+
547
+
548
+ /***/ }),
549
+ /* 2 */
550
+ /***/ (function(module, exports, __webpack_require__) {
551
+
552
+ // required so we don't have to do require('pusher').default etc.
553
+ module.exports = __webpack_require__(3).default;
554
+
555
+
556
+ /***/ }),
557
+ /* 3 */
558
+ /***/ (function(module, __webpack_exports__, __webpack_require__) {
559
+
560
+ "use strict";
561
+ // ESM COMPAT FLAG
562
+ __webpack_require__.r(__webpack_exports__);
563
+
564
+ // CONCATENATED MODULE: ./src/core/base64.ts
565
+ function encode(s) {
566
+ return btoa(utob(s));
567
+ }
568
+ var fromCharCode = String.fromCharCode;
569
+ var b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
570
+ var b64tab = {};
571
+ for (var base64_i = 0, l = b64chars.length; base64_i < l; base64_i++) {
572
+ b64tab[b64chars.charAt(base64_i)] = base64_i;
573
+ }
574
+ var cb_utob = function (c) {
575
+ var cc = c.charCodeAt(0);
576
+ return cc < 0x80
577
+ ? c
578
+ : cc < 0x800
579
+ ? fromCharCode(0xc0 | (cc >>> 6)) + fromCharCode(0x80 | (cc & 0x3f))
580
+ : fromCharCode(0xe0 | ((cc >>> 12) & 0x0f)) +
581
+ fromCharCode(0x80 | ((cc >>> 6) & 0x3f)) +
582
+ fromCharCode(0x80 | (cc & 0x3f));
583
+ };
584
+ var utob = function (u) {
585
+ return u.replace(/[^\x00-\x7F]/g, cb_utob);
586
+ };
587
+ var cb_encode = function (ccc) {
588
+ var padlen = [0, 2, 1][ccc.length % 3];
589
+ var ord = (ccc.charCodeAt(0) << 16) |
590
+ ((ccc.length > 1 ? ccc.charCodeAt(1) : 0) << 8) |
591
+ (ccc.length > 2 ? ccc.charCodeAt(2) : 0);
592
+ var chars = [
593
+ b64chars.charAt(ord >>> 18),
594
+ b64chars.charAt((ord >>> 12) & 63),
595
+ padlen >= 2 ? '=' : b64chars.charAt((ord >>> 6) & 63),
596
+ padlen >= 1 ? '=' : b64chars.charAt(ord & 63)
597
+ ];
598
+ return chars.join('');
599
+ };
600
+ var btoa = self.btoa ||
601
+ function (b) {
602
+ return b.replace(/[\s\S]{1,3}/g, cb_encode);
603
+ };
604
+
605
+ // CONCATENATED MODULE: ./src/core/utils/timers/abstract_timer.ts
606
+ class Timer {
607
+ constructor(set, clear, delay, callback) {
608
+ this.clear = clear;
609
+ this.timer = set(() => {
610
+ if (this.timer) {
611
+ this.timer = callback(this.timer);
612
+ }
613
+ }, delay);
614
+ }
615
+ isRunning() {
616
+ return this.timer !== null;
617
+ }
618
+ ensureAborted() {
619
+ if (this.timer) {
620
+ this.clear(this.timer);
621
+ this.timer = null;
622
+ }
623
+ }
624
+ }
625
+ /* harmony default export */ var abstract_timer = (Timer);
626
+
627
+ // CONCATENATED MODULE: ./src/core/utils/timers/index.ts
628
+
629
+ function timers_clearTimeout(timer) {
630
+ self.clearTimeout(timer);
631
+ }
632
+ function timers_clearInterval(timer) {
633
+ self.clearInterval(timer);
634
+ }
635
+ class timers_OneOffTimer extends abstract_timer {
636
+ constructor(delay, callback) {
637
+ super(setTimeout, timers_clearTimeout, delay, function (timer) {
638
+ callback();
639
+ return null;
640
+ });
641
+ }
642
+ }
643
+ class timers_PeriodicTimer extends abstract_timer {
644
+ constructor(delay, callback) {
645
+ super(setInterval, timers_clearInterval, delay, function (timer) {
646
+ callback();
647
+ return timer;
648
+ });
649
+ }
650
+ }
651
+
652
+ // CONCATENATED MODULE: ./src/core/util.ts
653
+
654
+ var Util = {
655
+ now() {
656
+ if (Date.now) {
657
+ return Date.now();
658
+ }
659
+ else {
660
+ return new Date().valueOf();
661
+ }
662
+ },
663
+ defer(callback) {
664
+ return new timers_OneOffTimer(0, callback);
665
+ },
666
+ method(name, ...args) {
667
+ var boundArguments = Array.prototype.slice.call(arguments, 1);
668
+ return function (object) {
669
+ return object[name].apply(object, boundArguments.concat(arguments));
670
+ };
671
+ }
672
+ };
673
+ /* harmony default export */ var util = (Util);
674
+
675
+ // CONCATENATED MODULE: ./src/core/utils/collections.ts
676
+
677
+
678
+ function extend(target, ...sources) {
679
+ for (var i = 0; i < sources.length; i++) {
680
+ var extensions = sources[i];
681
+ for (var property in extensions) {
682
+ if (extensions[property] &&
683
+ extensions[property].constructor &&
684
+ extensions[property].constructor === Object) {
685
+ target[property] = extend(target[property] || {}, extensions[property]);
686
+ }
687
+ else {
688
+ target[property] = extensions[property];
689
+ }
690
+ }
691
+ }
692
+ return target;
693
+ }
694
+ function stringify() {
695
+ var m = ['Pusher'];
696
+ for (var i = 0; i < arguments.length; i++) {
697
+ if (typeof arguments[i] === 'string') {
698
+ m.push(arguments[i]);
699
+ }
700
+ else {
701
+ m.push(safeJSONStringify(arguments[i]));
702
+ }
703
+ }
704
+ return m.join(' : ');
705
+ }
706
+ function arrayIndexOf(array, item) {
707
+ var nativeIndexOf = Array.prototype.indexOf;
708
+ if (array === null) {
709
+ return -1;
710
+ }
711
+ if (nativeIndexOf && array.indexOf === nativeIndexOf) {
712
+ return array.indexOf(item);
713
+ }
714
+ for (var i = 0, l = array.length; i < l; i++) {
715
+ if (array[i] === item) {
716
+ return i;
717
+ }
718
+ }
719
+ return -1;
720
+ }
721
+ function objectApply(object, f) {
722
+ for (var key in object) {
723
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
724
+ f(object[key], key, object);
725
+ }
726
+ }
727
+ }
728
+ function keys(object) {
729
+ var keys = [];
730
+ objectApply(object, function (_, key) {
731
+ keys.push(key);
732
+ });
733
+ return keys;
734
+ }
735
+ function values(object) {
736
+ var values = [];
737
+ objectApply(object, function (value) {
738
+ values.push(value);
739
+ });
740
+ return values;
741
+ }
742
+ function apply(array, f, context) {
743
+ for (var i = 0; i < array.length; i++) {
744
+ f.call(context || self, array[i], i, array);
745
+ }
746
+ }
747
+ function map(array, f) {
748
+ var result = [];
749
+ for (var i = 0; i < array.length; i++) {
750
+ result.push(f(array[i], i, array, result));
751
+ }
752
+ return result;
753
+ }
754
+ function mapObject(object, f) {
755
+ var result = {};
756
+ objectApply(object, function (value, key) {
757
+ result[key] = f(value);
758
+ });
759
+ return result;
760
+ }
761
+ function filter(array, test) {
762
+ test =
763
+ test ||
764
+ function (value) {
765
+ return !!value;
766
+ };
767
+ var result = [];
768
+ for (var i = 0; i < array.length; i++) {
769
+ if (test(array[i], i, array, result)) {
770
+ result.push(array[i]);
771
+ }
772
+ }
773
+ return result;
774
+ }
775
+ function filterObject(object, test) {
776
+ var result = {};
777
+ objectApply(object, function (value, key) {
778
+ if ((test && test(value, key, object, result)) || Boolean(value)) {
779
+ result[key] = value;
780
+ }
781
+ });
782
+ return result;
783
+ }
784
+ function flatten(object) {
785
+ var result = [];
786
+ objectApply(object, function (value, key) {
787
+ result.push([key, value]);
788
+ });
789
+ return result;
790
+ }
791
+ function any(array, test) {
792
+ for (var i = 0; i < array.length; i++) {
793
+ if (test(array[i], i, array)) {
794
+ return true;
795
+ }
796
+ }
797
+ return false;
798
+ }
799
+ function collections_all(array, test) {
800
+ for (var i = 0; i < array.length; i++) {
801
+ if (!test(array[i], i, array)) {
802
+ return false;
803
+ }
804
+ }
805
+ return true;
806
+ }
807
+ function encodeParamsObject(data) {
808
+ return mapObject(data, function (value) {
809
+ if (typeof value === 'object') {
810
+ value = safeJSONStringify(value);
811
+ }
812
+ return encodeURIComponent(encode(value.toString()));
813
+ });
814
+ }
815
+ function buildQueryString(data) {
816
+ var params = filterObject(data, function (value) {
817
+ return value !== undefined;
818
+ });
819
+ var query = map(flatten(encodeParamsObject(params)), util.method('join', '=')).join('&');
820
+ return query;
821
+ }
822
+ function decycleObject(object) {
823
+ var objects = [], paths = [];
824
+ return (function derez(value, path) {
825
+ var i, name, nu;
826
+ switch (typeof value) {
827
+ case 'object':
828
+ if (!value) {
829
+ return null;
830
+ }
831
+ for (i = 0; i < objects.length; i += 1) {
832
+ if (objects[i] === value) {
833
+ return { $ref: paths[i] };
834
+ }
835
+ }
836
+ objects.push(value);
837
+ paths.push(path);
838
+ if (Object.prototype.toString.apply(value) === '[object Array]') {
839
+ nu = [];
840
+ for (i = 0; i < value.length; i += 1) {
841
+ nu[i] = derez(value[i], path + '[' + i + ']');
842
+ }
843
+ }
844
+ else {
845
+ nu = {};
846
+ for (name in value) {
847
+ if (Object.prototype.hasOwnProperty.call(value, name)) {
848
+ nu[name] = derez(value[name], path + '[' + JSON.stringify(name) + ']');
849
+ }
850
+ }
851
+ }
852
+ return nu;
853
+ case 'number':
854
+ case 'string':
855
+ case 'boolean':
856
+ return value;
857
+ }
858
+ })(object, '$');
859
+ }
860
+ function safeJSONStringify(source) {
861
+ try {
862
+ return JSON.stringify(source);
863
+ }
864
+ catch (e) {
865
+ return JSON.stringify(decycleObject(source));
866
+ }
867
+ }
868
+
869
+ // CONCATENATED MODULE: ./src/core/defaults.ts
870
+ var Defaults = {
871
+ VERSION: "8.3.0",
872
+ PROTOCOL: 7,
873
+ wsPort: 80,
874
+ wssPort: 443,
875
+ wsPath: '',
876
+ httpHost: 'sockjs.pusher.com',
877
+ httpPort: 80,
878
+ httpsPort: 443,
879
+ httpPath: '/pusher',
880
+ stats_host: 'stats.pusher.com',
881
+ authEndpoint: '/pusher/auth',
882
+ authTransport: 'ajax',
883
+ activityTimeout: 120000,
884
+ pongTimeout: 30000,
885
+ unavailableTimeout: 10000,
886
+ userAuthentication: {
887
+ endpoint: '/pusher/user-auth',
888
+ transport: 'ajax'
889
+ },
890
+ channelAuthorization: {
891
+ endpoint: '/pusher/auth',
892
+ transport: 'ajax'
893
+ },
894
+ cdn_http: "http://js.pusher.com",
895
+ cdn_https: "https://js.pusher.com",
896
+ dependency_suffix: ""
897
+ };
898
+ /* harmony default export */ var defaults = (Defaults);
899
+
900
+ // CONCATENATED MODULE: ./src/core/transports/url_schemes.ts
901
+
902
+ function getGenericURL(baseScheme, params, path) {
903
+ var scheme = baseScheme + (params.useTLS ? 's' : '');
904
+ var host = params.useTLS ? params.hostTLS : params.hostNonTLS;
905
+ return scheme + '://' + host + path;
906
+ }
907
+ function getGenericPath(key, queryString) {
908
+ var path = '/app/' + key;
909
+ var query = '?protocol=' +
910
+ defaults.PROTOCOL +
911
+ '&client=js' +
912
+ '&version=' +
913
+ defaults.VERSION +
914
+ (queryString ? '&' + queryString : '');
915
+ return path + query;
916
+ }
917
+ var ws = {
918
+ getInitial: function (key, params) {
919
+ var path = (params.httpPath || '') + getGenericPath(key, 'flash=false');
920
+ return getGenericURL('ws', params, path);
921
+ }
922
+ };
923
+ var http = {
924
+ getInitial: function (key, params) {
925
+ var path = (params.httpPath || '/pusher') + getGenericPath(key);
926
+ return getGenericURL('http', params, path);
927
+ }
928
+ };
929
+ var sockjs = {
930
+ getInitial: function (key, params) {
931
+ return getGenericURL('http', params, params.httpPath || '/pusher');
932
+ },
933
+ getPath: function (key, params) {
934
+ return getGenericPath(key);
935
+ }
936
+ };
937
+
938
+ // CONCATENATED MODULE: ./src/core/events/callback_registry.ts
939
+
940
+ class callback_registry_CallbackRegistry {
941
+ constructor() {
942
+ this._callbacks = {};
943
+ }
944
+ get(name) {
945
+ return this._callbacks[prefix(name)];
946
+ }
947
+ add(name, callback, context) {
948
+ var prefixedEventName = prefix(name);
949
+ this._callbacks[prefixedEventName] =
950
+ this._callbacks[prefixedEventName] || [];
951
+ this._callbacks[prefixedEventName].push({
952
+ fn: callback,
953
+ context: context
954
+ });
955
+ }
956
+ remove(name, callback, context) {
957
+ if (!name && !callback && !context) {
958
+ this._callbacks = {};
959
+ return;
960
+ }
961
+ var names = name ? [prefix(name)] : keys(this._callbacks);
962
+ if (callback || context) {
963
+ this.removeCallback(names, callback, context);
964
+ }
965
+ else {
966
+ this.removeAllCallbacks(names);
967
+ }
968
+ }
969
+ removeCallback(names, callback, context) {
970
+ apply(names, function (name) {
971
+ this._callbacks[name] = filter(this._callbacks[name] || [], function (binding) {
972
+ return ((callback && callback !== binding.fn) ||
973
+ (context && context !== binding.context));
974
+ });
975
+ if (this._callbacks[name].length === 0) {
976
+ delete this._callbacks[name];
977
+ }
978
+ }, this);
979
+ }
980
+ removeAllCallbacks(names) {
981
+ apply(names, function (name) {
982
+ delete this._callbacks[name];
983
+ }, this);
984
+ }
985
+ }
986
+ function prefix(name) {
987
+ return '_' + name;
988
+ }
989
+
990
+ // CONCATENATED MODULE: ./src/core/events/dispatcher.ts
991
+
992
+
993
+ class dispatcher_Dispatcher {
994
+ constructor(failThrough) {
995
+ this.callbacks = new callback_registry_CallbackRegistry();
996
+ this.global_callbacks = [];
997
+ this.failThrough = failThrough;
998
+ }
999
+ bind(eventName, callback, context) {
1000
+ this.callbacks.add(eventName, callback, context);
1001
+ return this;
1002
+ }
1003
+ bind_global(callback) {
1004
+ this.global_callbacks.push(callback);
1005
+ return this;
1006
+ }
1007
+ unbind(eventName, callback, context) {
1008
+ this.callbacks.remove(eventName, callback, context);
1009
+ return this;
1010
+ }
1011
+ unbind_global(callback) {
1012
+ if (!callback) {
1013
+ this.global_callbacks = [];
1014
+ return this;
1015
+ }
1016
+ this.global_callbacks = filter(this.global_callbacks || [], c => c !== callback);
1017
+ return this;
1018
+ }
1019
+ unbind_all() {
1020
+ this.unbind();
1021
+ this.unbind_global();
1022
+ return this;
1023
+ }
1024
+ emit(eventName, data, metadata) {
1025
+ for (var i = 0; i < this.global_callbacks.length; i++) {
1026
+ this.global_callbacks[i](eventName, data);
1027
+ }
1028
+ var callbacks = this.callbacks.get(eventName);
1029
+ var args = [];
1030
+ if (metadata) {
1031
+ args.push(data, metadata);
1032
+ }
1033
+ else if (data) {
1034
+ args.push(data);
1035
+ }
1036
+ if (callbacks && callbacks.length > 0) {
1037
+ for (var i = 0; i < callbacks.length; i++) {
1038
+ callbacks[i].fn.apply(callbacks[i].context || self, args);
1039
+ }
1040
+ }
1041
+ else if (this.failThrough) {
1042
+ this.failThrough(eventName, data);
1043
+ }
1044
+ return this;
1045
+ }
1046
+ }
1047
+
1048
+ // CONCATENATED MODULE: ./src/core/logger.ts
1049
+
1050
+
1051
+ class logger_Logger {
1052
+ constructor() {
1053
+ this.globalLog = (message) => {
1054
+ if (self.console && self.console.log) {
1055
+ self.console.log(message);
1056
+ }
1057
+ };
1058
+ }
1059
+ debug(...args) {
1060
+ this.log(this.globalLog, args);
1061
+ }
1062
+ warn(...args) {
1063
+ this.log(this.globalLogWarn, args);
1064
+ }
1065
+ error(...args) {
1066
+ this.log(this.globalLogError, args);
1067
+ }
1068
+ globalLogWarn(message) {
1069
+ if (self.console && self.console.warn) {
1070
+ self.console.warn(message);
1071
+ }
1072
+ else {
1073
+ this.globalLog(message);
1074
+ }
1075
+ }
1076
+ globalLogError(message) {
1077
+ if (self.console && self.console.error) {
1078
+ self.console.error(message);
1079
+ }
1080
+ else {
1081
+ this.globalLogWarn(message);
1082
+ }
1083
+ }
1084
+ log(defaultLoggingFunction, ...args) {
1085
+ var message = stringify.apply(this, arguments);
1086
+ if (core_pusher.log) {
1087
+ core_pusher.log(message);
1088
+ }
1089
+ else if (core_pusher.logToConsole) {
1090
+ const log = defaultLoggingFunction.bind(this);
1091
+ log(message);
1092
+ }
1093
+ }
1094
+ }
1095
+ /* harmony default export */ var logger = (new logger_Logger());
1096
+
1097
+ // CONCATENATED MODULE: ./src/core/transports/transport_connection.ts
1098
+
1099
+
1100
+
1101
+
1102
+
1103
+ class transport_connection_TransportConnection extends dispatcher_Dispatcher {
1104
+ constructor(hooks, name, priority, key, options) {
1105
+ super();
1106
+ this.initialize = worker_runtime.transportConnectionInitializer;
1107
+ this.hooks = hooks;
1108
+ this.name = name;
1109
+ this.priority = priority;
1110
+ this.key = key;
1111
+ this.options = options;
1112
+ this.state = 'new';
1113
+ this.timeline = options.timeline;
1114
+ this.activityTimeout = options.activityTimeout;
1115
+ this.id = this.timeline.generateUniqueID();
1116
+ }
1117
+ handlesActivityChecks() {
1118
+ return Boolean(this.hooks.handlesActivityChecks);
1119
+ }
1120
+ supportsPing() {
1121
+ return Boolean(this.hooks.supportsPing);
1122
+ }
1123
+ connect() {
1124
+ if (this.socket || this.state !== 'initialized') {
1125
+ return false;
1126
+ }
1127
+ var url = this.hooks.urls.getInitial(this.key, this.options);
1128
+ try {
1129
+ this.socket = this.hooks.getSocket(url, this.options);
1130
+ }
1131
+ catch (e) {
1132
+ util.defer(() => {
1133
+ this.onError(e);
1134
+ this.changeState('closed');
1135
+ });
1136
+ return false;
1137
+ }
1138
+ this.bindListeners();
1139
+ logger.debug('Connecting', { transport: this.name, url });
1140
+ this.changeState('connecting');
1141
+ return true;
1142
+ }
1143
+ close() {
1144
+ if (this.socket) {
1145
+ this.socket.close();
1146
+ return true;
1147
+ }
1148
+ else {
1149
+ return false;
1150
+ }
1151
+ }
1152
+ send(data) {
1153
+ if (this.state === 'open') {
1154
+ util.defer(() => {
1155
+ if (this.socket) {
1156
+ this.socket.send(data);
1157
+ }
1158
+ });
1159
+ return true;
1160
+ }
1161
+ else {
1162
+ return false;
1163
+ }
1164
+ }
1165
+ ping() {
1166
+ if (this.state === 'open' && this.supportsPing()) {
1167
+ this.socket.ping();
1168
+ }
1169
+ }
1170
+ onOpen() {
1171
+ if (this.hooks.beforeOpen) {
1172
+ this.hooks.beforeOpen(this.socket, this.hooks.urls.getPath(this.key, this.options));
1173
+ }
1174
+ this.changeState('open');
1175
+ this.socket.onopen = undefined;
1176
+ }
1177
+ onError(error) {
1178
+ this.emit('error', { type: 'WebSocketError', error: error });
1179
+ this.timeline.error(this.buildTimelineMessage({ error: error.toString() }));
1180
+ }
1181
+ onClose(closeEvent) {
1182
+ if (closeEvent) {
1183
+ this.changeState('closed', {
1184
+ code: closeEvent.code,
1185
+ reason: closeEvent.reason,
1186
+ wasClean: closeEvent.wasClean
1187
+ });
1188
+ }
1189
+ else {
1190
+ this.changeState('closed');
1191
+ }
1192
+ this.unbindListeners();
1193
+ this.socket = undefined;
1194
+ }
1195
+ onMessage(message) {
1196
+ this.emit('message', message);
1197
+ }
1198
+ onActivity() {
1199
+ this.emit('activity');
1200
+ }
1201
+ bindListeners() {
1202
+ this.socket.onopen = () => {
1203
+ this.onOpen();
1204
+ };
1205
+ this.socket.onerror = error => {
1206
+ this.onError(error);
1207
+ };
1208
+ this.socket.onclose = closeEvent => {
1209
+ this.onClose(closeEvent);
1210
+ };
1211
+ this.socket.onmessage = message => {
1212
+ this.onMessage(message);
1213
+ };
1214
+ if (this.supportsPing()) {
1215
+ this.socket.onactivity = () => {
1216
+ this.onActivity();
1217
+ };
1218
+ }
1219
+ }
1220
+ unbindListeners() {
1221
+ if (this.socket) {
1222
+ this.socket.onopen = undefined;
1223
+ this.socket.onerror = undefined;
1224
+ this.socket.onclose = undefined;
1225
+ this.socket.onmessage = undefined;
1226
+ if (this.supportsPing()) {
1227
+ this.socket.onactivity = undefined;
1228
+ }
1229
+ }
1230
+ }
1231
+ changeState(state, params) {
1232
+ this.state = state;
1233
+ this.timeline.info(this.buildTimelineMessage({
1234
+ state: state,
1235
+ params: params
1236
+ }));
1237
+ this.emit(state, params);
1238
+ }
1239
+ buildTimelineMessage(message) {
1240
+ return extend({ cid: this.id }, message);
1241
+ }
1242
+ }
1243
+
1244
+ // CONCATENATED MODULE: ./src/core/transports/transport.ts
1245
+
1246
+ class transport_Transport {
1247
+ constructor(hooks) {
1248
+ this.hooks = hooks;
1249
+ }
1250
+ isSupported(environment) {
1251
+ return this.hooks.isSupported(environment);
1252
+ }
1253
+ createConnection(name, priority, key, options) {
1254
+ return new transport_connection_TransportConnection(this.hooks, name, priority, key, options);
1255
+ }
1256
+ }
1257
+
1258
+ // CONCATENATED MODULE: ./src/runtimes/isomorphic/transports/transports.ts
1259
+
1260
+
1261
+
1262
+
1263
+ var WSTransport = new transport_Transport({
1264
+ urls: ws,
1265
+ handlesActivityChecks: false,
1266
+ supportsPing: false,
1267
+ isInitialized: function () {
1268
+ return Boolean(worker_runtime.getWebSocketAPI());
1269
+ },
1270
+ isSupported: function () {
1271
+ return Boolean(worker_runtime.getWebSocketAPI());
1272
+ },
1273
+ getSocket: function (url) {
1274
+ return worker_runtime.createWebSocket(url);
1275
+ }
1276
+ });
1277
+ var httpConfiguration = {
1278
+ urls: http,
1279
+ handlesActivityChecks: false,
1280
+ supportsPing: true,
1281
+ isInitialized: function () {
1282
+ return true;
1283
+ }
1284
+ };
1285
+ var streamingConfiguration = extend({
1286
+ getSocket: function (url) {
1287
+ return worker_runtime.HTTPFactory.createStreamingSocket(url);
1288
+ }
1289
+ }, httpConfiguration);
1290
+ var pollingConfiguration = extend({
1291
+ getSocket: function (url) {
1292
+ return worker_runtime.HTTPFactory.createPollingSocket(url);
1293
+ }
1294
+ }, httpConfiguration);
1295
+ var xhrConfiguration = {
1296
+ isSupported: function () {
1297
+ return worker_runtime.isXHRSupported();
1298
+ }
1299
+ };
1300
+ var XHRStreamingTransport = new transport_Transport((extend({}, streamingConfiguration, xhrConfiguration)));
1301
+ var XHRPollingTransport = new transport_Transport(extend({}, pollingConfiguration, xhrConfiguration));
1302
+ var Transports = {
1303
+ ws: WSTransport,
1304
+ xhr_streaming: XHRStreamingTransport,
1305
+ xhr_polling: XHRPollingTransport
1306
+ };
1307
+ /* harmony default export */ var transports = (Transports);
1308
+
1309
+ // CONCATENATED MODULE: ./src/core/connection/protocol/protocol.ts
1310
+ const Protocol = {
1311
+ decodeMessage: function (messageEvent) {
1312
+ try {
1313
+ var messageData = JSON.parse(messageEvent.data);
1314
+ var pusherEventData = messageData.data;
1315
+ if (typeof pusherEventData === 'string') {
1316
+ try {
1317
+ pusherEventData = JSON.parse(messageData.data);
1318
+ }
1319
+ catch (e) { }
1320
+ }
1321
+ var pusherEvent = {
1322
+ event: messageData.event,
1323
+ channel: messageData.channel,
1324
+ data: pusherEventData
1325
+ };
1326
+ if (messageData.user_id) {
1327
+ pusherEvent.user_id = messageData.user_id;
1328
+ }
1329
+ return pusherEvent;
1330
+ }
1331
+ catch (e) {
1332
+ throw { type: 'MessageParseError', error: e, data: messageEvent.data };
1333
+ }
1334
+ },
1335
+ encodeMessage: function (event) {
1336
+ return JSON.stringify(event);
1337
+ },
1338
+ processHandshake: function (messageEvent) {
1339
+ var message = Protocol.decodeMessage(messageEvent);
1340
+ if (message.event === 'pusher:connection_established') {
1341
+ if (!message.data.activity_timeout) {
1342
+ throw 'No activity timeout specified in handshake';
1343
+ }
1344
+ return {
1345
+ action: 'connected',
1346
+ id: message.data.socket_id,
1347
+ activityTimeout: message.data.activity_timeout * 1000
1348
+ };
1349
+ }
1350
+ else if (message.event === 'pusher:error') {
1351
+ return {
1352
+ action: this.getCloseAction(message.data),
1353
+ error: this.getCloseError(message.data)
1354
+ };
1355
+ }
1356
+ else {
1357
+ throw 'Invalid handshake';
1358
+ }
1359
+ },
1360
+ getCloseAction: function (closeEvent) {
1361
+ if (closeEvent.code < 4000) {
1362
+ if (closeEvent.code >= 1002 && closeEvent.code <= 1004) {
1363
+ return 'backoff';
1364
+ }
1365
+ else {
1366
+ return null;
1367
+ }
1368
+ }
1369
+ else if (closeEvent.code === 4000) {
1370
+ return 'tls_only';
1371
+ }
1372
+ else if (closeEvent.code < 4100) {
1373
+ return 'refused';
1374
+ }
1375
+ else if (closeEvent.code < 4200) {
1376
+ return 'backoff';
1377
+ }
1378
+ else if (closeEvent.code < 4300) {
1379
+ return 'retry';
1380
+ }
1381
+ else {
1382
+ return 'refused';
1383
+ }
1384
+ },
1385
+ getCloseError: function (closeEvent) {
1386
+ if (closeEvent.code !== 1000 && closeEvent.code !== 1001) {
1387
+ return {
1388
+ type: 'PusherError',
1389
+ data: {
1390
+ code: closeEvent.code,
1391
+ message: closeEvent.reason || closeEvent.message
1392
+ }
1393
+ };
1394
+ }
1395
+ else {
1396
+ return null;
1397
+ }
1398
+ }
1399
+ };
1400
+ /* harmony default export */ var protocol = (Protocol);
1401
+
1402
+ // CONCATENATED MODULE: ./src/core/connection/connection.ts
1403
+
1404
+
1405
+
1406
+
1407
+ class connection_Connection extends dispatcher_Dispatcher {
1408
+ constructor(id, transport) {
1409
+ super();
1410
+ this.id = id;
1411
+ this.transport = transport;
1412
+ this.activityTimeout = transport.activityTimeout;
1413
+ this.bindListeners();
1414
+ }
1415
+ handlesActivityChecks() {
1416
+ return this.transport.handlesActivityChecks();
1417
+ }
1418
+ send(data) {
1419
+ return this.transport.send(data);
1420
+ }
1421
+ send_event(name, data, channel) {
1422
+ var event = { event: name, data: data };
1423
+ if (channel) {
1424
+ event.channel = channel;
1425
+ }
1426
+ logger.debug('Event sent', event);
1427
+ return this.send(protocol.encodeMessage(event));
1428
+ }
1429
+ ping() {
1430
+ if (this.transport.supportsPing()) {
1431
+ this.transport.ping();
1432
+ }
1433
+ else {
1434
+ this.send_event('pusher:ping', {});
1435
+ }
1436
+ }
1437
+ close() {
1438
+ this.transport.close();
1439
+ }
1440
+ bindListeners() {
1441
+ var listeners = {
1442
+ message: (messageEvent) => {
1443
+ var pusherEvent;
1444
+ try {
1445
+ pusherEvent = protocol.decodeMessage(messageEvent);
1446
+ }
1447
+ catch (e) {
1448
+ this.emit('error', {
1449
+ type: 'MessageParseError',
1450
+ error: e,
1451
+ data: messageEvent.data
1452
+ });
1453
+ }
1454
+ if (pusherEvent !== undefined) {
1455
+ logger.debug('Event recd', pusherEvent);
1456
+ switch (pusherEvent.event) {
1457
+ case 'pusher:error':
1458
+ this.emit('error', {
1459
+ type: 'PusherError',
1460
+ data: pusherEvent.data
1461
+ });
1462
+ break;
1463
+ case 'pusher:ping':
1464
+ this.emit('ping');
1465
+ break;
1466
+ case 'pusher:pong':
1467
+ this.emit('pong');
1468
+ break;
1469
+ }
1470
+ this.emit('message', pusherEvent);
1471
+ }
1472
+ },
1473
+ activity: () => {
1474
+ this.emit('activity');
1475
+ },
1476
+ error: error => {
1477
+ this.emit('error', error);
1478
+ },
1479
+ closed: closeEvent => {
1480
+ unbindListeners();
1481
+ if (closeEvent && closeEvent.code) {
1482
+ this.handleCloseEvent(closeEvent);
1483
+ }
1484
+ this.transport = null;
1485
+ this.emit('closed');
1486
+ }
1487
+ };
1488
+ var unbindListeners = () => {
1489
+ objectApply(listeners, (listener, event) => {
1490
+ this.transport.unbind(event, listener);
1491
+ });
1492
+ };
1493
+ objectApply(listeners, (listener, event) => {
1494
+ this.transport.bind(event, listener);
1495
+ });
1496
+ }
1497
+ handleCloseEvent(closeEvent) {
1498
+ var action = protocol.getCloseAction(closeEvent);
1499
+ var error = protocol.getCloseError(closeEvent);
1500
+ if (error) {
1501
+ this.emit('error', error);
1502
+ }
1503
+ if (action) {
1504
+ this.emit(action, { action: action, error: error });
1505
+ }
1506
+ }
1507
+ }
1508
+
1509
+ // CONCATENATED MODULE: ./src/core/connection/handshake/index.ts
1510
+
1511
+
1512
+
1513
+ class handshake_Handshake {
1514
+ constructor(transport, callback) {
1515
+ this.transport = transport;
1516
+ this.callback = callback;
1517
+ this.bindListeners();
1518
+ }
1519
+ close() {
1520
+ this.unbindListeners();
1521
+ this.transport.close();
1522
+ }
1523
+ bindListeners() {
1524
+ this.onMessage = m => {
1525
+ this.unbindListeners();
1526
+ var result;
1527
+ try {
1528
+ result = protocol.processHandshake(m);
1529
+ }
1530
+ catch (e) {
1531
+ this.finish('error', { error: e });
1532
+ this.transport.close();
1533
+ return;
1534
+ }
1535
+ if (result.action === 'connected') {
1536
+ this.finish('connected', {
1537
+ connection: new connection_Connection(result.id, this.transport),
1538
+ activityTimeout: result.activityTimeout
1539
+ });
1540
+ }
1541
+ else {
1542
+ this.finish(result.action, { error: result.error });
1543
+ this.transport.close();
1544
+ }
1545
+ };
1546
+ this.onClosed = closeEvent => {
1547
+ this.unbindListeners();
1548
+ var action = protocol.getCloseAction(closeEvent) || 'backoff';
1549
+ var error = protocol.getCloseError(closeEvent);
1550
+ this.finish(action, { error: error });
1551
+ };
1552
+ this.transport.bind('message', this.onMessage);
1553
+ this.transport.bind('closed', this.onClosed);
1554
+ }
1555
+ unbindListeners() {
1556
+ this.transport.unbind('message', this.onMessage);
1557
+ this.transport.unbind('closed', this.onClosed);
1558
+ }
1559
+ finish(action, params) {
1560
+ this.callback(extend({ transport: this.transport, action: action }, params));
1561
+ }
1562
+ }
1563
+
1564
+ // CONCATENATED MODULE: ./src/core/transports/assistant_to_the_transport_manager.ts
1565
+
1566
+
1567
+ class assistant_to_the_transport_manager_AssistantToTheTransportManager {
1568
+ constructor(manager, transport, options) {
1569
+ this.manager = manager;
1570
+ this.transport = transport;
1571
+ this.minPingDelay = options.minPingDelay;
1572
+ this.maxPingDelay = options.maxPingDelay;
1573
+ this.pingDelay = undefined;
1574
+ }
1575
+ createConnection(name, priority, key, options) {
1576
+ options = extend({}, options, {
1577
+ activityTimeout: this.pingDelay
1578
+ });
1579
+ var connection = this.transport.createConnection(name, priority, key, options);
1580
+ var openTimestamp = null;
1581
+ var onOpen = function () {
1582
+ connection.unbind('open', onOpen);
1583
+ connection.bind('closed', onClosed);
1584
+ openTimestamp = util.now();
1585
+ };
1586
+ var onClosed = closeEvent => {
1587
+ connection.unbind('closed', onClosed);
1588
+ if (closeEvent.code === 1002 || closeEvent.code === 1003) {
1589
+ this.manager.reportDeath();
1590
+ }
1591
+ else if (!closeEvent.wasClean && openTimestamp) {
1592
+ var lifespan = util.now() - openTimestamp;
1593
+ if (lifespan < 2 * this.maxPingDelay) {
1594
+ this.manager.reportDeath();
1595
+ this.pingDelay = Math.max(lifespan / 2, this.minPingDelay);
1596
+ }
1597
+ }
1598
+ };
1599
+ connection.bind('open', onOpen);
1600
+ return connection;
1601
+ }
1602
+ isSupported(environment) {
1603
+ return this.manager.isAlive() && this.transport.isSupported(environment);
1604
+ }
1605
+ }
1606
+
1607
+ // CONCATENATED MODULE: ./src/core/errors.ts
1608
+ class BadEventName extends Error {
1609
+ constructor(msg) {
1610
+ super(msg);
1611
+ Object.setPrototypeOf(this, new.target.prototype);
1612
+ }
1613
+ }
1614
+ class BadChannelName extends Error {
1615
+ constructor(msg) {
1616
+ super(msg);
1617
+ Object.setPrototypeOf(this, new.target.prototype);
1618
+ }
1619
+ }
1620
+ class RequestTimedOut extends Error {
1621
+ constructor(msg) {
1622
+ super(msg);
1623
+ Object.setPrototypeOf(this, new.target.prototype);
1624
+ }
1625
+ }
1626
+ class TransportPriorityTooLow extends Error {
1627
+ constructor(msg) {
1628
+ super(msg);
1629
+ Object.setPrototypeOf(this, new.target.prototype);
1630
+ }
1631
+ }
1632
+ class TransportClosed extends Error {
1633
+ constructor(msg) {
1634
+ super(msg);
1635
+ Object.setPrototypeOf(this, new.target.prototype);
1636
+ }
1637
+ }
1638
+ class UnsupportedFeature extends Error {
1639
+ constructor(msg) {
1640
+ super(msg);
1641
+ Object.setPrototypeOf(this, new.target.prototype);
1642
+ }
1643
+ }
1644
+ class UnsupportedTransport extends Error {
1645
+ constructor(msg) {
1646
+ super(msg);
1647
+ Object.setPrototypeOf(this, new.target.prototype);
1648
+ }
1649
+ }
1650
+ class UnsupportedStrategy extends Error {
1651
+ constructor(msg) {
1652
+ super(msg);
1653
+ Object.setPrototypeOf(this, new.target.prototype);
1654
+ }
1655
+ }
1656
+ class HTTPAuthError extends Error {
1657
+ constructor(status, msg) {
1658
+ super(msg);
1659
+ this.status = status;
1660
+ Object.setPrototypeOf(this, new.target.prototype);
1661
+ }
1662
+ }
1663
+
1664
+ // CONCATENATED MODULE: ./src/core/utils/url_store.ts
1665
+ const urlStore = {
1666
+ baseUrl: 'https://pusher.com',
1667
+ urls: {
1668
+ authenticationEndpoint: {
1669
+ path: '/docs/channels/server_api/authenticating_users'
1670
+ },
1671
+ authorizationEndpoint: {
1672
+ path: '/docs/channels/server_api/authorizing-users/'
1673
+ },
1674
+ javascriptQuickStart: {
1675
+ path: '/docs/javascript_quick_start'
1676
+ },
1677
+ triggeringClientEvents: {
1678
+ path: '/docs/client_api_guide/client_events#trigger-events'
1679
+ },
1680
+ encryptedChannelSupport: {
1681
+ fullUrl: 'https://github.com/pusher/pusher-js/tree/cc491015371a4bde5743d1c87a0fbac0feb53195#encrypted-channel-support'
1682
+ }
1683
+ }
1684
+ };
1685
+ const buildLogSuffix = function (key) {
1686
+ const urlPrefix = 'See:';
1687
+ const urlObj = urlStore.urls[key];
1688
+ if (!urlObj)
1689
+ return '';
1690
+ let url;
1691
+ if (urlObj.fullUrl) {
1692
+ url = urlObj.fullUrl;
1693
+ }
1694
+ else if (urlObj.path) {
1695
+ url = urlStore.baseUrl + urlObj.path;
1696
+ }
1697
+ if (!url)
1698
+ return '';
1699
+ return `${urlPrefix} ${url}`;
1700
+ };
1701
+ /* harmony default export */ var url_store = ({ buildLogSuffix });
1702
+
1703
+ // CONCATENATED MODULE: ./src/core/channels/channel.ts
1704
+
1705
+
1706
+
1707
+
1708
+
1709
+ class channel_Channel extends dispatcher_Dispatcher {
1710
+ constructor(name, pusher) {
1711
+ super(function (event, data) {
1712
+ logger.debug('No callbacks on ' + name + ' for ' + event);
1713
+ });
1714
+ this.name = name;
1715
+ this.pusher = pusher;
1716
+ this.subscribed = false;
1717
+ this.subscriptionPending = false;
1718
+ this.subscriptionCancelled = false;
1719
+ }
1720
+ authorize(socketId, callback) {
1721
+ return callback(null, { auth: '' });
1722
+ }
1723
+ trigger(event, data) {
1724
+ if (event.indexOf('client-') !== 0) {
1725
+ throw new BadEventName("Event '" + event + "' does not start with 'client-'");
1726
+ }
1727
+ if (!this.subscribed) {
1728
+ var suffix = url_store.buildLogSuffix('triggeringClientEvents');
1729
+ logger.warn(`Client event triggered before channel 'subscription_succeeded' event . ${suffix}`);
1730
+ }
1731
+ return this.pusher.send_event(event, data, this.name);
1732
+ }
1733
+ disconnect() {
1734
+ this.subscribed = false;
1735
+ this.subscriptionPending = false;
1736
+ }
1737
+ handleEvent(event) {
1738
+ var eventName = event.event;
1739
+ var data = event.data;
1740
+ if (eventName === 'pusher_internal:subscription_succeeded') {
1741
+ this.handleSubscriptionSucceededEvent(event);
1742
+ }
1743
+ else if (eventName === 'pusher_internal:subscription_count') {
1744
+ this.handleSubscriptionCountEvent(event);
1745
+ }
1746
+ else if (eventName.indexOf('pusher_internal:') !== 0) {
1747
+ var metadata = {};
1748
+ this.emit(eventName, data, metadata);
1749
+ }
1750
+ }
1751
+ handleSubscriptionSucceededEvent(event) {
1752
+ this.subscriptionPending = false;
1753
+ this.subscribed = true;
1754
+ if (this.subscriptionCancelled) {
1755
+ this.pusher.unsubscribe(this.name);
1756
+ }
1757
+ else {
1758
+ this.emit('pusher:subscription_succeeded', event.data);
1759
+ }
1760
+ }
1761
+ handleSubscriptionCountEvent(event) {
1762
+ if (event.data.subscription_count) {
1763
+ this.subscriptionCount = event.data.subscription_count;
1764
+ }
1765
+ this.emit('pusher:subscription_count', event.data);
1766
+ }
1767
+ subscribe() {
1768
+ if (this.subscribed) {
1769
+ return;
1770
+ }
1771
+ this.subscriptionPending = true;
1772
+ this.subscriptionCancelled = false;
1773
+ this.authorize(this.pusher.connection.socket_id, (error, data) => {
1774
+ if (error) {
1775
+ this.subscriptionPending = false;
1776
+ logger.error(error.toString());
1777
+ this.emit('pusher:subscription_error', Object.assign({}, {
1778
+ type: 'AuthError',
1779
+ error: error.message
1780
+ }, error instanceof HTTPAuthError ? { status: error.status } : {}));
1781
+ }
1782
+ else {
1783
+ this.pusher.send_event('pusher:subscribe', {
1784
+ auth: data.auth,
1785
+ channel_data: data.channel_data,
1786
+ channel: this.name
1787
+ });
1788
+ }
1789
+ });
1790
+ }
1791
+ unsubscribe() {
1792
+ this.subscribed = false;
1793
+ this.pusher.send_event('pusher:unsubscribe', {
1794
+ channel: this.name
1795
+ });
1796
+ }
1797
+ cancelSubscription() {
1798
+ this.subscriptionCancelled = true;
1799
+ }
1800
+ reinstateSubscription() {
1801
+ this.subscriptionCancelled = false;
1802
+ }
1803
+ }
1804
+
1805
+ // CONCATENATED MODULE: ./src/core/channels/channels.ts
1806
+
1807
+
1808
+
1809
+
1810
+ class channels_Channels {
1811
+ constructor() {
1812
+ this.channels = {};
1813
+ }
1814
+ add(name, pusher) {
1815
+ if (!this.channels[name]) {
1816
+ this.channels[name] = createChannel(name, pusher);
1817
+ }
1818
+ return this.channels[name];
1819
+ }
1820
+ all() {
1821
+ return values(this.channels);
1822
+ }
1823
+ find(name) {
1824
+ return this.channels[name];
1825
+ }
1826
+ remove(name) {
1827
+ var channel = this.channels[name];
1828
+ delete this.channels[name];
1829
+ return channel;
1830
+ }
1831
+ disconnect() {
1832
+ objectApply(this.channels, function (channel) {
1833
+ channel.disconnect();
1834
+ });
1835
+ }
1836
+ }
1837
+ function createChannel(name, pusher) {
1838
+ if (name.indexOf('private-encrypted-') === 0) {
1839
+ if (pusher.config.nacl) {
1840
+ return factory.createEncryptedChannel(name, pusher, pusher.config.nacl);
1841
+ }
1842
+ let errMsg = 'Tried to subscribe to a private-encrypted- channel but no nacl implementation available';
1843
+ let suffix = url_store.buildLogSuffix('encryptedChannelSupport');
1844
+ throw new UnsupportedFeature(`${errMsg}. ${suffix}`);
1845
+ }
1846
+ else if (name.indexOf('private-') === 0) {
1847
+ return factory.createPrivateChannel(name, pusher);
1848
+ }
1849
+ else if (name.indexOf('presence-') === 0) {
1850
+ return factory.createPresenceChannel(name, pusher);
1851
+ }
1852
+ else if (name.indexOf('#') === 0) {
1853
+ throw new BadChannelName('Cannot create a channel with name "' + name + '".');
1854
+ }
1855
+ else {
1856
+ return factory.createChannel(name, pusher);
1857
+ }
1858
+ }
1859
+
1860
+ // EXTERNAL MODULE: ./node_modules/@stablelib/base64/lib/base64.js
1861
+ var base64 = __webpack_require__(0);
1862
+
1863
+ // EXTERNAL MODULE: ./node_modules/@stablelib/utf8/lib/utf8.js
1864
+ var utf8 = __webpack_require__(1);
1865
+
1866
+ // CONCATENATED MODULE: ./src/core/channels/private_channel.ts
1867
+
1868
+ class private_channel_PrivateChannel extends channel_Channel {
1869
+ authorize(socketId, callback) {
1870
+ return this.pusher.config.channelAuthorizer({
1871
+ channelName: this.name,
1872
+ socketId: socketId
1873
+ }, callback);
1874
+ }
1875
+ }
1876
+
1877
+ // CONCATENATED MODULE: ./src/core/channels/encrypted_channel.ts
1878
+
1879
+
1880
+
1881
+
1882
+
1883
+ class encrypted_channel_EncryptedChannel extends private_channel_PrivateChannel {
1884
+ constructor(name, pusher, nacl) {
1885
+ super(name, pusher);
1886
+ this.key = null;
1887
+ this.nacl = nacl;
1888
+ }
1889
+ authorize(socketId, callback) {
1890
+ super.authorize(socketId, (error, authData) => {
1891
+ if (error) {
1892
+ callback(error, authData);
1893
+ return;
1894
+ }
1895
+ let sharedSecret = authData['shared_secret'];
1896
+ if (!sharedSecret) {
1897
+ callback(new Error(`No shared_secret key in auth payload for encrypted channel: ${this.name}`), null);
1898
+ return;
1899
+ }
1900
+ this.key = Object(base64["decode"])(sharedSecret);
1901
+ delete authData['shared_secret'];
1902
+ callback(null, authData);
1903
+ });
1904
+ }
1905
+ trigger(event, data) {
1906
+ throw new UnsupportedFeature('Client events are not currently supported for encrypted channels');
1907
+ }
1908
+ handleEvent(event) {
1909
+ var eventName = event.event;
1910
+ var data = event.data;
1911
+ if (eventName.indexOf('pusher_internal:') === 0 ||
1912
+ eventName.indexOf('pusher:') === 0) {
1913
+ super.handleEvent(event);
1914
+ return;
1915
+ }
1916
+ this.handleEncryptedEvent(eventName, data);
1917
+ }
1918
+ handleEncryptedEvent(event, data) {
1919
+ if (!this.key) {
1920
+ logger.debug('Received encrypted event before key has been retrieved from the authEndpoint');
1921
+ return;
1922
+ }
1923
+ if (!data.ciphertext || !data.nonce) {
1924
+ logger.error('Unexpected format for encrypted event, expected object with `ciphertext` and `nonce` fields, got: ' +
1925
+ data);
1926
+ return;
1927
+ }
1928
+ let cipherText = Object(base64["decode"])(data.ciphertext);
1929
+ if (cipherText.length < this.nacl.secretbox.overheadLength) {
1930
+ logger.error(`Expected encrypted event ciphertext length to be ${this.nacl.secretbox.overheadLength}, got: ${cipherText.length}`);
1931
+ return;
1932
+ }
1933
+ let nonce = Object(base64["decode"])(data.nonce);
1934
+ if (nonce.length < this.nacl.secretbox.nonceLength) {
1935
+ logger.error(`Expected encrypted event nonce length to be ${this.nacl.secretbox.nonceLength}, got: ${nonce.length}`);
1936
+ return;
1937
+ }
1938
+ let bytes = this.nacl.secretbox.open(cipherText, nonce, this.key);
1939
+ if (bytes === null) {
1940
+ logger.debug('Failed to decrypt an event, probably because it was encrypted with a different key. Fetching a new key from the authEndpoint...');
1941
+ this.authorize(this.pusher.connection.socket_id, (error, authData) => {
1942
+ if (error) {
1943
+ logger.error(`Failed to make a request to the authEndpoint: ${authData}. Unable to fetch new key, so dropping encrypted event`);
1944
+ return;
1945
+ }
1946
+ bytes = this.nacl.secretbox.open(cipherText, nonce, this.key);
1947
+ if (bytes === null) {
1948
+ logger.error(`Failed to decrypt event with new key. Dropping encrypted event`);
1949
+ return;
1950
+ }
1951
+ this.emit(event, this.getDataToEmit(bytes));
1952
+ return;
1953
+ });
1954
+ return;
1955
+ }
1956
+ this.emit(event, this.getDataToEmit(bytes));
1957
+ }
1958
+ getDataToEmit(bytes) {
1959
+ let raw = Object(utf8["decode"])(bytes);
1960
+ try {
1961
+ return JSON.parse(raw);
1962
+ }
1963
+ catch (_a) {
1964
+ return raw;
1965
+ }
1966
+ }
1967
+ }
1968
+
1969
+ // CONCATENATED MODULE: ./src/core/channels/members.ts
1970
+
1971
+ class members_Members {
1972
+ constructor() {
1973
+ this.reset();
1974
+ }
1975
+ get(id) {
1976
+ if (Object.prototype.hasOwnProperty.call(this.members, id)) {
1977
+ return {
1978
+ id: id,
1979
+ info: this.members[id]
1980
+ };
1981
+ }
1982
+ else {
1983
+ return null;
1984
+ }
1985
+ }
1986
+ each(callback) {
1987
+ objectApply(this.members, (member, id) => {
1988
+ callback(this.get(id));
1989
+ });
1990
+ }
1991
+ setMyID(id) {
1992
+ this.myID = id;
1993
+ }
1994
+ onSubscription(subscriptionData) {
1995
+ this.members = subscriptionData.presence.hash;
1996
+ this.count = subscriptionData.presence.count;
1997
+ this.me = this.get(this.myID);
1998
+ }
1999
+ addMember(memberData) {
2000
+ if (this.get(memberData.user_id) === null) {
2001
+ this.count++;
2002
+ }
2003
+ this.members[memberData.user_id] = memberData.user_info;
2004
+ return this.get(memberData.user_id);
2005
+ }
2006
+ removeMember(memberData) {
2007
+ var member = this.get(memberData.user_id);
2008
+ if (member) {
2009
+ delete this.members[memberData.user_id];
2010
+ this.count--;
2011
+ }
2012
+ return member;
2013
+ }
2014
+ reset() {
2015
+ this.members = {};
2016
+ this.count = 0;
2017
+ this.myID = null;
2018
+ this.me = null;
2019
+ }
2020
+ }
2021
+
2022
+ // CONCATENATED MODULE: ./src/core/channels/presence_channel.ts
2023
+ var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
2024
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
2025
+ return new (P || (P = Promise))(function (resolve, reject) {
2026
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
2027
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
2028
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
2029
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
2030
+ });
2031
+ };
2032
+
2033
+
2034
+
2035
+
2036
+ class presence_channel_PresenceChannel extends private_channel_PrivateChannel {
2037
+ constructor(name, pusher) {
2038
+ super(name, pusher);
2039
+ this.members = new members_Members();
2040
+ }
2041
+ authorize(socketId, callback) {
2042
+ super.authorize(socketId, (error, authData) => __awaiter(this, void 0, void 0, function* () {
2043
+ if (!error) {
2044
+ authData = authData;
2045
+ if (authData.channel_data != null) {
2046
+ var channelData = JSON.parse(authData.channel_data);
2047
+ this.members.setMyID(channelData.user_id);
2048
+ }
2049
+ else {
2050
+ yield this.pusher.user.signinDonePromise;
2051
+ if (this.pusher.user.user_data != null) {
2052
+ this.members.setMyID(this.pusher.user.user_data.id);
2053
+ }
2054
+ else {
2055
+ let suffix = url_store.buildLogSuffix('authorizationEndpoint');
2056
+ logger.error(`Invalid auth response for channel '${this.name}', ` +
2057
+ `expected 'channel_data' field. ${suffix}, ` +
2058
+ `or the user should be signed in.`);
2059
+ callback('Invalid auth response');
2060
+ return;
2061
+ }
2062
+ }
2063
+ }
2064
+ callback(error, authData);
2065
+ }));
2066
+ }
2067
+ handleEvent(event) {
2068
+ var eventName = event.event;
2069
+ if (eventName.indexOf('pusher_internal:') === 0) {
2070
+ this.handleInternalEvent(event);
2071
+ }
2072
+ else {
2073
+ var data = event.data;
2074
+ var metadata = {};
2075
+ if (event.user_id) {
2076
+ metadata.user_id = event.user_id;
2077
+ }
2078
+ this.emit(eventName, data, metadata);
2079
+ }
2080
+ }
2081
+ handleInternalEvent(event) {
2082
+ var eventName = event.event;
2083
+ var data = event.data;
2084
+ switch (eventName) {
2085
+ case 'pusher_internal:subscription_succeeded':
2086
+ this.handleSubscriptionSucceededEvent(event);
2087
+ break;
2088
+ case 'pusher_internal:subscription_count':
2089
+ this.handleSubscriptionCountEvent(event);
2090
+ break;
2091
+ case 'pusher_internal:member_added':
2092
+ var addedMember = this.members.addMember(data);
2093
+ this.emit('pusher:member_added', addedMember);
2094
+ break;
2095
+ case 'pusher_internal:member_removed':
2096
+ var removedMember = this.members.removeMember(data);
2097
+ if (removedMember) {
2098
+ this.emit('pusher:member_removed', removedMember);
2099
+ }
2100
+ break;
2101
+ }
2102
+ }
2103
+ handleSubscriptionSucceededEvent(event) {
2104
+ this.subscriptionPending = false;
2105
+ this.subscribed = true;
2106
+ if (this.subscriptionCancelled) {
2107
+ this.pusher.unsubscribe(this.name);
2108
+ }
2109
+ else {
2110
+ this.members.onSubscription(event.data);
2111
+ this.emit('pusher:subscription_succeeded', this.members);
2112
+ }
2113
+ }
2114
+ disconnect() {
2115
+ this.members.reset();
2116
+ super.disconnect();
2117
+ }
2118
+ }
2119
+
2120
+ // CONCATENATED MODULE: ./src/core/connection/connection_manager.ts
2121
+
2122
+
2123
+
2124
+
2125
+
2126
+ class connection_manager_ConnectionManager extends dispatcher_Dispatcher {
2127
+ constructor(key, options) {
2128
+ super();
2129
+ this.state = 'initialized';
2130
+ this.connection = null;
2131
+ this.key = key;
2132
+ this.options = options;
2133
+ this.timeline = this.options.timeline;
2134
+ this.usingTLS = this.options.useTLS;
2135
+ this.errorCallbacks = this.buildErrorCallbacks();
2136
+ this.connectionCallbacks = this.buildConnectionCallbacks(this.errorCallbacks);
2137
+ this.handshakeCallbacks = this.buildHandshakeCallbacks(this.errorCallbacks);
2138
+ var Network = worker_runtime.getNetwork();
2139
+ Network.bind('online', () => {
2140
+ this.timeline.info({ netinfo: 'online' });
2141
+ if (this.state === 'connecting' || this.state === 'unavailable') {
2142
+ this.retryIn(0);
2143
+ }
2144
+ });
2145
+ Network.bind('offline', () => {
2146
+ this.timeline.info({ netinfo: 'offline' });
2147
+ if (this.connection) {
2148
+ this.sendActivityCheck();
2149
+ }
2150
+ });
2151
+ this.updateStrategy();
2152
+ }
2153
+ connect() {
2154
+ if (this.connection || this.runner) {
2155
+ return;
2156
+ }
2157
+ if (!this.strategy.isSupported()) {
2158
+ this.updateState('failed');
2159
+ return;
2160
+ }
2161
+ this.updateState('connecting');
2162
+ this.startConnecting();
2163
+ this.setUnavailableTimer();
2164
+ }
2165
+ send(data) {
2166
+ if (this.connection) {
2167
+ return this.connection.send(data);
2168
+ }
2169
+ else {
2170
+ return false;
2171
+ }
2172
+ }
2173
+ send_event(name, data, channel) {
2174
+ if (this.connection) {
2175
+ return this.connection.send_event(name, data, channel);
2176
+ }
2177
+ else {
2178
+ return false;
2179
+ }
2180
+ }
2181
+ disconnect() {
2182
+ this.disconnectInternally();
2183
+ this.updateState('disconnected');
2184
+ }
2185
+ isUsingTLS() {
2186
+ return this.usingTLS;
2187
+ }
2188
+ startConnecting() {
2189
+ var callback = (error, handshake) => {
2190
+ if (error) {
2191
+ this.runner = this.strategy.connect(0, callback);
2192
+ }
2193
+ else {
2194
+ if (handshake.action === 'error') {
2195
+ this.emit('error', {
2196
+ type: 'HandshakeError',
2197
+ error: handshake.error
2198
+ });
2199
+ this.timeline.error({ handshakeError: handshake.error });
2200
+ }
2201
+ else {
2202
+ this.abortConnecting();
2203
+ this.handshakeCallbacks[handshake.action](handshake);
2204
+ }
2205
+ }
2206
+ };
2207
+ this.runner = this.strategy.connect(0, callback);
2208
+ }
2209
+ abortConnecting() {
2210
+ if (this.runner) {
2211
+ this.runner.abort();
2212
+ this.runner = null;
2213
+ }
2214
+ }
2215
+ disconnectInternally() {
2216
+ this.abortConnecting();
2217
+ this.clearRetryTimer();
2218
+ this.clearUnavailableTimer();
2219
+ if (this.connection) {
2220
+ var connection = this.abandonConnection();
2221
+ connection.close();
2222
+ }
2223
+ }
2224
+ updateStrategy() {
2225
+ this.strategy = this.options.getStrategy({
2226
+ key: this.key,
2227
+ timeline: this.timeline,
2228
+ useTLS: this.usingTLS
2229
+ });
2230
+ }
2231
+ retryIn(delay) {
2232
+ this.timeline.info({ action: 'retry', delay: delay });
2233
+ if (delay > 0) {
2234
+ this.emit('connecting_in', Math.round(delay / 1000));
2235
+ }
2236
+ this.retryTimer = new timers_OneOffTimer(delay || 0, () => {
2237
+ this.disconnectInternally();
2238
+ this.connect();
2239
+ });
2240
+ }
2241
+ clearRetryTimer() {
2242
+ if (this.retryTimer) {
2243
+ this.retryTimer.ensureAborted();
2244
+ this.retryTimer = null;
2245
+ }
2246
+ }
2247
+ setUnavailableTimer() {
2248
+ this.unavailableTimer = new timers_OneOffTimer(this.options.unavailableTimeout, () => {
2249
+ this.updateState('unavailable');
2250
+ });
2251
+ }
2252
+ clearUnavailableTimer() {
2253
+ if (this.unavailableTimer) {
2254
+ this.unavailableTimer.ensureAborted();
2255
+ }
2256
+ }
2257
+ sendActivityCheck() {
2258
+ this.stopActivityCheck();
2259
+ this.connection.ping();
2260
+ this.activityTimer = new timers_OneOffTimer(this.options.pongTimeout, () => {
2261
+ this.timeline.error({ pong_timed_out: this.options.pongTimeout });
2262
+ this.retryIn(0);
2263
+ });
2264
+ }
2265
+ resetActivityCheck() {
2266
+ this.stopActivityCheck();
2267
+ if (this.connection && !this.connection.handlesActivityChecks()) {
2268
+ this.activityTimer = new timers_OneOffTimer(this.activityTimeout, () => {
2269
+ this.sendActivityCheck();
2270
+ });
2271
+ }
2272
+ }
2273
+ stopActivityCheck() {
2274
+ if (this.activityTimer) {
2275
+ this.activityTimer.ensureAborted();
2276
+ }
2277
+ }
2278
+ buildConnectionCallbacks(errorCallbacks) {
2279
+ return extend({}, errorCallbacks, {
2280
+ message: message => {
2281
+ this.resetActivityCheck();
2282
+ this.emit('message', message);
2283
+ },
2284
+ ping: () => {
2285
+ this.send_event('pusher:pong', {});
2286
+ },
2287
+ activity: () => {
2288
+ this.resetActivityCheck();
2289
+ },
2290
+ error: error => {
2291
+ this.emit('error', error);
2292
+ },
2293
+ closed: () => {
2294
+ this.abandonConnection();
2295
+ if (this.shouldRetry()) {
2296
+ this.retryIn(1000);
2297
+ }
2298
+ }
2299
+ });
2300
+ }
2301
+ buildHandshakeCallbacks(errorCallbacks) {
2302
+ return extend({}, errorCallbacks, {
2303
+ connected: (handshake) => {
2304
+ this.activityTimeout = Math.min(this.options.activityTimeout, handshake.activityTimeout, handshake.connection.activityTimeout || Infinity);
2305
+ this.clearUnavailableTimer();
2306
+ this.setConnection(handshake.connection);
2307
+ this.socket_id = this.connection.id;
2308
+ this.updateState('connected', { socket_id: this.socket_id });
2309
+ }
2310
+ });
2311
+ }
2312
+ buildErrorCallbacks() {
2313
+ let withErrorEmitted = callback => {
2314
+ return (result) => {
2315
+ if (result.error) {
2316
+ this.emit('error', { type: 'WebSocketError', error: result.error });
2317
+ }
2318
+ callback(result);
2319
+ };
2320
+ };
2321
+ return {
2322
+ tls_only: withErrorEmitted(() => {
2323
+ this.usingTLS = true;
2324
+ this.updateStrategy();
2325
+ this.retryIn(0);
2326
+ }),
2327
+ refused: withErrorEmitted(() => {
2328
+ this.disconnect();
2329
+ }),
2330
+ backoff: withErrorEmitted(() => {
2331
+ this.retryIn(1000);
2332
+ }),
2333
+ retry: withErrorEmitted(() => {
2334
+ this.retryIn(0);
2335
+ })
2336
+ };
2337
+ }
2338
+ setConnection(connection) {
2339
+ this.connection = connection;
2340
+ for (var event in this.connectionCallbacks) {
2341
+ this.connection.bind(event, this.connectionCallbacks[event]);
2342
+ }
2343
+ this.resetActivityCheck();
2344
+ }
2345
+ abandonConnection() {
2346
+ if (!this.connection) {
2347
+ return;
2348
+ }
2349
+ this.stopActivityCheck();
2350
+ for (var event in this.connectionCallbacks) {
2351
+ this.connection.unbind(event, this.connectionCallbacks[event]);
2352
+ }
2353
+ var connection = this.connection;
2354
+ this.connection = null;
2355
+ return connection;
2356
+ }
2357
+ updateState(newState, data) {
2358
+ var previousState = this.state;
2359
+ this.state = newState;
2360
+ if (previousState !== newState) {
2361
+ var newStateDescription = newState;
2362
+ if (newStateDescription === 'connected') {
2363
+ newStateDescription += ' with new socket ID ' + data.socket_id;
2364
+ }
2365
+ logger.debug('State changed', previousState + ' -> ' + newStateDescription);
2366
+ this.timeline.info({ state: newState, params: data });
2367
+ this.emit('state_change', { previous: previousState, current: newState });
2368
+ this.emit(newState, data);
2369
+ }
2370
+ }
2371
+ shouldRetry() {
2372
+ return this.state === 'connecting' || this.state === 'connected';
2373
+ }
2374
+ }
2375
+
2376
+ // CONCATENATED MODULE: ./src/core/timeline/timeline_sender.ts
2377
+
2378
+ class timeline_sender_TimelineSender {
2379
+ constructor(timeline, options) {
2380
+ this.timeline = timeline;
2381
+ this.options = options || {};
2382
+ }
2383
+ send(useTLS, callback) {
2384
+ if (this.timeline.isEmpty()) {
2385
+ return;
2386
+ }
2387
+ this.timeline.send(worker_runtime.TimelineTransport.getAgent(this, useTLS), callback);
2388
+ }
2389
+ }
2390
+
2391
+ // CONCATENATED MODULE: ./src/core/utils/factory.ts
2392
+
2393
+
2394
+
2395
+
2396
+
2397
+
2398
+
2399
+
2400
+
2401
+ var Factory = {
2402
+ createChannels() {
2403
+ return new channels_Channels();
2404
+ },
2405
+ createConnectionManager(key, options) {
2406
+ return new connection_manager_ConnectionManager(key, options);
2407
+ },
2408
+ createChannel(name, pusher) {
2409
+ return new channel_Channel(name, pusher);
2410
+ },
2411
+ createPrivateChannel(name, pusher) {
2412
+ return new private_channel_PrivateChannel(name, pusher);
2413
+ },
2414
+ createPresenceChannel(name, pusher) {
2415
+ return new presence_channel_PresenceChannel(name, pusher);
2416
+ },
2417
+ createEncryptedChannel(name, pusher, nacl) {
2418
+ return new encrypted_channel_EncryptedChannel(name, pusher, nacl);
2419
+ },
2420
+ createTimelineSender(timeline, options) {
2421
+ return new timeline_sender_TimelineSender(timeline, options);
2422
+ },
2423
+ createHandshake(transport, callback) {
2424
+ return new handshake_Handshake(transport, callback);
2425
+ },
2426
+ createAssistantToTheTransportManager(manager, transport, options) {
2427
+ return new assistant_to_the_transport_manager_AssistantToTheTransportManager(manager, transport, options);
2428
+ }
2429
+ };
2430
+ /* harmony default export */ var factory = (Factory);
2431
+
2432
+ // CONCATENATED MODULE: ./src/core/transports/transport_manager.ts
2433
+
2434
+ class transport_manager_TransportManager {
2435
+ constructor(options) {
2436
+ this.options = options || {};
2437
+ this.livesLeft = this.options.lives || Infinity;
2438
+ }
2439
+ getAssistant(transport) {
2440
+ return factory.createAssistantToTheTransportManager(this, transport, {
2441
+ minPingDelay: this.options.minPingDelay,
2442
+ maxPingDelay: this.options.maxPingDelay
2443
+ });
2444
+ }
2445
+ isAlive() {
2446
+ return this.livesLeft > 0;
2447
+ }
2448
+ reportDeath() {
2449
+ this.livesLeft -= 1;
2450
+ }
2451
+ }
2452
+
2453
+ // CONCATENATED MODULE: ./src/core/strategies/sequential_strategy.ts
2454
+
2455
+
2456
+
2457
+ class sequential_strategy_SequentialStrategy {
2458
+ constructor(strategies, options) {
2459
+ this.strategies = strategies;
2460
+ this.loop = Boolean(options.loop);
2461
+ this.failFast = Boolean(options.failFast);
2462
+ this.timeout = options.timeout;
2463
+ this.timeoutLimit = options.timeoutLimit;
2464
+ }
2465
+ isSupported() {
2466
+ return any(this.strategies, util.method('isSupported'));
2467
+ }
2468
+ connect(minPriority, callback) {
2469
+ var strategies = this.strategies;
2470
+ var current = 0;
2471
+ var timeout = this.timeout;
2472
+ var runner = null;
2473
+ var tryNextStrategy = (error, handshake) => {
2474
+ if (handshake) {
2475
+ callback(null, handshake);
2476
+ }
2477
+ else {
2478
+ current = current + 1;
2479
+ if (this.loop) {
2480
+ current = current % strategies.length;
2481
+ }
2482
+ if (current < strategies.length) {
2483
+ if (timeout) {
2484
+ timeout = timeout * 2;
2485
+ if (this.timeoutLimit) {
2486
+ timeout = Math.min(timeout, this.timeoutLimit);
2487
+ }
2488
+ }
2489
+ runner = this.tryStrategy(strategies[current], minPriority, { timeout, failFast: this.failFast }, tryNextStrategy);
2490
+ }
2491
+ else {
2492
+ callback(true);
2493
+ }
2494
+ }
2495
+ };
2496
+ runner = this.tryStrategy(strategies[current], minPriority, { timeout: timeout, failFast: this.failFast }, tryNextStrategy);
2497
+ return {
2498
+ abort: function () {
2499
+ runner.abort();
2500
+ },
2501
+ forceMinPriority: function (p) {
2502
+ minPriority = p;
2503
+ if (runner) {
2504
+ runner.forceMinPriority(p);
2505
+ }
2506
+ }
2507
+ };
2508
+ }
2509
+ tryStrategy(strategy, minPriority, options, callback) {
2510
+ var timer = null;
2511
+ var runner = null;
2512
+ if (options.timeout > 0) {
2513
+ timer = new timers_OneOffTimer(options.timeout, function () {
2514
+ runner.abort();
2515
+ callback(true);
2516
+ });
2517
+ }
2518
+ runner = strategy.connect(minPriority, function (error, handshake) {
2519
+ if (error && timer && timer.isRunning() && !options.failFast) {
2520
+ return;
2521
+ }
2522
+ if (timer) {
2523
+ timer.ensureAborted();
2524
+ }
2525
+ callback(error, handshake);
2526
+ });
2527
+ return {
2528
+ abort: function () {
2529
+ if (timer) {
2530
+ timer.ensureAborted();
2531
+ }
2532
+ runner.abort();
2533
+ },
2534
+ forceMinPriority: function (p) {
2535
+ runner.forceMinPriority(p);
2536
+ }
2537
+ };
2538
+ }
2539
+ }
2540
+
2541
+ // CONCATENATED MODULE: ./src/core/strategies/best_connected_ever_strategy.ts
2542
+
2543
+
2544
+ class best_connected_ever_strategy_BestConnectedEverStrategy {
2545
+ constructor(strategies) {
2546
+ this.strategies = strategies;
2547
+ }
2548
+ isSupported() {
2549
+ return any(this.strategies, util.method('isSupported'));
2550
+ }
2551
+ connect(minPriority, callback) {
2552
+ return connect(this.strategies, minPriority, function (i, runners) {
2553
+ return function (error, handshake) {
2554
+ runners[i].error = error;
2555
+ if (error) {
2556
+ if (allRunnersFailed(runners)) {
2557
+ callback(true);
2558
+ }
2559
+ return;
2560
+ }
2561
+ apply(runners, function (runner) {
2562
+ runner.forceMinPriority(handshake.transport.priority);
2563
+ });
2564
+ callback(null, handshake);
2565
+ };
2566
+ });
2567
+ }
2568
+ }
2569
+ function connect(strategies, minPriority, callbackBuilder) {
2570
+ var runners = map(strategies, function (strategy, i, _, rs) {
2571
+ return strategy.connect(minPriority, callbackBuilder(i, rs));
2572
+ });
2573
+ return {
2574
+ abort: function () {
2575
+ apply(runners, abortRunner);
2576
+ },
2577
+ forceMinPriority: function (p) {
2578
+ apply(runners, function (runner) {
2579
+ runner.forceMinPriority(p);
2580
+ });
2581
+ }
2582
+ };
2583
+ }
2584
+ function allRunnersFailed(runners) {
2585
+ return collections_all(runners, function (runner) {
2586
+ return Boolean(runner.error);
2587
+ });
2588
+ }
2589
+ function abortRunner(runner) {
2590
+ if (!runner.error && !runner.aborted) {
2591
+ runner.abort();
2592
+ runner.aborted = true;
2593
+ }
2594
+ }
2595
+
2596
+ // CONCATENATED MODULE: ./src/core/strategies/websocket_prioritized_cached_strategy.ts
2597
+
2598
+
2599
+
2600
+
2601
+ class websocket_prioritized_cached_strategy_WebSocketPrioritizedCachedStrategy {
2602
+ constructor(strategy, transports, options) {
2603
+ this.strategy = strategy;
2604
+ this.transports = transports;
2605
+ this.ttl = options.ttl || 1800 * 1000;
2606
+ this.usingTLS = options.useTLS;
2607
+ this.timeline = options.timeline;
2608
+ }
2609
+ isSupported() {
2610
+ return this.strategy.isSupported();
2611
+ }
2612
+ connect(minPriority, callback) {
2613
+ var usingTLS = this.usingTLS;
2614
+ var info = fetchTransportCache(usingTLS);
2615
+ var cacheSkipCount = info && info.cacheSkipCount ? info.cacheSkipCount : 0;
2616
+ var strategies = [this.strategy];
2617
+ if (info && info.timestamp + this.ttl >= util.now()) {
2618
+ var transport = this.transports[info.transport];
2619
+ if (transport) {
2620
+ if (['ws', 'wss'].includes(info.transport) || cacheSkipCount > 3) {
2621
+ this.timeline.info({
2622
+ cached: true,
2623
+ transport: info.transport,
2624
+ latency: info.latency
2625
+ });
2626
+ strategies.push(new sequential_strategy_SequentialStrategy([transport], {
2627
+ timeout: info.latency * 2 + 1000,
2628
+ failFast: true
2629
+ }));
2630
+ }
2631
+ else {
2632
+ cacheSkipCount++;
2633
+ }
2634
+ }
2635
+ }
2636
+ var startTimestamp = util.now();
2637
+ var runner = strategies
2638
+ .pop()
2639
+ .connect(minPriority, function cb(error, handshake) {
2640
+ if (error) {
2641
+ flushTransportCache(usingTLS);
2642
+ if (strategies.length > 0) {
2643
+ startTimestamp = util.now();
2644
+ runner = strategies.pop().connect(minPriority, cb);
2645
+ }
2646
+ else {
2647
+ callback(error);
2648
+ }
2649
+ }
2650
+ else {
2651
+ storeTransportCache(usingTLS, handshake.transport.name, util.now() - startTimestamp, cacheSkipCount);
2652
+ callback(null, handshake);
2653
+ }
2654
+ });
2655
+ return {
2656
+ abort: function () {
2657
+ runner.abort();
2658
+ },
2659
+ forceMinPriority: function (p) {
2660
+ minPriority = p;
2661
+ if (runner) {
2662
+ runner.forceMinPriority(p);
2663
+ }
2664
+ }
2665
+ };
2666
+ }
2667
+ }
2668
+ function getTransportCacheKey(usingTLS) {
2669
+ return 'pusherTransport' + (usingTLS ? 'TLS' : 'NonTLS');
2670
+ }
2671
+ function fetchTransportCache(usingTLS) {
2672
+ var storage = worker_runtime.getLocalStorage();
2673
+ if (storage) {
2674
+ try {
2675
+ var serializedCache = storage[getTransportCacheKey(usingTLS)];
2676
+ if (serializedCache) {
2677
+ return JSON.parse(serializedCache);
2678
+ }
2679
+ }
2680
+ catch (e) {
2681
+ flushTransportCache(usingTLS);
2682
+ }
2683
+ }
2684
+ return null;
2685
+ }
2686
+ function storeTransportCache(usingTLS, transport, latency, cacheSkipCount) {
2687
+ var storage = worker_runtime.getLocalStorage();
2688
+ if (storage) {
2689
+ try {
2690
+ storage[getTransportCacheKey(usingTLS)] = safeJSONStringify({
2691
+ timestamp: util.now(),
2692
+ transport: transport,
2693
+ latency: latency,
2694
+ cacheSkipCount: cacheSkipCount
2695
+ });
2696
+ }
2697
+ catch (e) {
2698
+ }
2699
+ }
2700
+ }
2701
+ function flushTransportCache(usingTLS) {
2702
+ var storage = worker_runtime.getLocalStorage();
2703
+ if (storage) {
2704
+ try {
2705
+ delete storage[getTransportCacheKey(usingTLS)];
2706
+ }
2707
+ catch (e) {
2708
+ }
2709
+ }
2710
+ }
2711
+
2712
+ // CONCATENATED MODULE: ./src/core/strategies/delayed_strategy.ts
2713
+
2714
+ class delayed_strategy_DelayedStrategy {
2715
+ constructor(strategy, { delay: number }) {
2716
+ this.strategy = strategy;
2717
+ this.options = { delay: number };
2718
+ }
2719
+ isSupported() {
2720
+ return this.strategy.isSupported();
2721
+ }
2722
+ connect(minPriority, callback) {
2723
+ var strategy = this.strategy;
2724
+ var runner;
2725
+ var timer = new timers_OneOffTimer(this.options.delay, function () {
2726
+ runner = strategy.connect(minPriority, callback);
2727
+ });
2728
+ return {
2729
+ abort: function () {
2730
+ timer.ensureAborted();
2731
+ if (runner) {
2732
+ runner.abort();
2733
+ }
2734
+ },
2735
+ forceMinPriority: function (p) {
2736
+ minPriority = p;
2737
+ if (runner) {
2738
+ runner.forceMinPriority(p);
2739
+ }
2740
+ }
2741
+ };
2742
+ }
2743
+ }
2744
+
2745
+ // CONCATENATED MODULE: ./src/core/strategies/if_strategy.ts
2746
+ class IfStrategy {
2747
+ constructor(test, trueBranch, falseBranch) {
2748
+ this.test = test;
2749
+ this.trueBranch = trueBranch;
2750
+ this.falseBranch = falseBranch;
2751
+ }
2752
+ isSupported() {
2753
+ var branch = this.test() ? this.trueBranch : this.falseBranch;
2754
+ return branch.isSupported();
2755
+ }
2756
+ connect(minPriority, callback) {
2757
+ var branch = this.test() ? this.trueBranch : this.falseBranch;
2758
+ return branch.connect(minPriority, callback);
2759
+ }
2760
+ }
2761
+
2762
+ // CONCATENATED MODULE: ./src/core/strategies/first_connected_strategy.ts
2763
+ class FirstConnectedStrategy {
2764
+ constructor(strategy) {
2765
+ this.strategy = strategy;
2766
+ }
2767
+ isSupported() {
2768
+ return this.strategy.isSupported();
2769
+ }
2770
+ connect(minPriority, callback) {
2771
+ var runner = this.strategy.connect(minPriority, function (error, handshake) {
2772
+ if (handshake) {
2773
+ runner.abort();
2774
+ }
2775
+ callback(error, handshake);
2776
+ });
2777
+ return runner;
2778
+ }
2779
+ }
2780
+
2781
+ // CONCATENATED MODULE: ./src/runtimes/isomorphic/default_strategy.ts
2782
+
2783
+
2784
+
2785
+
2786
+
2787
+
2788
+
2789
+
2790
+ function testSupportsStrategy(strategy) {
2791
+ return function () {
2792
+ return strategy.isSupported();
2793
+ };
2794
+ }
2795
+ var getDefaultStrategy = function (config, baseOptions, defineTransport) {
2796
+ var definedTransports = {};
2797
+ function defineTransportStrategy(name, type, priority, options, manager) {
2798
+ var transport = defineTransport(config, name, type, priority, options, manager);
2799
+ definedTransports[name] = transport;
2800
+ return transport;
2801
+ }
2802
+ var ws_options = Object.assign({}, baseOptions, {
2803
+ hostNonTLS: config.wsHost + ':' + config.wsPort,
2804
+ hostTLS: config.wsHost + ':' + config.wssPort,
2805
+ httpPath: config.wsPath
2806
+ });
2807
+ var wss_options = extend({}, ws_options, {
2808
+ useTLS: true
2809
+ });
2810
+ var http_options = Object.assign({}, baseOptions, {
2811
+ hostNonTLS: config.httpHost + ':' + config.httpPort,
2812
+ hostTLS: config.httpHost + ':' + config.httpsPort,
2813
+ httpPath: config.httpPath
2814
+ });
2815
+ var timeouts = {
2816
+ loop: true,
2817
+ timeout: 15000,
2818
+ timeoutLimit: 60000
2819
+ };
2820
+ var ws_manager = new transport_manager_TransportManager({
2821
+ minPingDelay: 10000,
2822
+ maxPingDelay: config.activityTimeout
2823
+ });
2824
+ var streaming_manager = new transport_manager_TransportManager({
2825
+ lives: 2,
2826
+ minPingDelay: 10000,
2827
+ maxPingDelay: config.activityTimeout
2828
+ });
2829
+ var ws_transport = defineTransportStrategy('ws', 'ws', 3, ws_options, ws_manager);
2830
+ var wss_transport = defineTransportStrategy('wss', 'ws', 3, wss_options, ws_manager);
2831
+ var xhr_streaming_transport = defineTransportStrategy('xhr_streaming', 'xhr_streaming', 1, http_options, streaming_manager);
2832
+ var xhr_polling_transport = defineTransportStrategy('xhr_polling', 'xhr_polling', 1, http_options);
2833
+ var ws_loop = new sequential_strategy_SequentialStrategy([ws_transport], timeouts);
2834
+ var wss_loop = new sequential_strategy_SequentialStrategy([wss_transport], timeouts);
2835
+ var streaming_loop = new sequential_strategy_SequentialStrategy([xhr_streaming_transport], timeouts);
2836
+ var polling_loop = new sequential_strategy_SequentialStrategy([xhr_polling_transport], timeouts);
2837
+ var http_loop = new sequential_strategy_SequentialStrategy([
2838
+ new IfStrategy(testSupportsStrategy(streaming_loop), new best_connected_ever_strategy_BestConnectedEverStrategy([
2839
+ streaming_loop,
2840
+ new delayed_strategy_DelayedStrategy(polling_loop, { delay: 4000 })
2841
+ ]), polling_loop)
2842
+ ], timeouts);
2843
+ var wsStrategy;
2844
+ if (baseOptions.useTLS) {
2845
+ wsStrategy = new best_connected_ever_strategy_BestConnectedEverStrategy([
2846
+ ws_loop,
2847
+ new delayed_strategy_DelayedStrategy(http_loop, { delay: 2000 })
2848
+ ]);
2849
+ }
2850
+ else {
2851
+ wsStrategy = new best_connected_ever_strategy_BestConnectedEverStrategy([
2852
+ ws_loop,
2853
+ new delayed_strategy_DelayedStrategy(wss_loop, { delay: 2000 }),
2854
+ new delayed_strategy_DelayedStrategy(http_loop, { delay: 5000 })
2855
+ ]);
2856
+ }
2857
+ return new websocket_prioritized_cached_strategy_WebSocketPrioritizedCachedStrategy(new FirstConnectedStrategy(new IfStrategy(testSupportsStrategy(ws_transport), wsStrategy, http_loop)), definedTransports, {
2858
+ ttl: 1800000,
2859
+ timeline: baseOptions.timeline,
2860
+ useTLS: baseOptions.useTLS
2861
+ });
2862
+ };
2863
+ /* harmony default export */ var default_strategy = (getDefaultStrategy);
2864
+
2865
+ // CONCATENATED MODULE: ./src/runtimes/isomorphic/transports/transport_connection_initializer.ts
2866
+ /* harmony default export */ var transport_connection_initializer = (function () {
2867
+ var self = this;
2868
+ self.timeline.info(self.buildTimelineMessage({
2869
+ transport: self.name + (self.options.useTLS ? 's' : '')
2870
+ }));
2871
+ if (self.hooks.isInitialized()) {
2872
+ self.changeState('initialized');
2873
+ }
2874
+ else {
2875
+ self.onClose();
2876
+ }
2877
+ });
2878
+
2879
+ // CONCATENATED MODULE: ./src/core/http/http_request.ts
2880
+
2881
+
2882
+ const MAX_BUFFER_LENGTH = 256 * 1024;
2883
+ class http_request_HTTPRequest extends dispatcher_Dispatcher {
2884
+ constructor(hooks, method, url) {
2885
+ super();
2886
+ this.hooks = hooks;
2887
+ this.method = method;
2888
+ this.url = url;
2889
+ }
2890
+ start(payload) {
2891
+ this.position = 0;
2892
+ this.xhr = this.hooks.getRequest(this);
2893
+ this.unloader = () => {
2894
+ this.close();
2895
+ };
2896
+ worker_runtime.addUnloadListener(this.unloader);
2897
+ this.xhr.open(this.method, this.url, true);
2898
+ if (this.xhr.setRequestHeader) {
2899
+ this.xhr.setRequestHeader('Content-Type', 'application/json');
2900
+ }
2901
+ this.xhr.send(payload);
2902
+ }
2903
+ close() {
2904
+ if (this.unloader) {
2905
+ worker_runtime.removeUnloadListener(this.unloader);
2906
+ this.unloader = null;
2907
+ }
2908
+ if (this.xhr) {
2909
+ this.hooks.abortRequest(this.xhr);
2910
+ this.xhr = null;
2911
+ }
2912
+ }
2913
+ onChunk(status, data) {
2914
+ while (true) {
2915
+ var chunk = this.advanceBuffer(data);
2916
+ if (chunk) {
2917
+ this.emit('chunk', { status: status, data: chunk });
2918
+ }
2919
+ else {
2920
+ break;
2921
+ }
2922
+ }
2923
+ if (this.isBufferTooLong(data)) {
2924
+ this.emit('buffer_too_long');
2925
+ }
2926
+ }
2927
+ advanceBuffer(buffer) {
2928
+ var unreadData = buffer.slice(this.position);
2929
+ var endOfLinePosition = unreadData.indexOf('\n');
2930
+ if (endOfLinePosition !== -1) {
2931
+ this.position += endOfLinePosition + 1;
2932
+ return unreadData.slice(0, endOfLinePosition);
2933
+ }
2934
+ else {
2935
+ return null;
2936
+ }
2937
+ }
2938
+ isBufferTooLong(buffer) {
2939
+ return this.position === buffer.length && buffer.length > MAX_BUFFER_LENGTH;
2940
+ }
2941
+ }
2942
+
2943
+ // CONCATENATED MODULE: ./src/core/http/state.ts
2944
+ var State;
2945
+ (function (State) {
2946
+ State[State["CONNECTING"] = 0] = "CONNECTING";
2947
+ State[State["OPEN"] = 1] = "OPEN";
2948
+ State[State["CLOSED"] = 3] = "CLOSED";
2949
+ })(State || (State = {}));
2950
+ /* harmony default export */ var state = (State);
2951
+
2952
+ // CONCATENATED MODULE: ./src/core/http/http_socket.ts
2953
+
2954
+
2955
+
2956
+ var autoIncrement = 1;
2957
+ class http_socket_HTTPSocket {
2958
+ constructor(hooks, url) {
2959
+ this.hooks = hooks;
2960
+ this.session = randomNumber(1000) + '/' + randomString(8);
2961
+ this.location = getLocation(url);
2962
+ this.readyState = state.CONNECTING;
2963
+ this.openStream();
2964
+ }
2965
+ send(payload) {
2966
+ return this.sendRaw(JSON.stringify([payload]));
2967
+ }
2968
+ ping() {
2969
+ this.hooks.sendHeartbeat(this);
2970
+ }
2971
+ close(code, reason) {
2972
+ this.onClose(code, reason, true);
2973
+ }
2974
+ sendRaw(payload) {
2975
+ if (this.readyState === state.OPEN) {
2976
+ try {
2977
+ worker_runtime.createSocketRequest('POST', getUniqueURL(getSendURL(this.location, this.session))).start(payload);
2978
+ return true;
2979
+ }
2980
+ catch (e) {
2981
+ return false;
2982
+ }
2983
+ }
2984
+ else {
2985
+ return false;
2986
+ }
2987
+ }
2988
+ reconnect() {
2989
+ this.closeStream();
2990
+ this.openStream();
2991
+ }
2992
+ onClose(code, reason, wasClean) {
2993
+ this.closeStream();
2994
+ this.readyState = state.CLOSED;
2995
+ if (this.onclose) {
2996
+ this.onclose({
2997
+ code: code,
2998
+ reason: reason,
2999
+ wasClean: wasClean
3000
+ });
3001
+ }
3002
+ }
3003
+ onChunk(chunk) {
3004
+ if (chunk.status !== 200) {
3005
+ return;
3006
+ }
3007
+ if (this.readyState === state.OPEN) {
3008
+ this.onActivity();
3009
+ }
3010
+ var payload;
3011
+ var type = chunk.data.slice(0, 1);
3012
+ switch (type) {
3013
+ case 'o':
3014
+ payload = JSON.parse(chunk.data.slice(1) || '{}');
3015
+ this.onOpen(payload);
3016
+ break;
3017
+ case 'a':
3018
+ payload = JSON.parse(chunk.data.slice(1) || '[]');
3019
+ for (var i = 0; i < payload.length; i++) {
3020
+ this.onEvent(payload[i]);
3021
+ }
3022
+ break;
3023
+ case 'm':
3024
+ payload = JSON.parse(chunk.data.slice(1) || 'null');
3025
+ this.onEvent(payload);
3026
+ break;
3027
+ case 'h':
3028
+ this.hooks.onHeartbeat(this);
3029
+ break;
3030
+ case 'c':
3031
+ payload = JSON.parse(chunk.data.slice(1) || '[]');
3032
+ this.onClose(payload[0], payload[1], true);
3033
+ break;
3034
+ }
3035
+ }
3036
+ onOpen(options) {
3037
+ if (this.readyState === state.CONNECTING) {
3038
+ if (options && options.hostname) {
3039
+ this.location.base = replaceHost(this.location.base, options.hostname);
3040
+ }
3041
+ this.readyState = state.OPEN;
3042
+ if (this.onopen) {
3043
+ this.onopen();
3044
+ }
3045
+ }
3046
+ else {
3047
+ this.onClose(1006, 'Server lost session', true);
3048
+ }
3049
+ }
3050
+ onEvent(event) {
3051
+ if (this.readyState === state.OPEN && this.onmessage) {
3052
+ this.onmessage({ data: event });
3053
+ }
3054
+ }
3055
+ onActivity() {
3056
+ if (this.onactivity) {
3057
+ this.onactivity();
3058
+ }
3059
+ }
3060
+ onError(error) {
3061
+ if (this.onerror) {
3062
+ this.onerror(error);
3063
+ }
3064
+ }
3065
+ openStream() {
3066
+ this.stream = worker_runtime.createSocketRequest('POST', getUniqueURL(this.hooks.getReceiveURL(this.location, this.session)));
3067
+ this.stream.bind('chunk', chunk => {
3068
+ this.onChunk(chunk);
3069
+ });
3070
+ this.stream.bind('finished', status => {
3071
+ this.hooks.onFinished(this, status);
3072
+ });
3073
+ this.stream.bind('buffer_too_long', () => {
3074
+ this.reconnect();
3075
+ });
3076
+ try {
3077
+ this.stream.start();
3078
+ }
3079
+ catch (error) {
3080
+ util.defer(() => {
3081
+ this.onError(error);
3082
+ this.onClose(1006, 'Could not start streaming', false);
3083
+ });
3084
+ }
3085
+ }
3086
+ closeStream() {
3087
+ if (this.stream) {
3088
+ this.stream.unbind_all();
3089
+ this.stream.close();
3090
+ this.stream = null;
3091
+ }
3092
+ }
3093
+ }
3094
+ function getLocation(url) {
3095
+ var parts = /([^\?]*)\/*(\??.*)/.exec(url);
3096
+ return {
3097
+ base: parts[1],
3098
+ queryString: parts[2]
3099
+ };
3100
+ }
3101
+ function getSendURL(url, session) {
3102
+ return url.base + '/' + session + '/xhr_send';
3103
+ }
3104
+ function getUniqueURL(url) {
3105
+ var separator = url.indexOf('?') === -1 ? '?' : '&';
3106
+ return url + separator + 't=' + +new Date() + '&n=' + autoIncrement++;
3107
+ }
3108
+ function replaceHost(url, hostname) {
3109
+ var urlParts = /(https?:\/\/)([^\/:]+)((\/|:)?.*)/.exec(url);
3110
+ return urlParts[1] + hostname + urlParts[3];
3111
+ }
3112
+ function randomNumber(max) {
3113
+ return worker_runtime.randomInt(max);
3114
+ }
3115
+ function randomString(length) {
3116
+ var result = [];
3117
+ for (var i = 0; i < length; i++) {
3118
+ result.push(randomNumber(32).toString(32));
3119
+ }
3120
+ return result.join('');
3121
+ }
3122
+ /* harmony default export */ var http_socket = (http_socket_HTTPSocket);
3123
+
3124
+ // CONCATENATED MODULE: ./src/core/http/http_streaming_socket.ts
3125
+ var http_streaming_socket_hooks = {
3126
+ getReceiveURL: function (url, session) {
3127
+ return url.base + '/' + session + '/xhr_streaming' + url.queryString;
3128
+ },
3129
+ onHeartbeat: function (socket) {
3130
+ socket.sendRaw('[]');
3131
+ },
3132
+ sendHeartbeat: function (socket) {
3133
+ socket.sendRaw('[]');
3134
+ },
3135
+ onFinished: function (socket, status) {
3136
+ socket.onClose(1006, 'Connection interrupted (' + status + ')', false);
3137
+ }
3138
+ };
3139
+ /* harmony default export */ var http_streaming_socket = (http_streaming_socket_hooks);
3140
+
3141
+ // CONCATENATED MODULE: ./src/core/http/http_polling_socket.ts
3142
+ var http_polling_socket_hooks = {
3143
+ getReceiveURL: function (url, session) {
3144
+ return url.base + '/' + session + '/xhr' + url.queryString;
3145
+ },
3146
+ onHeartbeat: function () {
3147
+ },
3148
+ sendHeartbeat: function (socket) {
3149
+ socket.sendRaw('[]');
3150
+ },
3151
+ onFinished: function (socket, status) {
3152
+ if (status === 200) {
3153
+ socket.reconnect();
3154
+ }
3155
+ else {
3156
+ socket.onClose(1006, 'Connection interrupted (' + status + ')', false);
3157
+ }
3158
+ }
3159
+ };
3160
+ /* harmony default export */ var http_polling_socket = (http_polling_socket_hooks);
3161
+
3162
+ // CONCATENATED MODULE: ./src/runtimes/isomorphic/http/http_xhr_request.ts
3163
+
3164
+ var http_xhr_request_hooks = {
3165
+ getRequest: function (socket) {
3166
+ var Constructor = worker_runtime.getXHRAPI();
3167
+ var xhr = new Constructor();
3168
+ xhr.onreadystatechange = xhr.onprogress = function () {
3169
+ switch (xhr.readyState) {
3170
+ case 3:
3171
+ if (xhr.responseText && xhr.responseText.length > 0) {
3172
+ socket.onChunk(xhr.status, xhr.responseText);
3173
+ }
3174
+ break;
3175
+ case 4:
3176
+ if (xhr.responseText && xhr.responseText.length > 0) {
3177
+ socket.onChunk(xhr.status, xhr.responseText);
3178
+ }
3179
+ socket.emit('finished', xhr.status);
3180
+ socket.close();
3181
+ break;
3182
+ }
3183
+ };
3184
+ return xhr;
3185
+ },
3186
+ abortRequest: function (xhr) {
3187
+ xhr.onreadystatechange = null;
3188
+ xhr.abort();
3189
+ }
3190
+ };
3191
+ /* harmony default export */ var http_xhr_request = (http_xhr_request_hooks);
3192
+
3193
+ // CONCATENATED MODULE: ./src/runtimes/isomorphic/http/http.ts
3194
+
3195
+
3196
+
3197
+
3198
+
3199
+ var HTTP = {
3200
+ createStreamingSocket(url) {
3201
+ return this.createSocket(http_streaming_socket, url);
3202
+ },
3203
+ createPollingSocket(url) {
3204
+ return this.createSocket(http_polling_socket, url);
3205
+ },
3206
+ createSocket(hooks, url) {
3207
+ return new http_socket(hooks, url);
3208
+ },
3209
+ createXHR(method, url) {
3210
+ return this.createRequest(http_xhr_request, method, url);
3211
+ },
3212
+ createRequest(hooks, method, url) {
3213
+ return new http_request_HTTPRequest(hooks, method, url);
3214
+ }
3215
+ };
3216
+ /* harmony default export */ var http_http = (HTTP);
3217
+
3218
+ // CONCATENATED MODULE: ./src/runtimes/isomorphic/runtime.ts
3219
+
3220
+
3221
+
3222
+
3223
+
3224
+ var Isomorphic = {
3225
+ getDefaultStrategy: default_strategy,
3226
+ Transports: transports,
3227
+ transportConnectionInitializer: transport_connection_initializer,
3228
+ HTTPFactory: http_http,
3229
+ setup(PusherClass) {
3230
+ PusherClass.ready();
3231
+ },
3232
+ getLocalStorage() {
3233
+ return undefined;
3234
+ },
3235
+ getClientFeatures() {
3236
+ return keys(filterObject({ ws: transports.ws }, function (t) {
3237
+ return t.isSupported({});
3238
+ }));
3239
+ },
3240
+ getProtocol() {
3241
+ return 'http:';
3242
+ },
3243
+ isXHRSupported() {
3244
+ return true;
3245
+ },
3246
+ createSocketRequest(method, url) {
3247
+ if (this.isXHRSupported()) {
3248
+ return this.HTTPFactory.createXHR(method, url);
3249
+ }
3250
+ else {
3251
+ throw 'Cross-origin HTTP requests are not supported';
3252
+ }
3253
+ },
3254
+ createXHR() {
3255
+ var Constructor = this.getXHRAPI();
3256
+ return new Constructor();
3257
+ },
3258
+ createWebSocket(url) {
3259
+ var Constructor = this.getWebSocketAPI();
3260
+ return new Constructor(url);
3261
+ },
3262
+ addUnloadListener(listener) { },
3263
+ removeUnloadListener(listener) { }
3264
+ };
3265
+ /* harmony default export */ var runtime = (Isomorphic);
3266
+
3267
+ // CONCATENATED MODULE: ./src/runtimes/worker/net_info.ts
3268
+
3269
+ class net_info_NetInfo extends dispatcher_Dispatcher {
3270
+ isOnline() {
3271
+ return true;
3272
+ }
3273
+ }
3274
+ var net_info_Network = new net_info_NetInfo();
3275
+
3276
+ // CONCATENATED MODULE: ./src/runtimes/worker/auth/fetch_auth.ts
3277
+
3278
+ var fetchAuth = function (context, query, authOptions, authRequestType, callback) {
3279
+ var headers = new Headers();
3280
+ headers.set('Content-Type', 'application/x-www-form-urlencoded');
3281
+ for (var headerName in authOptions.headers) {
3282
+ headers.set(headerName, authOptions.headers[headerName]);
3283
+ }
3284
+ if (authOptions.headersProvider != null) {
3285
+ const dynamicHeaders = authOptions.headersProvider();
3286
+ for (var headerName in dynamicHeaders) {
3287
+ headers.set(headerName, dynamicHeaders[headerName]);
3288
+ }
3289
+ }
3290
+ var body = query;
3291
+ var request = new Request(authOptions.endpoint, {
3292
+ headers,
3293
+ body,
3294
+ credentials: 'same-origin',
3295
+ method: 'POST'
3296
+ });
3297
+ return fetch(request)
3298
+ .then(response => {
3299
+ let { status } = response;
3300
+ if (status === 200) {
3301
+ return response.text();
3302
+ }
3303
+ throw new HTTPAuthError(status, `Could not get ${authRequestType.toString()} info from your auth endpoint, status: ${status}`);
3304
+ })
3305
+ .then(data => {
3306
+ let parsedData;
3307
+ try {
3308
+ parsedData = JSON.parse(data);
3309
+ }
3310
+ catch (e) {
3311
+ throw new HTTPAuthError(200, `JSON returned from ${authRequestType.toString()} endpoint was invalid, yet status code was 200. Data was: ${data}`);
3312
+ }
3313
+ callback(null, parsedData);
3314
+ })
3315
+ .catch(err => {
3316
+ callback(err, null);
3317
+ });
3318
+ };
3319
+ /* harmony default export */ var fetch_auth = (fetchAuth);
3320
+
3321
+ // CONCATENATED MODULE: ./src/runtimes/worker/timeline/fetch_timeline.ts
3322
+
3323
+
3324
+ var getAgent = function (sender, useTLS) {
3325
+ return function (data, callback) {
3326
+ var scheme = 'http' + (useTLS ? 's' : '') + '://';
3327
+ var url = scheme + (sender.host || sender.options.host) + sender.options.path;
3328
+ var query = buildQueryString(data);
3329
+ url += '/' + 2 + '?' + query;
3330
+ fetch(url)
3331
+ .then(response => {
3332
+ if (response.status !== 200) {
3333
+ throw `received ${response.status} from stats.pusher.com`;
3334
+ }
3335
+ return response.json();
3336
+ })
3337
+ .then(({ host }) => {
3338
+ if (host) {
3339
+ sender.host = host;
3340
+ }
3341
+ })
3342
+ .catch(err => {
3343
+ logger.debug('TimelineSender Error: ', err);
3344
+ });
3345
+ };
3346
+ };
3347
+ var fetchTimeline = {
3348
+ name: 'xhr',
3349
+ getAgent
3350
+ };
3351
+ /* harmony default export */ var fetch_timeline = (fetchTimeline);
3352
+
3353
+ // CONCATENATED MODULE: ./src/runtimes/worker/runtime.ts
3354
+
3355
+
3356
+
3357
+
3358
+ const { getDefaultStrategy: runtime_getDefaultStrategy, Transports: runtime_Transports, setup, getProtocol, isXHRSupported, getLocalStorage, createXHR, createWebSocket, addUnloadListener, removeUnloadListener, transportConnectionInitializer, createSocketRequest, HTTPFactory } = runtime;
3359
+ const Worker = {
3360
+ getDefaultStrategy: runtime_getDefaultStrategy,
3361
+ Transports: runtime_Transports,
3362
+ setup,
3363
+ getProtocol,
3364
+ isXHRSupported,
3365
+ getLocalStorage,
3366
+ createXHR,
3367
+ createWebSocket,
3368
+ addUnloadListener,
3369
+ removeUnloadListener,
3370
+ transportConnectionInitializer,
3371
+ createSocketRequest,
3372
+ HTTPFactory,
3373
+ TimelineTransport: fetch_timeline,
3374
+ getAuthorizers() {
3375
+ return { ajax: fetch_auth };
3376
+ },
3377
+ getWebSocketAPI() {
3378
+ return WebSocket;
3379
+ },
3380
+ getXHRAPI() {
3381
+ return XMLHttpRequest;
3382
+ },
3383
+ getNetwork() {
3384
+ return net_info_Network;
3385
+ },
3386
+ randomInt(max) {
3387
+ const random = function () {
3388
+ const crypto = globalThis.crypto || globalThis['msCrypto'];
3389
+ const random = crypto.getRandomValues(new Uint32Array(1))[0];
3390
+ return random / Math.pow(2, 32);
3391
+ };
3392
+ return Math.floor(random() * max);
3393
+ }
3394
+ };
3395
+ /* harmony default export */ var worker_runtime = (Worker);
3396
+
3397
+ // CONCATENATED MODULE: ./src/core/auth/options.ts
3398
+ var AuthRequestType;
3399
+ (function (AuthRequestType) {
3400
+ AuthRequestType["UserAuthentication"] = "user-authentication";
3401
+ AuthRequestType["ChannelAuthorization"] = "channel-authorization";
3402
+ })(AuthRequestType || (AuthRequestType = {}));
3403
+
3404
+ // CONCATENATED MODULE: ./src/core/auth/user_authenticator.ts
3405
+
3406
+
3407
+ const composeChannelQuery = (params, authOptions) => {
3408
+ var query = 'socket_id=' + encodeURIComponent(params.socketId);
3409
+ for (var key in authOptions.params) {
3410
+ query +=
3411
+ '&' +
3412
+ encodeURIComponent(key) +
3413
+ '=' +
3414
+ encodeURIComponent(authOptions.params[key]);
3415
+ }
3416
+ if (authOptions.paramsProvider != null) {
3417
+ let dynamicParams = authOptions.paramsProvider();
3418
+ for (var key in dynamicParams) {
3419
+ query +=
3420
+ '&' +
3421
+ encodeURIComponent(key) +
3422
+ '=' +
3423
+ encodeURIComponent(dynamicParams[key]);
3424
+ }
3425
+ }
3426
+ return query;
3427
+ };
3428
+ const UserAuthenticator = (authOptions) => {
3429
+ if (typeof worker_runtime.getAuthorizers()[authOptions.transport] === 'undefined') {
3430
+ throw `'${authOptions.transport}' is not a recognized auth transport`;
3431
+ }
3432
+ return (params, callback) => {
3433
+ const query = composeChannelQuery(params, authOptions);
3434
+ worker_runtime.getAuthorizers()[authOptions.transport](worker_runtime, query, authOptions, AuthRequestType.UserAuthentication, callback);
3435
+ };
3436
+ };
3437
+ /* harmony default export */ var user_authenticator = (UserAuthenticator);
3438
+
3439
+ // CONCATENATED MODULE: ./src/core/auth/channel_authorizer.ts
3440
+
3441
+
3442
+ const channel_authorizer_composeChannelQuery = (params, authOptions) => {
3443
+ var query = 'socket_id=' + encodeURIComponent(params.socketId);
3444
+ query += '&channel_name=' + encodeURIComponent(params.channelName);
3445
+ for (var key in authOptions.params) {
3446
+ query +=
3447
+ '&' +
3448
+ encodeURIComponent(key) +
3449
+ '=' +
3450
+ encodeURIComponent(authOptions.params[key]);
3451
+ }
3452
+ if (authOptions.paramsProvider != null) {
3453
+ let dynamicParams = authOptions.paramsProvider();
3454
+ for (var key in dynamicParams) {
3455
+ query +=
3456
+ '&' +
3457
+ encodeURIComponent(key) +
3458
+ '=' +
3459
+ encodeURIComponent(dynamicParams[key]);
3460
+ }
3461
+ }
3462
+ return query;
3463
+ };
3464
+ const ChannelAuthorizer = (authOptions) => {
3465
+ if (typeof worker_runtime.getAuthorizers()[authOptions.transport] === 'undefined') {
3466
+ throw `'${authOptions.transport}' is not a recognized auth transport`;
3467
+ }
3468
+ return (params, callback) => {
3469
+ const query = channel_authorizer_composeChannelQuery(params, authOptions);
3470
+ worker_runtime.getAuthorizers()[authOptions.transport](worker_runtime, query, authOptions, AuthRequestType.ChannelAuthorization, callback);
3471
+ };
3472
+ };
3473
+ /* harmony default export */ var channel_authorizer = (ChannelAuthorizer);
3474
+
3475
+ // CONCATENATED MODULE: ./src/core/auth/deprecated_channel_authorizer.ts
3476
+ const ChannelAuthorizerProxy = (pusher, authOptions, channelAuthorizerGenerator) => {
3477
+ const deprecatedAuthorizerOptions = {
3478
+ authTransport: authOptions.transport,
3479
+ authEndpoint: authOptions.endpoint,
3480
+ auth: {
3481
+ params: authOptions.params,
3482
+ headers: authOptions.headers
3483
+ }
3484
+ };
3485
+ return (params, callback) => {
3486
+ const channel = pusher.channel(params.channelName);
3487
+ const channelAuthorizer = channelAuthorizerGenerator(channel, deprecatedAuthorizerOptions);
3488
+ channelAuthorizer.authorize(params.socketId, callback);
3489
+ };
3490
+ };
3491
+
3492
+ // CONCATENATED MODULE: ./src/core/config.ts
3493
+
3494
+
3495
+
3496
+
3497
+
3498
+ function getConfig(opts, pusher) {
3499
+ let config = {
3500
+ activityTimeout: opts.activityTimeout || defaults.activityTimeout,
3501
+ cluster: opts.cluster,
3502
+ httpPath: opts.httpPath || defaults.httpPath,
3503
+ httpPort: opts.httpPort || defaults.httpPort,
3504
+ httpsPort: opts.httpsPort || defaults.httpsPort,
3505
+ pongTimeout: opts.pongTimeout || defaults.pongTimeout,
3506
+ statsHost: opts.statsHost || defaults.stats_host,
3507
+ unavailableTimeout: opts.unavailableTimeout || defaults.unavailableTimeout,
3508
+ wsPath: opts.wsPath || defaults.wsPath,
3509
+ wsPort: opts.wsPort || defaults.wsPort,
3510
+ wssPort: opts.wssPort || defaults.wssPort,
3511
+ enableStats: getEnableStatsConfig(opts),
3512
+ httpHost: getHttpHost(opts),
3513
+ useTLS: shouldUseTLS(opts),
3514
+ wsHost: getWebsocketHost(opts),
3515
+ userAuthenticator: buildUserAuthenticator(opts),
3516
+ channelAuthorizer: buildChannelAuthorizer(opts, pusher)
3517
+ };
3518
+ if ('disabledTransports' in opts)
3519
+ config.disabledTransports = opts.disabledTransports;
3520
+ if ('enabledTransports' in opts)
3521
+ config.enabledTransports = opts.enabledTransports;
3522
+ if ('ignoreNullOrigin' in opts)
3523
+ config.ignoreNullOrigin = opts.ignoreNullOrigin;
3524
+ if ('timelineParams' in opts)
3525
+ config.timelineParams = opts.timelineParams;
3526
+ if ('nacl' in opts) {
3527
+ config.nacl = opts.nacl;
3528
+ }
3529
+ return config;
3530
+ }
3531
+ function getHttpHost(opts) {
3532
+ if (opts.httpHost) {
3533
+ return opts.httpHost;
3534
+ }
3535
+ if (opts.cluster) {
3536
+ return `sockjs-${opts.cluster}.pusher.com`;
3537
+ }
3538
+ return defaults.httpHost;
3539
+ }
3540
+ function getWebsocketHost(opts) {
3541
+ if (opts.wsHost) {
3542
+ return opts.wsHost;
3543
+ }
3544
+ return getWebsocketHostFromCluster(opts.cluster);
3545
+ }
3546
+ function getWebsocketHostFromCluster(cluster) {
3547
+ return `ws-${cluster}.pusher.com`;
3548
+ }
3549
+ function shouldUseTLS(opts) {
3550
+ if (worker_runtime.getProtocol() === 'https:') {
3551
+ return true;
3552
+ }
3553
+ else if (opts.forceTLS === false) {
3554
+ return false;
3555
+ }
3556
+ return true;
3557
+ }
3558
+ function getEnableStatsConfig(opts) {
3559
+ if ('enableStats' in opts) {
3560
+ return opts.enableStats;
3561
+ }
3562
+ if ('disableStats' in opts) {
3563
+ return !opts.disableStats;
3564
+ }
3565
+ return false;
3566
+ }
3567
+ function buildUserAuthenticator(opts) {
3568
+ const userAuthentication = Object.assign(Object.assign({}, defaults.userAuthentication), opts.userAuthentication);
3569
+ if ('customHandler' in userAuthentication &&
3570
+ userAuthentication['customHandler'] != null) {
3571
+ return userAuthentication['customHandler'];
3572
+ }
3573
+ return user_authenticator(userAuthentication);
3574
+ }
3575
+ function buildChannelAuth(opts, pusher) {
3576
+ let channelAuthorization;
3577
+ if ('channelAuthorization' in opts) {
3578
+ channelAuthorization = Object.assign(Object.assign({}, defaults.channelAuthorization), opts.channelAuthorization);
3579
+ }
3580
+ else {
3581
+ channelAuthorization = {
3582
+ transport: opts.authTransport || defaults.authTransport,
3583
+ endpoint: opts.authEndpoint || defaults.authEndpoint
3584
+ };
3585
+ if ('auth' in opts) {
3586
+ if ('params' in opts.auth)
3587
+ channelAuthorization.params = opts.auth.params;
3588
+ if ('headers' in opts.auth)
3589
+ channelAuthorization.headers = opts.auth.headers;
3590
+ }
3591
+ if ('authorizer' in opts)
3592
+ channelAuthorization.customHandler = ChannelAuthorizerProxy(pusher, channelAuthorization, opts.authorizer);
3593
+ }
3594
+ return channelAuthorization;
3595
+ }
3596
+ function buildChannelAuthorizer(opts, pusher) {
3597
+ const channelAuthorization = buildChannelAuth(opts, pusher);
3598
+ if ('customHandler' in channelAuthorization &&
3599
+ channelAuthorization['customHandler'] != null) {
3600
+ return channelAuthorization['customHandler'];
3601
+ }
3602
+ return channel_authorizer(channelAuthorization);
3603
+ }
3604
+
3605
+ // CONCATENATED MODULE: ./src/core/options.ts
3606
+
3607
+ function validateOptions(options) {
3608
+ if (options == null) {
3609
+ throw 'You must pass an options object';
3610
+ }
3611
+ if (options.cluster == null) {
3612
+ throw 'Options object must provide a cluster';
3613
+ }
3614
+ if ('disableStats' in options) {
3615
+ logger.warn('The disableStats option is deprecated in favor of enableStats');
3616
+ }
3617
+ }
3618
+
3619
+ // CONCATENATED MODULE: ./src/core/strategies/transport_strategy.ts
3620
+
3621
+
3622
+
3623
+
3624
+ class transport_strategy_TransportStrategy {
3625
+ constructor(name, priority, transport, options) {
3626
+ this.name = name;
3627
+ this.priority = priority;
3628
+ this.transport = transport;
3629
+ this.options = options || {};
3630
+ }
3631
+ isSupported() {
3632
+ return this.transport.isSupported({
3633
+ useTLS: this.options.useTLS
3634
+ });
3635
+ }
3636
+ connect(minPriority, callback) {
3637
+ if (!this.isSupported()) {
3638
+ return failAttempt(new UnsupportedStrategy(), callback);
3639
+ }
3640
+ else if (this.priority < minPriority) {
3641
+ return failAttempt(new TransportPriorityTooLow(), callback);
3642
+ }
3643
+ var connected = false;
3644
+ var transport = this.transport.createConnection(this.name, this.priority, this.options.key, this.options);
3645
+ var handshake = null;
3646
+ var onInitialized = function () {
3647
+ transport.unbind('initialized', onInitialized);
3648
+ transport.connect();
3649
+ };
3650
+ var onOpen = function () {
3651
+ handshake = factory.createHandshake(transport, function (result) {
3652
+ connected = true;
3653
+ unbindListeners();
3654
+ callback(null, result);
3655
+ });
3656
+ };
3657
+ var onError = function (error) {
3658
+ unbindListeners();
3659
+ callback(error);
3660
+ };
3661
+ var onClosed = function () {
3662
+ unbindListeners();
3663
+ var serializedTransport;
3664
+ serializedTransport = safeJSONStringify(transport);
3665
+ callback(new TransportClosed(serializedTransport));
3666
+ };
3667
+ var unbindListeners = function () {
3668
+ transport.unbind('initialized', onInitialized);
3669
+ transport.unbind('open', onOpen);
3670
+ transport.unbind('error', onError);
3671
+ transport.unbind('closed', onClosed);
3672
+ };
3673
+ transport.bind('initialized', onInitialized);
3674
+ transport.bind('open', onOpen);
3675
+ transport.bind('error', onError);
3676
+ transport.bind('closed', onClosed);
3677
+ transport.initialize();
3678
+ return {
3679
+ abort: () => {
3680
+ if (connected) {
3681
+ return;
3682
+ }
3683
+ unbindListeners();
3684
+ if (handshake) {
3685
+ handshake.close();
3686
+ }
3687
+ else {
3688
+ transport.close();
3689
+ }
3690
+ },
3691
+ forceMinPriority: p => {
3692
+ if (connected) {
3693
+ return;
3694
+ }
3695
+ if (this.priority < p) {
3696
+ if (handshake) {
3697
+ handshake.close();
3698
+ }
3699
+ else {
3700
+ transport.close();
3701
+ }
3702
+ }
3703
+ }
3704
+ };
3705
+ }
3706
+ }
3707
+ function failAttempt(error, callback) {
3708
+ util.defer(function () {
3709
+ callback(error);
3710
+ });
3711
+ return {
3712
+ abort: function () { },
3713
+ forceMinPriority: function () { }
3714
+ };
3715
+ }
3716
+
3717
+ // CONCATENATED MODULE: ./src/core/strategies/strategy_builder.ts
3718
+
3719
+
3720
+
3721
+
3722
+
3723
+ const { Transports: strategy_builder_Transports } = worker_runtime;
3724
+ var strategy_builder_defineTransport = function (config, name, type, priority, options, manager) {
3725
+ var transportClass = strategy_builder_Transports[type];
3726
+ if (!transportClass) {
3727
+ throw new UnsupportedTransport(type);
3728
+ }
3729
+ var enabled = (!config.enabledTransports ||
3730
+ arrayIndexOf(config.enabledTransports, name) !== -1) &&
3731
+ (!config.disabledTransports ||
3732
+ arrayIndexOf(config.disabledTransports, name) === -1);
3733
+ var transport;
3734
+ if (enabled) {
3735
+ options = Object.assign({ ignoreNullOrigin: config.ignoreNullOrigin }, options);
3736
+ transport = new transport_strategy_TransportStrategy(name, priority, manager ? manager.getAssistant(transportClass) : transportClass, options);
3737
+ }
3738
+ else {
3739
+ transport = strategy_builder_UnsupportedStrategy;
3740
+ }
3741
+ return transport;
3742
+ };
3743
+ var strategy_builder_UnsupportedStrategy = {
3744
+ isSupported: function () {
3745
+ return false;
3746
+ },
3747
+ connect: function (_, callback) {
3748
+ var deferred = util.defer(function () {
3749
+ callback(new UnsupportedStrategy());
3750
+ });
3751
+ return {
3752
+ abort: function () {
3753
+ deferred.ensureAborted();
3754
+ },
3755
+ forceMinPriority: function () { }
3756
+ };
3757
+ }
3758
+ };
3759
+
3760
+ // CONCATENATED MODULE: ./src/core/timeline/level.ts
3761
+ var TimelineLevel;
3762
+ (function (TimelineLevel) {
3763
+ TimelineLevel[TimelineLevel["ERROR"] = 3] = "ERROR";
3764
+ TimelineLevel[TimelineLevel["INFO"] = 6] = "INFO";
3765
+ TimelineLevel[TimelineLevel["DEBUG"] = 7] = "DEBUG";
3766
+ })(TimelineLevel || (TimelineLevel = {}));
3767
+ /* harmony default export */ var timeline_level = (TimelineLevel);
3768
+
3769
+ // CONCATENATED MODULE: ./src/core/timeline/timeline.ts
3770
+
3771
+
3772
+
3773
+ class timeline_Timeline {
3774
+ constructor(key, session, options) {
3775
+ this.key = key;
3776
+ this.session = session;
3777
+ this.events = [];
3778
+ this.options = options || {};
3779
+ this.sent = 0;
3780
+ this.uniqueID = 0;
3781
+ }
3782
+ log(level, event) {
3783
+ if (level <= this.options.level) {
3784
+ this.events.push(extend({}, event, { timestamp: util.now() }));
3785
+ if (this.options.limit && this.events.length > this.options.limit) {
3786
+ this.events.shift();
3787
+ }
3788
+ }
3789
+ }
3790
+ error(event) {
3791
+ this.log(timeline_level.ERROR, event);
3792
+ }
3793
+ info(event) {
3794
+ this.log(timeline_level.INFO, event);
3795
+ }
3796
+ debug(event) {
3797
+ this.log(timeline_level.DEBUG, event);
3798
+ }
3799
+ isEmpty() {
3800
+ return this.events.length === 0;
3801
+ }
3802
+ send(sendfn, callback) {
3803
+ var data = extend({
3804
+ session: this.session,
3805
+ bundle: this.sent + 1,
3806
+ key: this.key,
3807
+ lib: 'js',
3808
+ version: this.options.version,
3809
+ cluster: this.options.cluster,
3810
+ features: this.options.features,
3811
+ timeline: this.events
3812
+ }, this.options.params);
3813
+ this.events = [];
3814
+ sendfn(data, (error, result) => {
3815
+ if (!error) {
3816
+ this.sent++;
3817
+ }
3818
+ if (callback) {
3819
+ callback(error, result);
3820
+ }
3821
+ });
3822
+ return true;
3823
+ }
3824
+ generateUniqueID() {
3825
+ this.uniqueID++;
3826
+ return this.uniqueID;
3827
+ }
3828
+ }
3829
+
3830
+ // CONCATENATED MODULE: ./src/core/utils/flat_promise.ts
3831
+ function flatPromise() {
3832
+ let resolve, reject;
3833
+ const promise = new Promise((res, rej) => {
3834
+ resolve = res;
3835
+ reject = rej;
3836
+ });
3837
+ return { promise, resolve, reject };
3838
+ }
3839
+ /* harmony default export */ var flat_promise = (flatPromise);
3840
+
3841
+ // CONCATENATED MODULE: ./src/core/watchlist.ts
3842
+
3843
+
3844
+ class watchlist_WatchlistFacade extends dispatcher_Dispatcher {
3845
+ constructor(pusher) {
3846
+ super(function (eventName, data) {
3847
+ logger.debug(`No callbacks on watchlist events for ${eventName}`);
3848
+ });
3849
+ this.pusher = pusher;
3850
+ this.bindWatchlistInternalEvent();
3851
+ }
3852
+ handleEvent(pusherEvent) {
3853
+ pusherEvent.data.events.forEach(watchlistEvent => {
3854
+ this.emit(watchlistEvent.name, watchlistEvent);
3855
+ });
3856
+ }
3857
+ bindWatchlistInternalEvent() {
3858
+ this.pusher.connection.bind('message', pusherEvent => {
3859
+ var eventName = pusherEvent.event;
3860
+ if (eventName === 'pusher_internal:watchlist_events') {
3861
+ this.handleEvent(pusherEvent);
3862
+ }
3863
+ });
3864
+ }
3865
+ }
3866
+
3867
+ // CONCATENATED MODULE: ./src/core/user.ts
3868
+
3869
+
3870
+
3871
+
3872
+
3873
+ class user_UserFacade extends dispatcher_Dispatcher {
3874
+ constructor(pusher) {
3875
+ super(function (eventName, data) {
3876
+ logger.debug('No callbacks on user for ' + eventName);
3877
+ });
3878
+ this.signin_requested = false;
3879
+ this.user_data = null;
3880
+ this.serverToUserChannel = null;
3881
+ this.signinDonePromise = null;
3882
+ this._signinDoneResolve = null;
3883
+ this._onAuthorize = (err, authData) => {
3884
+ if (err) {
3885
+ logger.warn(`Error during signin: ${err}`);
3886
+ this._cleanup();
3887
+ return;
3888
+ }
3889
+ this.pusher.send_event('pusher:signin', {
3890
+ auth: authData.auth,
3891
+ user_data: authData.user_data
3892
+ });
3893
+ };
3894
+ this.pusher = pusher;
3895
+ this.pusher.connection.bind('state_change', ({ previous, current }) => {
3896
+ if (previous !== 'connected' && current === 'connected') {
3897
+ this._signin();
3898
+ }
3899
+ if (previous === 'connected' && current !== 'connected') {
3900
+ this._cleanup();
3901
+ this._newSigninPromiseIfNeeded();
3902
+ }
3903
+ });
3904
+ this.watchlist = new watchlist_WatchlistFacade(pusher);
3905
+ this.pusher.connection.bind('message', event => {
3906
+ var eventName = event.event;
3907
+ if (eventName === 'pusher:signin_success') {
3908
+ this._onSigninSuccess(event.data);
3909
+ }
3910
+ if (this.serverToUserChannel &&
3911
+ this.serverToUserChannel.name === event.channel) {
3912
+ this.serverToUserChannel.handleEvent(event);
3913
+ }
3914
+ });
3915
+ }
3916
+ signin() {
3917
+ if (this.signin_requested) {
3918
+ return;
3919
+ }
3920
+ this.signin_requested = true;
3921
+ this._signin();
3922
+ }
3923
+ _signin() {
3924
+ if (!this.signin_requested) {
3925
+ return;
3926
+ }
3927
+ this._newSigninPromiseIfNeeded();
3928
+ if (this.pusher.connection.state !== 'connected') {
3929
+ return;
3930
+ }
3931
+ this.pusher.config.userAuthenticator({
3932
+ socketId: this.pusher.connection.socket_id
3933
+ }, this._onAuthorize);
3934
+ }
3935
+ _onSigninSuccess(data) {
3936
+ try {
3937
+ this.user_data = JSON.parse(data.user_data);
3938
+ }
3939
+ catch (e) {
3940
+ logger.error(`Failed parsing user data after signin: ${data.user_data}`);
3941
+ this._cleanup();
3942
+ return;
3943
+ }
3944
+ if (typeof this.user_data.id !== 'string' || this.user_data.id === '') {
3945
+ logger.error(`user_data doesn't contain an id. user_data: ${this.user_data}`);
3946
+ this._cleanup();
3947
+ return;
3948
+ }
3949
+ this._signinDoneResolve();
3950
+ this._subscribeChannels();
3951
+ }
3952
+ _subscribeChannels() {
3953
+ const ensure_subscribed = channel => {
3954
+ if (channel.subscriptionPending && channel.subscriptionCancelled) {
3955
+ channel.reinstateSubscription();
3956
+ }
3957
+ else if (!channel.subscriptionPending &&
3958
+ this.pusher.connection.state === 'connected') {
3959
+ channel.subscribe();
3960
+ }
3961
+ };
3962
+ this.serverToUserChannel = new channel_Channel(`#server-to-user-${this.user_data.id}`, this.pusher);
3963
+ this.serverToUserChannel.bind_global((eventName, data) => {
3964
+ if (eventName.indexOf('pusher_internal:') === 0 ||
3965
+ eventName.indexOf('pusher:') === 0) {
3966
+ return;
3967
+ }
3968
+ this.emit(eventName, data);
3969
+ });
3970
+ ensure_subscribed(this.serverToUserChannel);
3971
+ }
3972
+ _cleanup() {
3973
+ this.user_data = null;
3974
+ if (this.serverToUserChannel) {
3975
+ this.serverToUserChannel.unbind_all();
3976
+ this.serverToUserChannel.disconnect();
3977
+ this.serverToUserChannel = null;
3978
+ }
3979
+ if (this.signin_requested) {
3980
+ this._signinDoneResolve();
3981
+ }
3982
+ }
3983
+ _newSigninPromiseIfNeeded() {
3984
+ if (!this.signin_requested) {
3985
+ return;
3986
+ }
3987
+ if (this.signinDonePromise && !this.signinDonePromise.done) {
3988
+ return;
3989
+ }
3990
+ const { promise, resolve, reject: _ } = flat_promise();
3991
+ promise.done = false;
3992
+ const setDone = () => {
3993
+ promise.done = true;
3994
+ };
3995
+ promise.then(setDone).catch(setDone);
3996
+ this.signinDonePromise = promise;
3997
+ this._signinDoneResolve = resolve;
3998
+ }
3999
+ }
4000
+
4001
+ // CONCATENATED MODULE: ./src/core/pusher.ts
4002
+
4003
+
4004
+
4005
+
4006
+
4007
+
4008
+
4009
+
4010
+
4011
+
4012
+
4013
+
4014
+
4015
+ class pusher_Pingerchips {
4016
+ static ready() {
4017
+ pusher_Pingerchips.isReady = true;
4018
+ for (var i = 0, l = pusher_Pingerchips.instances.length; i < l; i++) {
4019
+ pusher_Pingerchips.instances[i].connect();
4020
+ }
4021
+ }
4022
+ static getClientFeatures() {
4023
+ return keys(filterObject({ ws: worker_runtime.Transports.ws }, function (t) {
4024
+ return t.isSupported({});
4025
+ }));
4026
+ }
4027
+ constructor(app_key, options) {
4028
+ checkAppKey(app_key);
4029
+ validateOptions(options);
4030
+ this.key = app_key;
4031
+ this.config = getConfig(options, this);
4032
+ this.channels = factory.createChannels();
4033
+ this.global_emitter = new dispatcher_Dispatcher();
4034
+ this.sessionID = worker_runtime.randomInt(1000000000);
4035
+ this.timeline = new timeline_Timeline(this.key, this.sessionID, {
4036
+ cluster: this.config.cluster,
4037
+ features: pusher_Pingerchips.getClientFeatures(),
4038
+ params: this.config.timelineParams || {},
4039
+ limit: 50,
4040
+ level: timeline_level.INFO,
4041
+ version: defaults.VERSION
4042
+ });
4043
+ if (this.config.enableStats) {
4044
+ this.timelineSender = factory.createTimelineSender(this.timeline, {
4045
+ host: this.config.statsHost,
4046
+ path: '/timeline/v2/' + worker_runtime.TimelineTransport.name
4047
+ });
4048
+ }
4049
+ var getStrategy = (options) => {
4050
+ return worker_runtime.getDefaultStrategy(this.config, options, strategy_builder_defineTransport);
4051
+ };
4052
+ this.connection = factory.createConnectionManager(this.key, {
4053
+ getStrategy: getStrategy,
4054
+ timeline: this.timeline,
4055
+ activityTimeout: this.config.activityTimeout,
4056
+ pongTimeout: this.config.pongTimeout,
4057
+ unavailableTimeout: this.config.unavailableTimeout,
4058
+ useTLS: Boolean(this.config.useTLS)
4059
+ });
4060
+ this.connection.bind('connected', () => {
4061
+ this.subscribeAll();
4062
+ if (this.timelineSender) {
4063
+ this.timelineSender.send(this.connection.isUsingTLS());
4064
+ }
4065
+ });
4066
+ this.connection.bind('message', event => {
4067
+ var eventName = event.event;
4068
+ var internal = eventName.indexOf('pusher_internal:') === 0;
4069
+ if (event.channel) {
4070
+ var channel = this.channel(event.channel);
4071
+ if (channel) {
4072
+ channel.handleEvent(event);
4073
+ }
4074
+ }
4075
+ if (!internal) {
4076
+ this.global_emitter.emit(event.event, event.data);
4077
+ }
4078
+ });
4079
+ this.connection.bind('connecting', () => {
4080
+ this.channels.disconnect();
4081
+ });
4082
+ this.connection.bind('disconnected', () => {
4083
+ this.channels.disconnect();
4084
+ });
4085
+ this.connection.bind('error', err => {
4086
+ logger.warn(err);
4087
+ });
4088
+ pusher_Pingerchips.instances.push(this);
4089
+ this.timeline.info({ instances: pusher_Pingerchips.instances.length });
4090
+ this.user = new user_UserFacade(this);
4091
+ if (pusher_Pingerchips.isReady) {
4092
+ this.connect();
4093
+ }
4094
+ }
4095
+ channel(name) {
4096
+ return this.channels.find(name);
4097
+ }
4098
+ allChannels() {
4099
+ return this.channels.all();
4100
+ }
4101
+ connect() {
4102
+ this.connection.connect();
4103
+ if (this.timelineSender) {
4104
+ if (!this.timelineSenderTimer) {
4105
+ var usingTLS = this.connection.isUsingTLS();
4106
+ var timelineSender = this.timelineSender;
4107
+ this.timelineSenderTimer = new timers_PeriodicTimer(60000, function () {
4108
+ timelineSender.send(usingTLS);
4109
+ });
4110
+ }
4111
+ }
4112
+ }
4113
+ disconnect() {
4114
+ this.connection.disconnect();
4115
+ if (this.timelineSenderTimer) {
4116
+ this.timelineSenderTimer.ensureAborted();
4117
+ this.timelineSenderTimer = null;
4118
+ }
4119
+ }
4120
+ bind(event_name, callback, context) {
4121
+ this.global_emitter.bind(event_name, callback, context);
4122
+ return this;
4123
+ }
4124
+ unbind(event_name, callback, context) {
4125
+ this.global_emitter.unbind(event_name, callback, context);
4126
+ return this;
4127
+ }
4128
+ bind_global(callback) {
4129
+ this.global_emitter.bind_global(callback);
4130
+ return this;
4131
+ }
4132
+ unbind_global(callback) {
4133
+ this.global_emitter.unbind_global(callback);
4134
+ return this;
4135
+ }
4136
+ unbind_all(callback) {
4137
+ this.global_emitter.unbind_all();
4138
+ return this;
4139
+ }
4140
+ subscribeAll() {
4141
+ var channelName;
4142
+ for (channelName in this.channels.channels) {
4143
+ if (this.channels.channels.hasOwnProperty(channelName)) {
4144
+ this.subscribe(channelName);
4145
+ }
4146
+ }
4147
+ }
4148
+ subscribe(channel_name) {
4149
+ var channel = this.channels.add(channel_name, this);
4150
+ if (channel.subscriptionPending && channel.subscriptionCancelled) {
4151
+ channel.reinstateSubscription();
4152
+ }
4153
+ else if (!channel.subscriptionPending &&
4154
+ this.connection.state === 'connected') {
4155
+ channel.subscribe();
4156
+ }
4157
+ return channel;
4158
+ }
4159
+ unsubscribe(channel_name) {
4160
+ var channel = this.channels.find(channel_name);
4161
+ if (channel && channel.subscriptionPending) {
4162
+ channel.cancelSubscription();
4163
+ }
4164
+ else {
4165
+ channel = this.channels.remove(channel_name);
4166
+ if (channel && channel.subscribed) {
4167
+ channel.unsubscribe();
4168
+ }
4169
+ }
4170
+ }
4171
+ send_event(event_name, data, channel) {
4172
+ return this.connection.send_event(event_name, data, channel);
4173
+ }
4174
+ shouldUseTLS() {
4175
+ return this.config.useTLS;
4176
+ }
4177
+ signin() {
4178
+ this.user.signin();
4179
+ }
4180
+ }
4181
+ pusher_Pingerchips.instances = [];
4182
+ pusher_Pingerchips.isReady = false;
4183
+ pusher_Pingerchips.logToConsole = false;
4184
+ pusher_Pingerchips.Runtime = worker_runtime;
4185
+ pusher_Pingerchips.ScriptReceivers = worker_runtime.ScriptReceivers;
4186
+ pusher_Pingerchips.DependenciesReceivers = worker_runtime.DependenciesReceivers;
4187
+ pusher_Pingerchips.auth_callbacks = worker_runtime.auth_callbacks;
4188
+ /* harmony default export */ var core_pusher = __webpack_exports__["default"] = (pusher_Pingerchips);
4189
+ function checkAppKey(key) {
4190
+ if (key === null || key === undefined) {
4191
+ throw 'You must pass your app key when you instantiate Pusher.';
4192
+ }
4193
+ }
4194
+ worker_runtime.setup(pusher_Pingerchips);
4195
+
4196
+
4197
+ /***/ })
4198
+ /******/ ]);
4199
+ });
4200
+ //# sourceMappingURL=pusher.worker.js.map