UNPKG

@harelpls/use-pusher

Version:

A wrapper around pusher-js for easy-as hooks in React.

1,300 lines (1,123 loc) 145 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var React = require('react'); var reactNative$1 = require('react-native'); function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } var React__default = /*#__PURE__*/_interopDefaultLegacy(React); /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ var __assign = function() { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; function __rest(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; } var has = Object.prototype.hasOwnProperty; function find(iter, tar, key) { for (key of iter.keys()) { if (dequal(key, tar)) return key; } } function dequal(foo, bar) { var ctor, len, tmp; if (foo === bar) return true; if (foo && bar && (ctor=foo.constructor) === bar.constructor) { if (ctor === Date) return foo.getTime() === bar.getTime(); if (ctor === RegExp) return foo.toString() === bar.toString(); if (ctor === Array) { if ((len=foo.length) === bar.length) { while (len-- && dequal(foo[len], bar[len])); } return len === -1; } if (ctor === Set) { if (foo.size !== bar.size) { return false; } for (len of foo) { tmp = len; if (tmp && typeof tmp === 'object') { tmp = find(bar, tmp); if (!tmp) return false; } if (!bar.has(tmp)) return false; } return true; } if (ctor === Map) { if (foo.size !== bar.size) { return false; } for (len of foo) { tmp = len[0]; if (tmp && typeof tmp === 'object') { tmp = find(bar, tmp); if (!tmp) return false; } if (!dequal(len[1], bar.get(tmp))) { return false; } } return true; } if (ctor === ArrayBuffer) { foo = new Uint8Array(foo); bar = new Uint8Array(bar); } else if (ctor === DataView) { if ((len=foo.byteLength) === bar.byteLength) { while (len-- && foo.getInt8(len) === bar.getInt8(len)); } return len === -1; } if (ArrayBuffer.isView(foo)) { if ((len=foo.byteLength) === bar.byteLength) { while (len-- && foo[len] === bar[len]); } return len === -1; } if (!ctor || typeof foo === 'object') { len = 0; for (ctor in foo) { if (has.call(foo, ctor) && ++len && !has.call(bar, ctor)) return false; if (!(ctor in bar) || !dequal(foo[ctor], bar[ctor])) return false; } return Object.keys(bar).length === len; } } return foo !== foo && bar !== bar; } // context setup var PusherContext = React__default['default'].createContext({}); var __PusherContext = PusherContext; /** * Provider that creates your pusher instance and provides it to child hooks throughout your app. * Note, you can pass in value={{}} as a prop if you'd like to override the pusher client passed. * This is handy when simulating pusher locally, or for testing. * @param props Config for Pusher client */ var CorePusherProvider = function (_a) { var clientKey = _a.clientKey, cluster = _a.cluster, triggerEndpoint = _a.triggerEndpoint, _b = _a.defer, defer = _b === void 0 ? false : _b, children = _a.children, _PusherRuntime = _a._PusherRuntime, props = __rest(_a, ["clientKey", "cluster", "triggerEndpoint", "defer", "children", "_PusherRuntime"]); // errors when required props are not passed. React.useEffect(function () { if (!clientKey) console.error("A client key is required for pusher"); if (!cluster) console.error("A cluster is required for pusher"); }, [clientKey, cluster]); var config = __assign({ cluster: cluster }, props); // track config for comparison var previousConfig = React.useRef(props); React.useEffect(function () { previousConfig.current = props; }); var _c = React.useState(), client = _c[0], setClient = _c[1]; React.useEffect(function () { // Skip creation of client if deferring, a value prop is passed, or config props are the same. if (!_PusherRuntime || defer || props.value || (dequal(previousConfig.current, props) && client !== undefined)) { return; } // @ts-ignore setClient(new _PusherRuntime(clientKey, config)); }, [client, clientKey, props, defer]); return (React__default['default'].createElement(PusherContext.Provider, __assign({ value: { client: client, triggerEndpoint: triggerEndpoint, }, children: children }, props))); }; /** * Provides access to the pusher client instance. * * @returns a `MutableRefObject<Pusher|undefined>`. The instance is held by a `useRef()` hook. * @example * ```javascript * const { client } = usePusher(); * client.current.subscribe('my-channel'); * ``` */ function usePusher() { var context = React.useContext(__PusherContext); React.useEffect(function () { if (!Object.keys(context).length) console.warn(NOT_IN_CONTEXT_WARNING); }, [context]); return context; } var NOT_IN_CONTEXT_WARNING = "No Pusher context. Did you forget to wrap your app in a <PusherProvider />?"; /** * Subscribe to a channel * * @param channelName The name of the channel you want to subscribe to. * @typeparam Type of channel you're subscribing to. Can be one of `Channel` or `PresenceChannel` from `pusher-js`. * @returns Instance of the channel you just subscribed to. * * @example * ```javascript * const channel = useChannel("my-channel") * channel.bind('some-event', () => {}) * ``` */ var NO_CHANNEL_NAME_WARNING = "No channel name passed to useChannel. No channel has been subscribed to."; function useChannel(channelName) { var client = usePusher().client; var _a = React.useState(), channel = _a[0], setChannel = _a[1]; React.useEffect(function () { /** Return early if there's no client */ if (!client) return; /** Return early and warn if there's no channel */ if (!channelName) { console.warn(NO_CHANNEL_NAME_WARNING); return; } /** Subscribe to channel and set it in state */ var pusherChannel = client.subscribe(channelName); setChannel(pusherChannel); /** Cleanup on unmount/re-render */ return function () { return client === null || client === void 0 ? void 0 : client.unsubscribe(channelName); }; }, [channelName, client]); /** Return the channel for use. */ return channel; } /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var NODE_ENV = process.env.NODE_ENV; var invariant = function(condition, format, a, b, c, d, e, f) { if (NODE_ENV !== 'production') { if (format === undefined) { throw new Error('invariant requires an error message argument'); } } if (!condition) { var error; if (format === undefined) { error = new Error( 'Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.' ); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error( format.replace(/%s/g, function() { return args[argIndex++]; }) ); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } }; var invariant_1 = invariant; /** Presence channel reducer to keep track of state */ var SET_STATE = "set-state"; var ADD_MEMBER = "add-member"; var REMOVE_MEMBER = "remove-member"; var presenceChannelReducer = function (state, _a) { var _b; var type = _a.type, payload = _a.payload; switch (type) { /** Generic setState */ case SET_STATE: return __assign(__assign({}, state), payload); /** Member added */ case ADD_MEMBER: var _c = payload, addedMemberId = _c.id, info = _c.info; return __assign(__assign({}, state), { count: state.count + 1, members: __assign(__assign({}, state.members), (_b = {}, _b[addedMemberId] = info, _b)) }); /** Member removed */ case REMOVE_MEMBER: var removedMemberId = payload.id; var members = __assign({}, state.members); delete members[removedMemberId]; return __assign(__assign({}, state), { count: state.count - 1, members: __assign({}, members) }); } }; function usePresenceChannel(channelName) { // errors for missing arguments if (channelName) { invariant_1(channelName.includes("presence-"), "Presence channels should use prefix 'presence-' in their name. Use the useChannel hook instead."); } /** Store internal channel state */ var _a = React.useReducer(presenceChannelReducer, { members: {}, me: undefined, myID: undefined, count: 0, }), state = _a[0], dispatch = _a[1]; // bind and unbind member events events on our channel var channel = useChannel(channelName); React.useEffect(function () { if (channel) { // Get membership info on successful subscription var handleSubscriptionSuccess_1 = function (members) { dispatch({ type: SET_STATE, payload: { members: members.members, myID: members.myID, me: members.me, count: Object.keys(members.members).length, }, }); }; // Add member to the members object var handleAdd_1 = function (member) { dispatch({ type: ADD_MEMBER, payload: member, }); }; // Remove member from the members object var handleRemove_1 = function (member) { dispatch({ type: REMOVE_MEMBER, payload: member, }); }; // bind to all member addition/removal events channel.bind("pusher:subscription_succeeded", handleSubscriptionSuccess_1); channel.bind("pusher:member_added", handleAdd_1); channel.bind("pusher:member_removed", handleRemove_1); // cleanup return function () { channel.unbind("pusher:subscription_succeeded", handleSubscriptionSuccess_1); channel.unbind("pusher:member_added", handleAdd_1); channel.unbind("pusher:member_removed", handleRemove_1); }; } // to make typescript happy. return function () { }; }, [channel]); return __assign({ channel: channel }, state); } /** * Subscribes to a channel event and registers a callback. * @param channel Pusher channel to bind to * @param eventName Name of event to bind to * @param callback Callback to call on a new event */ function useEvent(channel, eventName, callback) { // error when required arguments aren't passed. invariant_1(eventName, "Must supply eventName and callback to onEvent"); invariant_1(callback, "Must supply callback to onEvent"); // bind and unbind events whenever the channel, eventName or callback changes. React.useEffect(function () { if (channel === undefined) { return; } else channel.bind(eventName, callback); return function () { channel.unbind(eventName, callback); }; }, [channel, eventName, callback]); } /** * * @param channel the channel you'd like to trigger clientEvents on. Get this from [[useChannel]] or [[usePresenceChannel]]. * @typeparam TData shape of the data you're sending with the event. * @returns A memoized trigger function that will perform client events on the channel. * @example * ```javascript * const channel = useChannel('my-channel'); * const trigger = useClientTrigger(channel) * * const handleClick = () => trigger('some-client-event', {}); * ``` */ function useClientTrigger(channel) { channel && invariant_1(channel.name.match(/(private-|presence-)/gi), "Channel provided to useClientTrigger wasn't private or presence channel. Client events only work on these types of channels."); // memoize trigger so it's not being created every render var trigger = React.useCallback(function (eventName, data) { invariant_1(eventName, "Must pass event name to trigger a client event."); channel && channel.trigger(eventName, data); }, [channel]); return trigger; } /** * Hook to provide a trigger function that calls the server defined in `PusherProviderProps.triggerEndpoint` using `fetch`. * Any `auth?.headers` in the config object will be passed with the `fetch` call. * * @param channelName name of channel to call trigger on * @typeparam TData shape of the data you're sending with the event * * @example * ```typescript * const trigger = useTrigger<{message: string}>('my-channel'); * trigger('my-event', {message: 'hello'}); * ``` */ function useTrigger(channelName) { var _a = usePusher(), client = _a.client, triggerEndpoint = _a.triggerEndpoint; // you can't use this if you haven't supplied a triggerEndpoint. invariant_1(triggerEndpoint, "No trigger endpoint specified to <PusherProvider />. Cannot trigger an event."); // subscribe to the channel we'll be triggering to. useChannel(channelName); // memoized trigger function to return var trigger = React.useCallback(function (eventName, data) { var _a; var fetchOptions = { method: "POST", body: JSON.stringify({ channelName: channelName, eventName: eventName, data: data }) }; if (client && ((_a = client.config) === null || _a === void 0 ? void 0 : _a.auth)) { fetchOptions.headers = client.config.auth.headers; } else { console.warn(NO_AUTH_HEADERS_WARNING); } return fetch(triggerEndpoint, fetchOptions); }, [client, triggerEndpoint, channelName]); return trigger; } var NO_AUTH_HEADERS_WARNING = "No auth parameters supplied to <PusherProvider />. Your events will be unauthenticated."; function unwrapExports (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } var arrayWithHoles = _arrayWithHoles; function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } var iterableToArrayLimit = _iterableToArrayLimit; function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } var arrayLikeToArray = _arrayLikeToArray; function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen); } var unsupportedIterableToArray = _unsupportedIterableToArray; function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var nonIterableRest = _nonIterableRest; function _slicedToArray(arr, i) { return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest(); } var slicedToArray = _slicedToArray; function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var defineProperty = _defineProperty; function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? Object(arguments[i]) : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { defineProperty(target, key, source[key]); }); } return target; } var objectSpread = _objectSpread; var DEFAULT_CONFIGURATION = {reachabilityUrl:'https://clients3.google.com/generate_204',reachabilityTest:function reachabilityTest(response){return Promise.resolve(response.status===204);},reachabilityShortTimeout:5*1000,reachabilityLongTimeout:60*1000,reachabilityRequestTimeout:15*1000}; /** * Copyright (c) 2014-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Op = Object.prototype; var hasOwn = Op.hasOwnProperty; var undefined$1; // More compressible than void 0. var $Symbol = typeof Symbol === "function" ? Symbol : {}; var iteratorSymbol = $Symbol.iterator || "@@iterator"; var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function wrap(innerFn, outerFn, self, tryLocsList) { // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; var generator = Object.create(protoGenerator.prototype); var context = new Context(tryLocsList || []); // The ._invoke method unifies the implementations of the .next, // .throw, and .return methods. generator._invoke = makeInvokeMethod(innerFn, self, context); return generator; } // Try/catch helper to minimize deoptimizations. Returns a completion // record like context.tryEntries[i].completion. This interface could // have been (and was previously) designed to take a closure to be // invoked without arguments, but in all the cases we care about we // already have an existing method we want to call, so there's no need // to create a new function object. We can even get away with assuming // the method takes exactly one argument, since that happens to be true // in every case, so we don't have to touch the arguments object. The // only additional allocation required is the completion record, which // has a stable shape and so hopefully should be cheap to allocate. function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } var GenStateSuspendedStart = "suspendedStart"; var GenStateSuspendedYield = "suspendedYield"; var GenStateExecuting = "executing"; var GenStateCompleted = "completed"; // Returning this object from the innerFn has the same effect as // breaking out of the dispatch switch statement. var ContinueSentinel = {}; // Dummy constructor functions that we use as the .constructor and // .constructor.prototype properties for functions that return Generator // objects. For full spec compliance, you may wish to configure your // minifier not to mangle the names of these two functions. function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} // This is a polyfill for %IteratorPrototype% for environments that // don't natively support it. var IteratorPrototype = {}; IteratorPrototype[iteratorSymbol] = function () { return this; }; var getProto = Object.getPrototypeOf; var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); if (NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { // This environment has a native %IteratorPrototype%; use it instead // of the polyfill. IteratorPrototype = NativeIteratorPrototype; } var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; GeneratorFunctionPrototype.constructor = GeneratorFunction; GeneratorFunctionPrototype[toStringTagSymbol] = GeneratorFunction.displayName = "GeneratorFunction"; // Helper for defining the .next, .throw, and .return methods of the // Iterator interface in terms of a single ._invoke method. function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function(method) { prototype[method] = function(arg) { return this._invoke(method, arg); }; }); } function isGeneratorFunction (genFun) { var ctor = typeof genFun === "function" && genFun.constructor; return ctor ? ctor === GeneratorFunction || // For the native GeneratorFunction constructor, the best we can // do is to check its .name property. (ctor.displayName || ctor.name) === "GeneratorFunction" : false; } function mark (genFun) { if (Object.setPrototypeOf) { Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); } else { genFun.__proto__ = GeneratorFunctionPrototype; if (!(toStringTagSymbol in genFun)) { genFun[toStringTagSymbol] = "GeneratorFunction"; } } genFun.prototype = Object.create(Gp); return genFun; } // Within the body of any async function, `await x` is transformed to // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test // `hasOwn.call(value, "__await")` to determine if the yielded value is // meant to be awaited. function awrap (arg) { return { __await: arg }; } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if (record.type === "throw") { reject(record.arg); } else { var result = record.arg; var value = result.value; if (value && typeof value === "object" && hasOwn.call(value, "__await")) { return PromiseImpl.resolve(value.__await).then(function(value) { invoke("next", value, resolve, reject); }, function(err) { invoke("throw", err, resolve, reject); }); } return PromiseImpl.resolve(value).then(function(unwrapped) { // When a yielded Promise is resolved, its final value becomes // the .value of the Promise<{value,done}> result for the // current iteration. result.value = unwrapped; resolve(result); }, function(error) { // If a rejected Promise was yielded, throw the rejection back // into the async generator function so it can be handled there. return invoke("throw", error, resolve, reject); }); } } var previousPromise; function enqueue(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function(resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = // If enqueue has been called before, then we want to wait until // all previous Promises have been resolved before calling invoke, // so that results are always delivered in the correct order. If // enqueue has not been called before, then it is important to // call invoke immediately, without waiting on a callback to fire, // so that the async generator function has the opportunity to do // any necessary setup in a predictable way. This predictability // is why the Promise constructor synchronously invokes its // executor callback, and why async functions synchronously // execute code before the first await. Since we implement simple // async functions in terms of async generators, it is especially // important to get this right, even though it requires care. previousPromise ? previousPromise.then( callInvokeWithMethodAndArg, // Avoid propagating failures to Promises returned by later // invocations of the iterator. callInvokeWithMethodAndArg ) : callInvokeWithMethodAndArg(); } // Define the unified helper method that is used to implement .next, // .throw, and .return (see defineIteratorMethods). this._invoke = enqueue; } defineIteratorMethods(AsyncIterator.prototype); AsyncIterator.prototype[asyncIteratorSymbol] = function () { return this; }; // Note that simple async functions are implemented on top of // AsyncIterator objects; they just return a Promise for the value of // the final result produced by the iterator. function async (innerFn, outerFn, self, tryLocsList, PromiseImpl) { if (PromiseImpl === void 0) PromiseImpl = Promise; var iter = new AsyncIterator( wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl ); return isGeneratorFunction(outerFn) ? iter // If outerFn is a generator, return the full iterator. : iter.next().then(function(result) { return result.done ? result.value : iter.next(); }); } function makeInvokeMethod(innerFn, self, context) { var state = GenStateSuspendedStart; return function invoke(method, arg) { if (state === GenStateExecuting) { throw new Error("Generator is already running"); } if (state === GenStateCompleted) { if (method === "throw") { throw arg; } // Be forgiving, per 25.3.3.3.3 of the spec: // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume return doneResult(); } context.method = method; context.arg = arg; while (true) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if (context.method === "next") { // Setting context._sent for legacy support of Babel's // function.sent implementation. context.sent = context._sent = context.arg; } else if (context.method === "throw") { if (state === GenStateSuspendedStart) { state = GenStateCompleted; throw context.arg; } context.dispatchException(context.arg); } else if (context.method === "return") { context.abrupt("return", context.arg); } state = GenStateExecuting; var record = tryCatch(innerFn, self, context); if (record.type === "normal") { // If an exception is thrown from innerFn, we leave state === // GenStateExecuting and loop back for another invocation. state = context.done ? GenStateCompleted : GenStateSuspendedYield; if (record.arg === ContinueSentinel) { continue; } return { value: record.arg, done: context.done }; } else if (record.type === "throw") { state = GenStateCompleted; // Dispatch the exception by looping back around to the // context.dispatchException(context.arg) call above. context.method = "throw"; context.arg = record.arg; } } }; } // Call delegate.iterator[context.method](context.arg) and handle the // result, either by returning a { value, done } result from the // delegate iterator, or by modifying context.method and context.arg, // setting context.delegate to null, and returning the ContinueSentinel. function maybeInvokeDelegate(delegate, context) { var method = delegate.iterator[context.method]; if (method === undefined$1) { // A .throw or .return when the delegate iterator has no .throw // method always terminates the yield* loop. context.delegate = null; if (context.method === "throw") { // Note: ["return"] must be used for ES3 parsing compatibility. if (delegate.iterator["return"]) { // If the delegate iterator has a return method, give it a // chance to clean up. context.method = "return"; context.arg = undefined$1; maybeInvokeDelegate(delegate, context); if (context.method === "throw") { // If maybeInvokeDelegate(context) changed context.method from // "return" to "throw", let that override the TypeError below. return ContinueSentinel; } } context.method = "throw"; context.arg = new TypeError( "The iterator does not provide a 'throw' method"); } return ContinueSentinel; } var record = tryCatch(method, delegate.iterator, context.arg); if (record.type === "throw") { context.method = "throw"; context.arg = record.arg; context.delegate = null; return ContinueSentinel; } var info = record.arg; if (! info) { context.method = "throw"; context.arg = new TypeError("iterator result is not an object"); context.delegate = null; return ContinueSentinel; } if (info.done) { // Assign the result of the finished delegate to the temporary // variable specified by delegate.resultName (see delegateYield). context[delegate.resultName] = info.value; // Resume execution at the desired location (see delegateYield). context.next = delegate.nextLoc; // If context.method was "throw" but the delegate handled the // exception, let the outer generator proceed normally. If // context.method was "next", forget context.arg since it has been // "consumed" by the delegate iterator. If context.method was // "return", allow the original .return call to continue in the // outer generator. if (context.method !== "return") { context.method = "next"; context.arg = undefined$1; } } else { // Re-yield the result returned by the delegate method. return info; } // The delegate iterator is finished, so forget it and continue with // the outer generator. context.delegate = null; return ContinueSentinel; } // Define Generator.prototype.{next,throw,return} in terms of the // unified ._invoke helper method. defineIteratorMethods(Gp); Gp[toStringTagSymbol] = "Generator"; // A Generator should always return itself as the iterator object when the // @@iterator function is called on it. Some browsers' implementations of the // iterator prototype chain incorrectly implement this, causing the Generator // object to not be returned from this call. This ensures that doesn't happen. // See https://github.com/facebook/regenerator/issues/274 for more details. Gp[iteratorSymbol] = function() { return this; }; Gp.toString = function() { return "[object Generator]"; }; function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; if (1 in locs) { entry.catchLoc = locs[1]; } if (2 in locs) { entry.finallyLoc = locs[2]; entry.afterLoc = locs[3]; } this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal"; delete record.arg; entry.completion = record; } function Context(tryLocsList) { // The root entry object (effectively a try statement without a catch // or a finally block) gives us a place to store values thrown from // locations where there is no enclosing try statement. this.tryEntries = [{ tryLoc: "root" }]; tryLocsList.forEach(pushTryEntry, this); this.reset(true); } function keys (object) { var keys = []; for (var key in object) { keys.push(key); } keys.reverse(); // Rather than returning an object with a next method, we keep // things simple and return the next function itself. return function next() { while (keys.length) { var key = keys.pop(); if (key in object) { next.value = key; next.done = false; return next; } } // To avoid creating an additional object, we just hang the .value // and .done properties off the next function object itself. This // also ensures that the minifier will not anonymize the function. next.done = true; return next; }; } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) { return iteratorMethod.call(iterable); } if (typeof iterable.next === "function") { return iterable; } if (!isNaN(iterable.length)) { var i = -1, next = function next() { while (++i < iterable.length) { if (hasOwn.call(iterable, i)) { next.value = iterable[i]; next.done = false; return next; } } next.value = undefined$1; next.done = true; return next; }; return next.next = next; } } // Return an iterator with no values. return { next: doneResult }; } function doneResult() { return { value: undefined$1, done: true }; } Context.prototype = { constructor: Context, reset: function(skipTempReset) { this.prev = 0; this.next = 0; // Resetting context._sent for legacy support of Babel's // function.sent implementation. this.sent = this._sent = undefined$1; this.done = false; this.delegate = null; this.method = "next"; this.arg = undefined$1; this.tryEntries.forEach(resetTryEntry); if (!skipTempReset) { for (var name in this) { // Not sure about the optimal order of these conditions: if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) { this[name] = undefined$1; } } } }, stop: function() { this.done = true; var rootEntry = this.tryEntries[0]; var rootRecord = rootEntry.completion; if (rootRecord.type === "throw") { throw rootRecord.arg; } return this.rval; }, dispatchException: function(exception) { if (this.done) { throw exception; } var context = this; function handle(loc, caught) { record.type = "throw"; record.arg = exception; context.next = loc; if (caught) { // If the dispatched exception was caught by a catch block, // then let that catch block handle the exception normally. context.method = "next"; context.arg = undefined$1; } return !! caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; var record = entry.completion; if (entry.tryLoc === "root") { // Exception thrown outside of any try block that could handle // it, so set the completion value of the entire function to // throw the exception. return handle("end"); } if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"); var hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } else if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else if (hasCatch) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } } else if (hasFinally) { if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else { throw new Error("try statement without catch or finally"); } } } }, abrupt: function(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) { // Ignore the finally entry if control is not jumping to a // location outside the try/catch block. finallyEntry = null; } var record = finallyEntry ? finallyEntry.completion : {}; record.type = type; record.arg = arg; if (finallyEntry) { this.method = "next"; this.next = finallyEntry.finallyLoc; return ContinueSentinel; } return this.complete(record); }, complete: function(record, afterLoc) { if (record.type === "throw") { throw record.arg; } if (record.type === "break" || record.type === "continue") { this.next = record.arg; } else if (record.type === "return") { this.rval = this.arg = record.arg; this.method = "return"; this.next = "end"; } else if (record.type === "normal" && afterLoc) { this.next = afterLoc; } return ContinueSentinel; }, finish: function(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) { this.complete(entry.completion, entry.afterLoc); resetTryEntry(entry); return ContinueSentinel; } } }, "catch": function(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if (record.type === "throw") { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } // The context.catch method must only be called with a location // argument that corresponds to a known catch block. throw new Error("illegal catch attempt"); }, delegateYield: function(iterable, resultName, nextLoc) { this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }; if (this.method === "next") { // Deliberately forget the last sent value so that we don't // accidentally pass it on to the delegate. this.arg = undefined$1; } return ContinueSentinel; } }; // Export a default namespace that plays well with Rollup var _regeneratorRuntime = { wrap, isGeneratorFunction, AsyncIterator, mark, awrap, async, keys, values }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var classCallCheck = _classCallCheck; var RNCNetInfo=reactNative$1.NativeModules.RNCNetInfo; if(!RNCNetInfo){throw new Error("@react-native-community/netinfo: NativeModule.RNCNetInfo is null. To fix this issue try these steps:\n\n\u2022 Run `react-native link @react-native-community/netinfo` in the project root.\n\u2022 Rebuild and re-run the app.\n\u2022 If you are using CocoaPods on iOS, run `pod install` in the `ios` directory and then rebuild and re-run the app. You may also need to re-open Xcode to get the new pods.\n\u2022 Check that the library was linked correctly when you used the link command by running through the manual installation instructions in the README.\n* If you are getting this error while unit testing you need to mock the native module. Follow the guide in the README.\n\nIf none of these fix the issue, please open an issue on the Github repository: https://github.com/react-native-community/react-native-netinfo");}var nativeEventEmitter=null;var NativeInterface = objectSpread({},RNCNetInfo,{get eventEmitter(){if(!nativeEventEmitter){nativeEventEmitter=new reactNative$1.NativeEventEmitter(RNCNetInfo);}return nativeEventEmitter;}}); var InternetReachability=function InternetReachability(configuration,listener){var _this=this;classCallCheck(this,InternetReachability);this._isInternetReachable=undefined;this._currentInternetReachabilityCheckHandler=null;this._currentTimeoutHandle=null;this._setIsInternetReachable=function(isInternetReachable){if(_this._isInternetReachable===isInternetReachable){return;}_this._isInternetReachable=isInternetReachable;_this._listener(_this._isInternetReachable);};this._setExpectsConnection=function(expectsConnection){if(_this._currentInternetReachabilityCheckHandler!==null){_this._currentInternetReachabilityCheckHandler.cancel();_this._currentInternetReachabilityCheckHandler=null;}if(_this._currentTimeoutHandle!==null){clearTimeout(_this._currentTimeoutHandle);_this._currentTimeoutHandle=null;}if(expectsConnection){if(!_this._isInternetReachable){_this._setIsInternetReachable(null);}_this._currentInternetReachabilityCheckHandler=_this._checkInternetReachability();}else {_this._setIsInternetReachable(false);}};this._checkInternetReachability=function(){var responsePromise=fetch(_this._configuration.reachabilityUrl,{method:'HEAD',cache:'no-cache'});var timeoutHandle;var timeoutPromise=new Promise(function(_,reject){timeoutHandle=setTimeout(function(){return reject('timedout');},_this._configuration.reachabilityRequestTimeout);});var cancel=function cancel(){};var cancelPromise=new Promise(function(_,reject){cancel=function cancel(){return reject('canceled');};});var promise=Promise.race([responsePromise,timeoutPromise,cancelPromise]).then(function(response){return _this._configuration.reachabilityTest(response);}).then(function(result){_this._setIsInternetReachable(result);var nextTimeoutInterval=_this._isInternetReachable?_this._configuration.reachabilityLongTimeout:_this._configuration.reachabilityShortTimeout;_this._currentTimeoutHandle=setTimeout(_this._checkInternetReachability,nextTimeoutInterval);}).catch(function(error){if(error!=='canceled'){_this._setIsInternetReachable(false);_this._currentTimeoutHandle=setTimeout(_this._checkInternetReachability,_this._configuration.reachabilityShortTimeout);}}).then(function(){clearTimeout(timeoutHandle);},function(error){clearTimeout(timeoutHandle);throw error;});return {promise:promise,cancel:cancel};};this.update=function(state){if(typeof state.isInternetReachable==='boolean'){_this._setIsInternetReachable(state.isInternetReachable);}else {_this._setExpectsConnection(state.isConnected);}};this.currentState=function(){return _this._isInternetReachable;};this.tearDown=function(){if(_this._currentInternetReachabilityCheckHandler!==null){_this._currentInternetReachabilityCheckHandler.cancel();_this._currentInternetReachabilityCheckHandler=null;}if(_this._currentTimeoutHandle!==null){clearTimeout(_this._currentTimeoutHandle);_this._currentTimeoutHandle=null;}};this._configuration=configuration;this._listener=listener;}; var DEVICE_CONNECTIVITY_EVENT='netInfo.networkStatusDidChange'; var State=function State(configuration){var _this=this;classCallCheck(this,State);this._nativeEventSubscription=null;this._subscriptions=new Set();this._latestState=null;this._handleNativeStateUpdate=function(state){_this._internetReachability.update(state);var convertedState=_this._convertState(state);_this._latestState=convertedState;_this._subscriptions.forEach(function(handler){return handler(convertedState);});};this._handleInternetReachabilityUpdate=function(isInternetReachable){if(!_this._latestState){return;}var nextState=objectSpread({},_this._latestState,{isInternetReachable:isInternetReachable});_this._latestState=nextState;_this._subscriptions.forEach(function(handler){return handler(nextState);});};this._fetchCurrentState=function _callee(requestedInterface){var state,convertedState;return _regeneratorRuntime.async(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:_context.next=2;return _regeneratorRuntime.awrap(NativeInterface.getCurrentState(requestedInterface));case 2:state=_context.sent;_this._internetReachability.update(state);convertedState=_this._convertState(state);if(!requestedInterface){_this._latestState=convertedState;}return _context.abrupt("return",convertedState);case 7:case"end":return _context.stop();}}},null,this);};this._convertState=function(input){if(typeof input.isInternetReachable==='boolean'){return input;}else {return objectSpread({},input,{isInternetReachable:_this._internetReachability.currentState()});}};this.latest=function(requestedInterface){if(requestedInterface){return _this._fetchCurrentState(requestedInterface);}else if(_this._latestState){return Promise.resolve(_this._latestState);}else {return _this._fetchCurrentState();}};this.add=function(handler){_this._subscriptions.add(handler);if(_this._latestState){handler(_this._latestState);}else {_this.latest().then(handler);}};this.remove=function(handler){_this._subscriptions.delete(handler);};this.tearDown=function(){if(_this._internetReachability){_this._internetReachability.tearDown();}if(_this._nativeEventSubscription){_this._nativeEventSubscription.remove();}_this._subscriptions.clear();};this._internetReachability=new InternetReachability(configuration,this._handleInternetReachabilityUpdate);this._nativeEventSubscription=NativeInterface.eventEmitter.addListener(DEVICE_CONNECTIVITY_EVENT,this._handleNativeStateUpdate);this._fetchCurrentState();}; var NetInfoStateType;(function(NetInfoStateType){NetInfoStateType["unknown"]="unknown";NetInfoStateType["none"]="none";NetInfoStateType["cellular"]="cellular";NetInfoStateType["wifi"]="wifi";NetInfoStateType["bluetooth"]="bluetooth";NetInfoStateType["ethernet"]="ethernet";NetInfoStateType["wimax"]="wimax";NetInfoStateType["vpn"]="vpn";NetInfoStateType["other"]="other";})(NetInfoStateType||(NetInfoStateType={}));var NetInfoCellularGeneration;(function(NetInfoCellularGeneration){NetInfoCellularGeneration["2g"]="2g";NetInfoCellularGeneration["3g"]="3g";NetInfoCellularGeneration["4g"]="4g";})(NetInfoCellularGeneration||(NetInfoCellularGeneration={})); var _configuration=DEFAULT_CONFIGURATION;var _state=null;var createState=function createState(){return new State(_configuration);};function configure(configuration){_configuration=objectSpread({},DEFAULT_CONFIGURATION,configuration);if(_state){_state.tearDown();_state=createState();}}function fetch$1(requestedInterface){if(!_state){_state=createState();}return _state.latest(requestedInterface);}function addEventListener(listener){if(!_state){_state=createState();}_state.add(listener);return function(){_state&&_state.remove(listener);};}function useNetInfo(configuration){if(configuration){configure(configuration);}var _useState=React.useState({type:NetInfoStateType.unknown,isConnected:false,isInternetReachable:false,details:null}),_useState2=slicedToArray(_useState,2),netInfo=_useState2[0],setNetInfo=_useState2[1];React.useEffect(function(){return addEventListener(setNetInfo);},[]);return netInfo;}var require$$0 = {configure:configure,fetch:fetch$1,addEventListener:addEventListener,useNetInfo:useNetInfo}; var pusher = createCommonjsModule(function (module) { /*! * Pusher JavaScript Library v7.0.0 * https://pusher.com/ * * Copyright 2020, Pusher * Released under the MIT licence. */ module.exports=function(t){var n={};function e(r){if(n[r])return n[r].exports;var o=n[r]={i:r,l:!1,exports:{}};return t[r].call(o.exports,o,o.exports,e),o.l=!0,o.exports}return e.m=t,e.c=n,e.d=function(t,n,r){e.o(t,n)||Object.defineProperty(t,n,{enumerable:!0,get:r});},e.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbo