diff options
author | Minteck <nekostarfan@gmail.com> | 2021-08-24 14:41:48 +0200 |
---|---|---|
committer | Minteck <nekostarfan@gmail.com> | 2021-08-24 14:41:48 +0200 |
commit | d25e11bee6ca5ca523884da132d18e1400e077b9 (patch) | |
tree | 8af39fde19f7ed640a60fb397c7edd647dff1c4c /node_modules/p-event | |
download | kartik-iridium-d25e11bee6ca5ca523884da132d18e1400e077b9.tar.gz kartik-iridium-d25e11bee6ca5ca523884da132d18e1400e077b9.tar.bz2 kartik-iridium-d25e11bee6ca5ca523884da132d18e1400e077b9.zip |
Initial commit
Diffstat (limited to 'node_modules/p-event')
-rw-r--r-- | node_modules/p-event/index.js | 272 | ||||
-rw-r--r-- | node_modules/p-event/license | 9 | ||||
-rw-r--r-- | node_modules/p-event/package.json | 52 | ||||
-rw-r--r-- | node_modules/p-event/readme.md | 315 |
4 files changed, 648 insertions, 0 deletions
diff --git a/node_modules/p-event/index.js b/node_modules/p-event/index.js new file mode 100644 index 0000000..23ee421 --- /dev/null +++ b/node_modules/p-event/index.js @@ -0,0 +1,272 @@ +'use strict'; +const pTimeout = require('p-timeout'); + +const symbolAsyncIterator = Symbol.asyncIterator || '@@asyncIterator'; + +const normalizeEmitter = emitter => { + const addListener = emitter.on || emitter.addListener || emitter.addEventListener; + const removeListener = emitter.off || emitter.removeListener || emitter.removeEventListener; + + if (!addListener || !removeListener) { + throw new TypeError('Emitter is not compatible'); + } + + return { + addListener: addListener.bind(emitter), + removeListener: removeListener.bind(emitter) + }; +}; + +const normalizeEvents = event => Array.isArray(event) ? event : [event]; + +const multiple = (emitter, event, options) => { + let cancel; + const ret = new Promise((resolve, reject) => { + options = Object.assign({ + rejectionEvents: ['error'], + multiArgs: false, + resolveImmediately: false + }, options); + + if (!(options.count >= 0 && (options.count === Infinity || Number.isInteger(options.count)))) { + throw new TypeError('The `count` option should be at least 0 or more'); + } + + // Allow multiple events + const events = normalizeEvents(event); + + const items = []; + const {addListener, removeListener} = normalizeEmitter(emitter); + + const onItem = (...args) => { + const value = options.multiArgs ? args : args[0]; + + if (options.filter && !options.filter(value)) { + return; + } + + items.push(value); + + if (options.count === items.length) { + cancel(); + resolve(items); + } + }; + + const rejectHandler = error => { + cancel(); + reject(error); + }; + + cancel = () => { + for (const event of events) { + removeListener(event, onItem); + } + + for (const rejectionEvent of options.rejectionEvents) { + removeListener(rejectionEvent, rejectHandler); + } + }; + + for (const event of events) { + addListener(event, onItem); + } + + for (const rejectionEvent of options.rejectionEvents) { + addListener(rejectionEvent, rejectHandler); + } + + if (options.resolveImmediately) { + resolve(items); + } + }); + + ret.cancel = cancel; + + if (typeof options.timeout === 'number') { + const timeout = pTimeout(ret, options.timeout); + timeout.cancel = cancel; + return timeout; + } + + return ret; +}; + +module.exports = (emitter, event, options) => { + if (typeof options === 'function') { + options = {filter: options}; + } + + options = Object.assign({}, options, { + count: 1, + resolveImmediately: false + }); + + const arrayPromise = multiple(emitter, event, options); + + const promise = arrayPromise.then(array => array[0]); + promise.cancel = arrayPromise.cancel; + + return promise; +}; + +module.exports.multiple = multiple; + +module.exports.iterator = (emitter, event, options) => { + if (typeof options === 'function') { + options = {filter: options}; + } + + // Allow multiple events + const events = normalizeEvents(event); + + options = Object.assign({ + rejectionEvents: ['error'], + resolutionEvents: [], + limit: Infinity, + multiArgs: false + }, options); + + const {limit} = options; + const isValidLimit = limit >= 0 && (limit === Infinity || Number.isInteger(limit)); + if (!isValidLimit) { + throw new TypeError('The `limit` option should be a non-negative integer or Infinity'); + } + + if (limit === 0) { + // Return an empty async iterator to avoid any further cost + return { + [Symbol.asyncIterator]() { + return this; + }, + next() { + return Promise.resolve({done: true, value: undefined}); + } + }; + } + + let isLimitReached = false; + + const {addListener, removeListener} = normalizeEmitter(emitter); + + let done = false; + let error; + let hasPendingError = false; + const nextQueue = []; + const valueQueue = []; + let eventCount = 0; + + const valueHandler = (...args) => { + eventCount++; + isLimitReached = eventCount === limit; + + const value = options.multiArgs ? args : args[0]; + + if (nextQueue.length > 0) { + const {resolve} = nextQueue.shift(); + + resolve({done: false, value}); + + if (isLimitReached) { + cancel(); + } + + return; + } + + valueQueue.push(value); + + if (isLimitReached) { + cancel(); + } + }; + + const cancel = () => { + done = true; + for (const event of events) { + removeListener(event, valueHandler); + } + + for (const rejectionEvent of options.rejectionEvents) { + removeListener(rejectionEvent, rejectHandler); + } + + for (const resolutionEvent of options.resolutionEvents) { + removeListener(resolutionEvent, resolveHandler); + } + + while (nextQueue.length > 0) { + const {resolve} = nextQueue.shift(); + resolve({done: true, value: undefined}); + } + }; + + const rejectHandler = (...args) => { + error = options.multiArgs ? args : args[0]; + + if (nextQueue.length > 0) { + const {reject} = nextQueue.shift(); + reject(error); + } else { + hasPendingError = true; + } + + cancel(); + }; + + const resolveHandler = (...args) => { + const value = options.multiArgs ? args : args[0]; + + if (options.filter && !options.filter(value)) { + return; + } + + if (nextQueue.length > 0) { + const {resolve} = nextQueue.shift(); + resolve({done: true, value}); + } else { + valueQueue.push(value); + } + + cancel(); + }; + + for (const event of events) { + addListener(event, valueHandler); + } + + for (const rejectionEvent of options.rejectionEvents) { + addListener(rejectionEvent, rejectHandler); + } + + for (const resolutionEvent of options.resolutionEvents) { + addListener(resolutionEvent, resolveHandler); + } + + return { + [symbolAsyncIterator]() { + return this; + }, + next() { + if (valueQueue.length > 0) { + const value = valueQueue.shift(); + return Promise.resolve({done: done && valueQueue.length === 0 && !isLimitReached, value}); + } + + if (hasPendingError) { + hasPendingError = false; + return Promise.reject(error); + } + + if (done) { + return Promise.resolve({done: true, value: undefined}); + } + + return new Promise((resolve, reject) => nextQueue.push({resolve, reject})); + }, + return(value) { + cancel(); + return Promise.resolve({done, value}); + } + }; +}; diff --git a/node_modules/p-event/license b/node_modules/p-event/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/p-event/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/p-event/package.json b/node_modules/p-event/package.json new file mode 100644 index 0000000..00024aa --- /dev/null +++ b/node_modules/p-event/package.json @@ -0,0 +1,52 @@ +{ + "name": "p-event", + "version": "2.3.1", + "description": "Promisify an event by waiting for it to be emitted", + "license": "MIT", + "repository": "sindresorhus/p-event", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=6" + }, + "scripts": { + "test": "xo && ava" + }, + "files": [ + "index.js" + ], + "keywords": [ + "promise", + "events", + "event", + "emitter", + "eventemitter", + "event-emitter", + "emit", + "emits", + "listener", + "promisify", + "addlistener", + "addeventlistener", + "wait", + "waits", + "on", + "browser", + "dom", + "async", + "await", + "promises", + "bluebird" + ], + "dependencies": { + "p-timeout": "^2.0.1" + }, + "devDependencies": { + "ava": "^1.2.1", + "delay": "^4.1.0", + "xo": "^0.24.0" + } +} diff --git a/node_modules/p-event/readme.md b/node_modules/p-event/readme.md new file mode 100644 index 0000000..840b0e1 --- /dev/null +++ b/node_modules/p-event/readme.md @@ -0,0 +1,315 @@ +# p-event [![Build Status](https://travis-ci.org/sindresorhus/p-event.svg?branch=master)](https://travis-ci.org/sindresorhus/p-event) + +> Promisify an event by waiting for it to be emitted + +Useful when you need only one event emission and want to use it with promises or await it in an async function. + +It's works with any event API in Node.js and the browser (using a bundler). + +If you want multiple individual events as they are emitted, you can use the `pEvent.iterator()` method. [Observables](https://medium.com/@benlesh/learning-observable-by-building-observable-d5da57405d87) can be useful too. + + +## Install + +``` +$ npm install p-event +``` + + +## Usage + +In Node.js: + +```js +const pEvent = require('p-event'); +const emitter = require('./some-event-emitter'); + +(async () => { + try { + const result = await pEvent(emitter, 'finish'); + + // `emitter` emitted a `finish` event + console.log(result); + } catch (error) { + // `emitter` emitted an `error` event + console.error(error); + } +})(); +``` + +In the browser: + +```js +const pEvent = require('p-event'); + +(async () => { + await pEvent(document, 'DOMContentLoaded'); + console.log('😎'); +})(); +``` + +Async iteration: + +```js +const pEvent = require('p-event'); +const emitter = require('./some-event-emitter'); + +(async () => { + const asyncIterator = pEvent.iterator(emitter, 'data', { + resolutionEvents: ['finish'] + }); + + for await (const event of asyncIterator) { + console.log(event); + } +})(); +``` + + +## API + +### pEvent(emitter, event, [options]) +### pEvent(emitter, event, filter) + +Returns a `Promise` that is fulfilled when `emitter` emits an event matching `event`, or rejects if `emitter` emits any of the events defined in the `rejectionEvents` option. + +**Note**: `event` is a string for a single event type, for example, `'data'`. To listen on multiple +events, pass an array of strings, such as `['started', 'stopped']`. + +The returned promise has a `.cancel()` method, which when called, removes the event listeners and causes the promise to never be settled. + +#### emitter + +Type: `Object` + +Event emitter object. + +Should have either a `.on()`/`.addListener()`/`.addEventListener()` and `.off()`/`.removeListener()`/`.removeEventListener()` method, like the [Node.js `EventEmitter`](https://nodejs.org/api/events.html) and [DOM events](https://developer.mozilla.org/en-US/docs/Web/Events). + +#### event + +Type: `string | string[]` + +Name of the event or events to listen to. + +If the same event is defined both here and in `rejectionEvents`, this one takes priority. + +#### options + +Type: `Object` + +##### rejectionEvents + +Type: `string[]`<br> +Default: `['error']` + +Events that will reject the promise. + +##### multiArgs + +Type: `boolean`<br> +Default: `false` + +By default, the promisified function will only return the first argument from the event callback, which works fine for most APIs. This option can be useful for APIs that return multiple arguments in the callback. Turning this on will make it return an array of all arguments from the callback, instead of just the first argument. This also applies to rejections. + +Example: + +```js +const pEvent = require('p-event'); +const emitter = require('./some-event-emitter'); + +(async () => { + const [foo, bar] = await pEvent(emitter, 'finish', {multiArgs: true}); +})(); +``` + +##### timeout + +Type: `number`<br> +Default: `Infinity` + +Time in milliseconds before timing out. + +##### filter + +Type: `Function` + +Filter function for accepting an event. + +```js +const pEvent = require('p-event'); +const emitter = require('./some-event-emitter'); + +(async () => { + const result = await pEvent(emitter, '🦄', value => value > 3); + // Do something with first 🦄 event with a value greater than 3 +})(); +``` + +### pEvent.multiple(emitter, event, options) + +Wait for multiple event emissions. Returns an array. + +This method has the same arguments and options as `pEvent()` with the addition of the following options: + +#### options + +Type: `Object` + +##### count + +*Required*<br> +Type: `number` + +The number of times the event needs to be emitted before the promise resolves. + +##### resolveImmediately + +Type: `boolean`<br> +Default: `false` + +Whether to resolve the promise immediately. Emitting one of the `rejectionEvents` won't throw an error. + +**Note**: The returned array will be mutated when an event is emitted. + +Example: + +```js +const emitter = new EventEmitter(); + +const promise = pEvent.multiple(emitter, 'hello', { + resolveImmediately: true, + count: Infinity +}); + +const result = await promise; +console.log(result); +//=> [] + +emitter.emit('hello', 'Jack'); +console.log(result); +//=> ['Jack'] + +emitter.emit('hello', 'Mark'); +console.log(result); +//=> ['Jack', 'Mark'] + +// Stops listening +emitter.emit('error', new Error('😿')); + +emitter.emit('hello', 'John'); +console.log(result); +//=> ['Jack', 'Mark'] +``` + +### pEvent.iterator(emitter, event, [options]) +### pEvent.iterator(emitter, event, filter) + +Returns an [async iterator](http://2ality.com/2016/10/asynchronous-iteration.html) that lets you asynchronously iterate over events of `event` emitted from `emitter`. The iterator ends when `emitter` emits an event matching any of the events defined in `resolutionEvents`, or rejects if `emitter` emits any of the events defined in the `rejectionEvents` option. + +This method has the same arguments and options as `pEvent()` with the addition of the following options: + +#### options + +Type: `Object` + +##### limit + +Type: `number` *(non-negative integer)*<br> +Default: `Infinity` + +Maximum number of events for the iterator before it ends. When the limit is reached, the iterator will be marked as `done`. This option is useful to paginate events, for example, fetching 10 events per page. + +##### resolutionEvents + +Type: `string[]`<br> +Default: `[]` + +Events that will end the iterator. + + +## Before and after + +```js +const fs = require('fs'); + +function getOpenReadStream(file, callback) { + const stream = fs.createReadStream(file); + + stream.on('open', () => { + callback(null, stream); + }); + + stream.on('error', error => { + callback(error); + }); +} + +getOpenReadStream('unicorn.txt', (error, stream) => { + if (error) { + console.error(error); + return; + } + + console.log('File descriptor:', stream.fd); + stream.pipe(process.stdout); +}); +``` + +```js +const fs = require('fs'); +const pEvent = require('p-event'); + +async function getOpenReadStream(file) { + const stream = fs.createReadStream(file); + await pEvent(stream, 'open'); + return stream; +} + +(async () => { + const stream = await getOpenReadStream('unicorn.txt'); + console.log('File descriptor:', stream.fd); + stream.pipe(process.stdout); +})().catch(console.error); +``` + + +## Tip + +### Dealing with calls that resolve with an error code + +Some functions might use a single event for success and for certain errors. Promises make it easy to have combined error handler for both error events and successes containing values which represent errors. + +```js +const pEvent = require('p-event'); +const emitter = require('./some-event-emitter'); + +(async () => { + try { + const result = await pEvent(emitter, 'finish'); + + if (result === 'unwanted result') { + throw new Error('Emitter finished with an error'); + } + + // `emitter` emitted a `finish` event with an acceptable value + console.log(result); + } catch (error) { + // `emitter` emitted an `error` event or + // emitted a `finish` with 'unwanted result' + console.error(error); + } +})(); +``` + + +## Related + +- [pify](https://github.com/sindresorhus/pify) - Promisify a callback-style function +- [p-map](https://github.com/sindresorhus/p-map) - Map over promises concurrently +- [More…](https://github.com/sindresorhus/promise-fun) + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) |