Cache for async operations
-Context of applying for async handlers
-Map for task identifiers
-The lock status. -If true, then all new tasks won't be registered.
-Set of used async namespaces
-Cache for initialized workers
-Map of namespaces for async operations
-Link to Async.namespaces
Wrapper for globalThis.cancelIdleCallback
Clears the specified "requestIdleCallback" timer or a group of timers
-options for the operation
-Cancels the specified iterable object.
-Notice that cancellation affects only objects that have already been activated by invoking the next method.
-So, for example, canceled iterable will throw an error on the next invoking of next.
Cancels the specified iterable or a group of iterable.
-Notice that cancellation affects only objects that have already been activated by invoking the next method.
-So, for example, canceled iterable will throw an error on the next invoking of next.
options for the operation
-Cancels the specified promise. -The canceled promise will be automatically rejected.
-Cancels the specified promise or a group of promises. -The canceled promises will be automatically rejected.
-options for the operation
-Cancels the specified proxy function
-Cancels the specified proxy function or a group of functions
-options for the operation
-Cancels the specified request. -The canceled promise will be automatically rejected.
-Cancels the specified request or a group of requests. -The canceled promises will be automatically rejected.
-options for the operation
-Cancels a task (or a group of tasks) from the specified namespace
-operation options or task link
-Clears all async tasks
-Removes the specified event listener
-Removes the specified event listener or a group of listeners. -Notice, you can't remove event listeners by a label without providing a group.
-options for the operation
-Wrapper for globalThis.cancelIdleCallback
Clears the specified "requestIdleCallback" timer or a group of timers
-options for the operation
-Wrapper for globalThis.clearImmediate
Clears the specified "setImmediate" timer or a group of timers
-options for the operation
-Wrapper for globalThis.clearInterval
Clears the specified "setInterval" timer or a group of timers
-options for the operation
-Cancels the specified iterable object.
-Notice that cancellation affects only objects that have already been activated by invoking the next method.
-So, for example, canceled iterable will throw an error on the next invoking of next.
Cancels the specified iterable object.
-Notice that cancellation affects only objects that have already been activated by invoking the next method.
-So, for example, canceled iterable will throw an error on the next invoking of next.
options for the operation
-Cancels the specified promise. -The canceled promise will be automatically rejected.
-Cancels the specified promise or a group of promises. -The canceled promises will be automatically rejected.
-options for the operation
-Cancels the specified proxy function
-Cancels the specified proxy function or a group of functions
-options for the operation
-Cancels the specified request. -The canceled promise will be automatically rejected.
-Cancels the specified request or a group of requests. -The canceled promises will be automatically rejected.
-options for the operation
-Wrapper for globalThis.clearTimeout
Clears the specified "setTimeout" timer or a group of timers
-options for the operation
-Terminates the specified worker
-Terminates the specified worker or a group of workers
-options for the operation
-Returns a new function that allows invoking the passed function only with the specified delay. -The next invocation of the function will cancel the previous.
-Removes the passed event listener from the specified emitter
-event object
-Returns an iterator from the passed iterable object. -Notice, an asynchronous iterator has more priority.
-Returns a cache object by the specified name
-Returns a promise that will be resolved on the process idle
-Creates a new asynchronous iterable object from the specified iterable and returns it.
-If the passed iterable doesn't have Symbol.asyncIterator, it will be created from a synchronous object iterator
-(the synchronous iterator will also be preserved).
Notice, until the created promise object isn't executed by invoking the next method,
-any async operations won't be registered.
Marks all async tasks from the namespace by the specified label
-operation options
-Marks an event task with the specified label
-Marks an event task or group of tasks with the specified label
-additional options
-Marks a promise with the specified label
-Marks a promise or group of promises with the specified label
-additional options
-Marks a task (or a group of tasks) from the namespace by the specified label
-operation options or a link to the task
-Mutes all async tasks
-Mutes the specified event listener
-Mutes the specified event listener or a group of listeners. -Notice, you can't mute event listeners by a label without providing a group.
-options for the operation
-Mutes the specified "requestIdleCallback" timer
-Mutes the specified "requestIdleCallback" timer or a group of timers
-options for the operation
-Mutes the specified "setImmediate" timer
-Mutes the specified "setImmediate" timer or a group of timers
-options for the operation
-Mutes the specified "setInterval" timer
-Mutes the specified "setInterval" timer or a group of timers
-options for the operation
-Mutes the specified iterable object.
-Elements that are consumed during the object is muted will be ignored.
-Notice that muting affects only objects that have already been activated by invoking the next method.
Mutes the specified iterable object or a group of iterable objects.
-Elements, that are consumed during the object is muted will be ignored.
-Notice that muting affects only objects that have already been activated by invoking the next method.
options for the operation
-Mutes the specified promise. -If the promise is resolved during it muted, the promise wrapper will be rejected.
-Mutes the specified promise or a group of promises. -If the promises are resolved during muted, the promise wrappers will be rejected.
-options for the operation
-Mutes the specified proxy function
-Mutes the specified proxy function or a group of functions
-options for the operation
-Mutes the specified request. -If the request is resolved during it muted, the promise wrapper will be rejected.
-Mutes the specified request or a group of requests. -If the requests are resolved during muted, the promise wrappers will be rejected.
-options for the operation
-Mutes the specified "setTimeout" timer
-Mutes the specified "setTimeout" timer or a group of timers
-options for the operation
-Returns a promise that will be resolved on the next tick of the event loop
-Removes the specified event listener
-Removes the specified event listener or a group of listeners. -Notice, you can't remove event listeners by a label without providing a group.
-options for the operation
-Attaches an event listener from the specified event emitter. -If the emitter is a function, it is interpreted as the function to attach events. -Notice, if you don't provide a group for the operation, it will be taken from the event name.
-event emitter
-event or list of events (can also specify multiple events by using spaces)
-event handler
-Attaches an event listener from the specified event emitter. -If the emitter is a function, it is interpreted as the function to attach events. -Notice, if you don't provide a group for the operation, it will be taken from the event name.
-event emitter
-event or list of events (can also specify multiple events by using spaces)
-event handler
-options for the operation
-Factory to create promise clear handlers
-Factory to create promise merge handlers
-Attaches an event listener from the specified event emitter, but the event is listened only once. -If the emitter is a function, it is interpreted as the function to attach events. -Notice, if you don't provide a group for the operation, it will be taken from the event name.
-event emitter
-event or list of events (can also specify multiple events by using spaces)
-event handler
-Attaches an event listener from the specified event emitter, but the event is listened only once. -If the emitter is a function, it is interpreted as the function to attach events. -Notice, if you don't provide a group for the operation, it will be taken from the event name.
-event emitter
-event or list of events (can also specify multiple events with a space)
-event handler
-options for the operation
-Creates a new promise that wraps the passed promise and returns it.
-This method doesn't attach any hook or listeners to the object, -but if we cancel the operation by using one of Async's methods, like, "cancelPromise", -the promise will be rejected.
-The promise can be provided as it is or as a function, that returns a promise.
-Terminates the specified promise
-name of the destructor method
-Returns a promise that is resolved after emitting the specified event. -If the emitter is a function, it is interpreted as the function to attach events. -Notice, if you don't provide a group for the operation, it will be taken from the event name.
-event emitter
-event or list of events (can also specify multiple events with a space)
-options for the operation
-Returns a promise that is resolved after emitting the specified event. -If the emitter is a function, it is interpreted as the function to attach events. -Notice, if you don't provide a group for the operation, it will be taken from the event name.
-event emitter
-event or list of events (can also specify multiple events with a space)
-Creates a new function that wraps the original and returns it.
-This method doesn't attach any hook or listeners to the object,
-but if we cancel the operation by using one of Async's methods, like, cancelProxy,
-the target function won't be invoked.
Registers the specified async task
-Creates a promise that wraps the passed request and returns it.
-This method doesn't attach any hook or listeners to the object, -but if we cancel the operation by using one of Async's methods, like, "cancelRequest", -the promise will be rejected.
-The request can be provided as a promise or function, that returns a promise.
-Notice, the method uses Async.promise, but with a different namespace: request instead of promise.
Wrapper for globalThis.requestIdleCallback
callback function
-Wrapper for globalThis.setImmediate
callback function
-Wrapper for globalThis.setInterval
callback function
-timer value
-Wrapper for globalThis.setTimeout
callback function
-timeout value
-Returns a promise that will be resolved after the specified timeout
-Suspends all async tasks
-Suspends the specified event listener
-Suspends the specified event listener or a group of listeners. -Notice, you can't suspend event listeners by a label without providing a group.
-options for the operation
-Suspends the specified "requestIdleCallback" timer
-Suspends the specified "requestIdleCallback" timer or a group of timers
-options for the operation
-Suspends the specified "setImmediate" timer
-Suspends the specified "setImmediate" timer or a group of timers
-options for the operation
-Suspends the specified "setInterval" timer
-Suspends the specified "setInterval" timer or a group of timers
-options for the operation
-Suspends the specified iterable object.
-Notice that suspending affects only objects that have already been activated by invoking the next method.
Suspends the specified iterable or a group of iterable objects.
-Notice that suspending affects only objects that have already been activated by invoking the next method.
options for the operation
-Suspends the specified promise
-Suspends the specified promise or a group of promises
-options for the operation
-Suspends the specified proxy function
-Suspends the specified proxy function or a group of functions
-options for the operation
-Suspends the specified request
-Suspends the specified request or a group of requests
-options for the operation
-Suspends the specified "setTimeout" timer
-Suspends the specified "setTimeout" timer or a group of timers
-options for the operation
-Terminates the specified worker
-Terminates the specified worker or a group of workers
-options for the operation
-Returns a new function that allows invoking the passed function not more often than the specified delay
-Unmutes all async tasks
-Unmutes the specified event listener
-Unmutes the specified event listener or a group of listeners. -Notice, you can't unmute event listeners by a label without providing a group.
-options for the operation
-Unmutes the specified "requestIdleCallback" timer
-Unmutes the specified "requestIdleCallback" timer or a group of timers
-options for the operation
-Unmutes the specified "setImmediate" timer
-Unmutes the specified "setImmediate" timer or a group of timers
-options for the operation
-Unmutes the specified "setInterval" timer
-Unmutes the specified "setInterval" timer or a group of timers
-options for the operation
-Unmutes the specified iterable object
-Unmutes the specified iterable function or a group of iterable objects
-options for the operation
-Unmutes the specified promise
-Unmutes the specified promise or a group of promises
-options for the operation
-Unmutes the specified proxy function
-Unmutes the specified proxy function or a group of functions
-options for the operation
-Unmutes the specified request
-Unmutes the specified request or a group of requests
-options for the operation
-Unmutes the specified "setTimeout" timer
-Unmutes the specified "setTimeout" timer or a group of timers
-options for the operation
-Unsuspends all async tasks
-Unsuspends the specified event listener
-Unsuspends the specified event listener or a group of listeners. -Notice, you can't unsuspend event listeners by a label without providing a group.
-options for the operation
-Unsuspends the specified "requestIdleCallback" timer
-Unsuspends the specified "requestIdleCallback" timer or a group of timers
-options for the operation
-Unsuspends the specified "setImmediate" timer
-Unsuspends the specified "setImmediate" timer or a group of timers
-options for the operation
-Unsuspends the specified "setImmediate" timer
-Unsuspends the specified "setImmediate" timer or a group of timers
-options for the operation
-Unsuspends the specified iterable object
-Unsuspends the specified iterable or a group of iterable objects
-options for the operation
-Unsuspends the specified promise
-Unsuspends the specified promise or a group of promises
-options for the operation
-Unsuspends the specified proxy function
-Unsuspends the specified proxy function or a group of functions
-options for the operation
-Unsuspends the specified request
-Unsuspends the specified request or a group of requests
-options for the operation
-Unsuspends the specified "setTimeout" timer
-Unsuspends the specified "setTimeout" timer or a group of names
-options for the operation
-Returns a promise that will be resolved only when the specified function returns a positive value (== true)
-Wraps the specified worker object.
-This method doesn't attach any hook or listeners to the object,
-but every time the same object is registered, Async will increment the number of links that relate to this object.
-After, when we try to destroy the worker by using one of Async's methods, like, terminateWorker,
-it will de-increment values of links. When the number of links is equal to zero,
-Async will try to call a "real" object destructor by using one of the possible destructor methods from
-the whitelist or by the specified destructor name, also if the worker is a function,
-it is interpreted as the destructor.
Terminates the specified worker
-name of the destructor method
-The wrapper takes a link to the "raw" data provider and returns a new object that based -on the original, but all async methods and properties are wrapped by Async. -Notice, the wrapped methods can take additional Async parameters, like group or label. -If you don't provide a group, it will be taken from the provider name.
-The wrapper takes a link to the "raw" event emitter and returns a new object that based -on the original, but all async methods and properties are wrapped by Async. -Notice, the wrapped methods can take additional Async parameters, like group or label. -In addition, the wrapper adds new methods, like "on" or "off", to make the emitter API more standard.
-The wrapper takes a link to the "raw" async storage and returns a new object that based -on the original, but all async methods and properties are wrapped by Async. -Notice, the wrapped methods can take additional Async parameters, like group or label.
-Cache for async operations
-Context of applying for async handlers
-Map for task identifiers
-The lock status. -If true, then all new tasks won't be registered.
-Set of used async namespaces
-Cache for initialized workers
-Map of namespaces for async operations
-Link to Async.namespaces
Cancels a task (or a group of tasks) from the specified namespace
-operation options or task link
-Clears all async tasks
-Returns a cache object by the specified name
-Marks all async tasks from the namespace by the specified label
-operation options
-Marks a task (or a group of tasks) from the namespace by the specified label
-operation options or a link to the task
-Mutes all async tasks
-Registers the specified async task
-Suspends all async tasks
-Unmutes all async tasks
-Unsuspends all async tasks
-Cache for async operations
-Context of applying for async handlers
-Map for task identifiers
-The lock status. -If true, then all new tasks won't be registered.
-Set of used async namespaces
-Cache for initialized workers
-Map of namespaces for async operations
-Link to Async.namespaces
Wrapper for globalThis.cancelIdleCallback
Clears the specified "requestIdleCallback" timer or a group of timers
-options for the operation
-Cancels the specified iterable object.
-Notice that cancellation affects only objects that have already been activated by invoking the next method.
-So, for example, canceled iterable will throw an error on the next invoking of next.
Cancels the specified iterable or a group of iterable.
-Notice that cancellation affects only objects that have already been activated by invoking the next method.
-So, for example, canceled iterable will throw an error on the next invoking of next.
options for the operation
-Cancels the specified promise. -The canceled promise will be automatically rejected.
-Cancels the specified promise or a group of promises. -The canceled promises will be automatically rejected.
-options for the operation
-Cancels the specified proxy function
-Cancels the specified proxy function or a group of functions
-options for the operation
-Cancels the specified request. -The canceled promise will be automatically rejected.
-Cancels the specified request or a group of requests. -The canceled promises will be automatically rejected.
-options for the operation
-Cancels a task (or a group of tasks) from the specified namespace
-operation options or task link
-Clears all async tasks
-Removes the specified event listener
-Removes the specified event listener or a group of listeners. -Notice, you can't remove event listeners by a label without providing a group.
-options for the operation
-Wrapper for globalThis.cancelIdleCallback
Clears the specified "requestIdleCallback" timer or a group of timers
-options for the operation
-Wrapper for globalThis.clearImmediate
Clears the specified "setImmediate" timer or a group of timers
-options for the operation
-Wrapper for globalThis.clearInterval
Clears the specified "setInterval" timer or a group of timers
-options for the operation
-Cancels the specified iterable object.
-Notice that cancellation affects only objects that have already been activated by invoking the next method.
-So, for example, canceled iterable will throw an error on the next invoking of next.
Cancels the specified iterable object.
-Notice that cancellation affects only objects that have already been activated by invoking the next method.
-So, for example, canceled iterable will throw an error on the next invoking of next.
options for the operation
-Cancels the specified promise. -The canceled promise will be automatically rejected.
-Cancels the specified promise or a group of promises. -The canceled promises will be automatically rejected.
-options for the operation
-Cancels the specified proxy function
-Cancels the specified proxy function or a group of functions
-options for the operation
-Cancels the specified request. -The canceled promise will be automatically rejected.
-Cancels the specified request or a group of requests. -The canceled promises will be automatically rejected.
-options for the operation
-Wrapper for globalThis.clearTimeout
Clears the specified "setTimeout" timer or a group of timers
-options for the operation
-Terminates the specified worker
-Terminates the specified worker or a group of workers
-options for the operation
-Returns a new function that allows invoking the passed function only with the specified delay. -The next invocation of the function will cancel the previous.
-Removes the passed event listener from the specified emitter
-event object
-Returns an iterator from the passed iterable object. -Notice, an asynchronous iterator has more priority.
-Returns a cache object by the specified name
-Returns a promise that will be resolved on the process idle
-Creates a new asynchronous iterable object from the specified iterable and returns it.
-If the passed iterable doesn't have Symbol.asyncIterator, it will be created from a synchronous object iterator
-(the synchronous iterator will also be preserved).
Notice, until the created promise object isn't executed by invoking the next method,
-any async operations won't be registered.
Marks all async tasks from the namespace by the specified label
-operation options
-Marks an event task with the specified label
-Marks an event task or group of tasks with the specified label
-additional options
-Marks a promise with the specified label
-Marks a promise or group of promises with the specified label
-additional options
-Marks a task (or a group of tasks) from the namespace by the specified label
-operation options or a link to the task
-Mutes all async tasks
-Mutes the specified event listener
-Mutes the specified event listener or a group of listeners. -Notice, you can't mute event listeners by a label without providing a group.
-options for the operation
-Mutes the specified "requestIdleCallback" timer
-Mutes the specified "requestIdleCallback" timer or a group of timers
-options for the operation
-Mutes the specified "setImmediate" timer
-Mutes the specified "setImmediate" timer or a group of timers
-options for the operation
-Mutes the specified "setInterval" timer
-Mutes the specified "setInterval" timer or a group of timers
-options for the operation
-Mutes the specified iterable object.
-Elements that are consumed during the object is muted will be ignored.
-Notice that muting affects only objects that have already been activated by invoking the next method.
Mutes the specified iterable object or a group of iterable objects.
-Elements, that are consumed during the object is muted will be ignored.
-Notice that muting affects only objects that have already been activated by invoking the next method.
options for the operation
-Mutes the specified promise. -If the promise is resolved during it muted, the promise wrapper will be rejected.
-Mutes the specified promise or a group of promises. -If the promises are resolved during muted, the promise wrappers will be rejected.
-options for the operation
-Mutes the specified proxy function
-Mutes the specified proxy function or a group of functions
-options for the operation
-Mutes the specified request. -If the request is resolved during it muted, the promise wrapper will be rejected.
-Mutes the specified request or a group of requests. -If the requests are resolved during muted, the promise wrappers will be rejected.
-options for the operation
-Mutes the specified "setTimeout" timer
-Mutes the specified "setTimeout" timer or a group of timers
-options for the operation
-Returns a promise that will be resolved on the next tick of the event loop
-Removes the specified event listener
-Removes the specified event listener or a group of listeners. -Notice, you can't remove event listeners by a label without providing a group.
-options for the operation
-Attaches an event listener from the specified event emitter. -If the emitter is a function, it is interpreted as the function to attach events. -Notice, if you don't provide a group for the operation, it will be taken from the event name.
-event emitter
-event or list of events (can also specify multiple events by using spaces)
-event handler
-Attaches an event listener from the specified event emitter. -If the emitter is a function, it is interpreted as the function to attach events. -Notice, if you don't provide a group for the operation, it will be taken from the event name.
-event emitter
-event or list of events (can also specify multiple events by using spaces)
-event handler
-options for the operation
-Factory to create promise clear handlers
-Factory to create promise merge handlers
-Attaches an event listener from the specified event emitter, but the event is listened only once. -If the emitter is a function, it is interpreted as the function to attach events. -Notice, if you don't provide a group for the operation, it will be taken from the event name.
-event emitter
-event or list of events (can also specify multiple events by using spaces)
-event handler
-Attaches an event listener from the specified event emitter, but the event is listened only once. -If the emitter is a function, it is interpreted as the function to attach events. -Notice, if you don't provide a group for the operation, it will be taken from the event name.
-event emitter
-event or list of events (can also specify multiple events with a space)
-event handler
-options for the operation
-Creates a new promise that wraps the passed promise and returns it.
-This method doesn't attach any hook or listeners to the object, -but if we cancel the operation by using one of Async's methods, like, "cancelPromise", -the promise will be rejected.
-The promise can be provided as it is or as a function, that returns a promise.
-Terminates the specified promise
-name of the destructor method
-Returns a promise that is resolved after emitting the specified event. -If the emitter is a function, it is interpreted as the function to attach events. -Notice, if you don't provide a group for the operation, it will be taken from the event name.
-event emitter
-event or list of events (can also specify multiple events with a space)
-options for the operation
-Returns a promise that is resolved after emitting the specified event. -If the emitter is a function, it is interpreted as the function to attach events. -Notice, if you don't provide a group for the operation, it will be taken from the event name.
-event emitter
-event or list of events (can also specify multiple events with a space)
-Creates a new function that wraps the original and returns it.
-This method doesn't attach any hook or listeners to the object,
-but if we cancel the operation by using one of Async's methods, like, cancelProxy,
-the target function won't be invoked.
Registers the specified async task
-Creates a promise that wraps the passed request and returns it.
-This method doesn't attach any hook or listeners to the object, -but if we cancel the operation by using one of Async's methods, like, "cancelRequest", -the promise will be rejected.
-The request can be provided as a promise or function, that returns a promise.
-Notice, the method uses Async.promise, but with a different namespace: request instead of promise.
Wrapper for globalThis.requestIdleCallback
callback function
-Wrapper for globalThis.setImmediate
callback function
-Wrapper for globalThis.setInterval
callback function
-timer value
-Wrapper for globalThis.setTimeout
callback function
-timeout value
-Returns a promise that will be resolved after the specified timeout
-Suspends all async tasks
-Suspends the specified event listener
-Suspends the specified event listener or a group of listeners. -Notice, you can't suspend event listeners by a label without providing a group.
-options for the operation
-Suspends the specified "requestIdleCallback" timer
-Suspends the specified "requestIdleCallback" timer or a group of timers
-options for the operation
-Suspends the specified "setImmediate" timer
-Suspends the specified "setImmediate" timer or a group of timers
-options for the operation
-Suspends the specified "setInterval" timer
-Suspends the specified "setInterval" timer or a group of timers
-options for the operation
-Suspends the specified iterable object.
-Notice that suspending affects only objects that have already been activated by invoking the next method.
Suspends the specified iterable or a group of iterable objects.
-Notice that suspending affects only objects that have already been activated by invoking the next method.
options for the operation
-Suspends the specified promise
-Suspends the specified promise or a group of promises
-options for the operation
-Suspends the specified proxy function
-Suspends the specified proxy function or a group of functions
-options for the operation
-Suspends the specified request
-Suspends the specified request or a group of requests
-options for the operation
-Suspends the specified "setTimeout" timer
-Suspends the specified "setTimeout" timer or a group of timers
-options for the operation
-Terminates the specified worker
-Terminates the specified worker or a group of workers
-options for the operation
-Returns a new function that allows invoking the passed function not more often than the specified delay
-Unmutes all async tasks
-Unmutes the specified event listener
-Unmutes the specified event listener or a group of listeners. -Notice, you can't unmute event listeners by a label without providing a group.
-options for the operation
-Unmutes the specified "requestIdleCallback" timer
-Unmutes the specified "requestIdleCallback" timer or a group of timers
-options for the operation
-Unmutes the specified "setImmediate" timer
-Unmutes the specified "setImmediate" timer or a group of timers
-options for the operation
-Unmutes the specified "setInterval" timer
-Unmutes the specified "setInterval" timer or a group of timers
-options for the operation
-Unmutes the specified iterable object
-Unmutes the specified iterable function or a group of iterable objects
-options for the operation
-Unmutes the specified promise
-Unmutes the specified promise or a group of promises
-options for the operation
-Unmutes the specified proxy function
-Unmutes the specified proxy function or a group of functions
-options for the operation
-Unmutes the specified request
-Unmutes the specified request or a group of requests
-options for the operation
-Unmutes the specified "setTimeout" timer
-Unmutes the specified "setTimeout" timer or a group of timers
-options for the operation
-Unsuspends all async tasks
-Unsuspends the specified event listener
-Unsuspends the specified event listener or a group of listeners. -Notice, you can't unsuspend event listeners by a label without providing a group.
-options for the operation
-Unsuspends the specified "requestIdleCallback" timer
-Unsuspends the specified "requestIdleCallback" timer or a group of timers
-options for the operation
-Unsuspends the specified "setImmediate" timer
-Unsuspends the specified "setImmediate" timer or a group of timers
-options for the operation
-Unsuspends the specified "setImmediate" timer
-Unsuspends the specified "setImmediate" timer or a group of timers
-options for the operation
-Unsuspends the specified iterable object
-Unsuspends the specified iterable or a group of iterable objects
-options for the operation
-Unsuspends the specified promise
-Unsuspends the specified promise or a group of promises
-options for the operation
-Unsuspends the specified proxy function
-Unsuspends the specified proxy function or a group of functions
-options for the operation
-Unsuspends the specified request
-Unsuspends the specified request or a group of requests
-options for the operation
-Unsuspends the specified "setTimeout" timer
-Unsuspends the specified "setTimeout" timer or a group of names
-options for the operation
-Returns a promise that will be resolved only when the specified function returns a positive value (== true)
-Wraps the specified worker object.
-This method doesn't attach any hook or listeners to the object,
-but every time the same object is registered, Async will increment the number of links that relate to this object.
-After, when we try to destroy the worker by using one of Async's methods, like, terminateWorker,
-it will de-increment values of links. When the number of links is equal to zero,
-Async will try to call a "real" object destructor by using one of the possible destructor methods from
-the whitelist or by the specified destructor name, also if the worker is a function,
-it is interpreted as the destructor.
Terminates the specified worker
-name of the destructor method
-Cache for async operations
-Context of applying for async handlers
-Map for task identifiers
-The lock status. -If true, then all new tasks won't be registered.
-Set of used async namespaces
-Cache for initialized workers
-Map of namespaces for async operations
-Link to Async.namespaces
Cancels the specified iterable object.
-Notice that cancellation affects only objects that have already been activated by invoking the next method.
-So, for example, canceled iterable will throw an error on the next invoking of next.
Cancels the specified iterable or a group of iterable.
-Notice that cancellation affects only objects that have already been activated by invoking the next method.
-So, for example, canceled iterable will throw an error on the next invoking of next.
options for the operation
-Cancels the specified promise. -The canceled promise will be automatically rejected.
-Cancels the specified promise or a group of promises. -The canceled promises will be automatically rejected.
-options for the operation
-Cancels the specified proxy function
-Cancels the specified proxy function or a group of functions
-options for the operation
-Cancels the specified request. -The canceled promise will be automatically rejected.
-Cancels the specified request or a group of requests. -The canceled promises will be automatically rejected.
-options for the operation
-Cancels a task (or a group of tasks) from the specified namespace
-operation options or task link
-Clears all async tasks
-Cancels the specified iterable object.
-Notice that cancellation affects only objects that have already been activated by invoking the next method.
-So, for example, canceled iterable will throw an error on the next invoking of next.
Cancels the specified iterable object.
-Notice that cancellation affects only objects that have already been activated by invoking the next method.
-So, for example, canceled iterable will throw an error on the next invoking of next.
options for the operation
-Cancels the specified promise. -The canceled promise will be automatically rejected.
-Cancels the specified promise or a group of promises. -The canceled promises will be automatically rejected.
-options for the operation
-Cancels the specified proxy function
-Cancels the specified proxy function or a group of functions
-options for the operation
-Cancels the specified request. -The canceled promise will be automatically rejected.
-Cancels the specified request or a group of requests. -The canceled promises will be automatically rejected.
-options for the operation
-Terminates the specified worker
-Terminates the specified worker or a group of workers
-options for the operation
-Returns a new function that allows invoking the passed function only with the specified delay. -The next invocation of the function will cancel the previous.
-Returns an iterator from the passed iterable object. -Notice, an asynchronous iterator has more priority.
-Returns a cache object by the specified name
-Creates a new asynchronous iterable object from the specified iterable and returns it.
-If the passed iterable doesn't have Symbol.asyncIterator, it will be created from a synchronous object iterator
-(the synchronous iterator will also be preserved).
Notice, until the created promise object isn't executed by invoking the next method,
-any async operations won't be registered.
Marks all async tasks from the namespace by the specified label
-operation options
-Marks a promise with the specified label
-Marks a promise or group of promises with the specified label
-additional options
-Marks a task (or a group of tasks) from the namespace by the specified label
-operation options or a link to the task
-Mutes all async tasks
-Mutes the specified iterable object.
-Elements that are consumed during the object is muted will be ignored.
-Notice that muting affects only objects that have already been activated by invoking the next method.
Mutes the specified iterable object or a group of iterable objects.
-Elements, that are consumed during the object is muted will be ignored.
-Notice that muting affects only objects that have already been activated by invoking the next method.
options for the operation
-Mutes the specified promise. -If the promise is resolved during it muted, the promise wrapper will be rejected.
-Mutes the specified promise or a group of promises. -If the promises are resolved during muted, the promise wrappers will be rejected.
-options for the operation
-Mutes the specified proxy function
-Mutes the specified proxy function or a group of functions
-options for the operation
-Mutes the specified request. -If the request is resolved during it muted, the promise wrapper will be rejected.
-Mutes the specified request or a group of requests. -If the requests are resolved during muted, the promise wrappers will be rejected.
-options for the operation
-Factory to create promise clear handlers
-Factory to create promise merge handlers
-Creates a new promise that wraps the passed promise and returns it.
-This method doesn't attach any hook or listeners to the object, -but if we cancel the operation by using one of Async's methods, like, "cancelPromise", -the promise will be rejected.
-The promise can be provided as it is or as a function, that returns a promise.
-Terminates the specified promise
-name of the destructor method
-Creates a new function that wraps the original and returns it.
-This method doesn't attach any hook or listeners to the object,
-but if we cancel the operation by using one of Async's methods, like, cancelProxy,
-the target function won't be invoked.
Registers the specified async task
-Creates a promise that wraps the passed request and returns it.
-This method doesn't attach any hook or listeners to the object, -but if we cancel the operation by using one of Async's methods, like, "cancelRequest", -the promise will be rejected.
-The request can be provided as a promise or function, that returns a promise.
-Notice, the method uses Async.promise, but with a different namespace: request instead of promise.
Suspends all async tasks
-Suspends the specified iterable object.
-Notice that suspending affects only objects that have already been activated by invoking the next method.
Suspends the specified iterable or a group of iterable objects.
-Notice that suspending affects only objects that have already been activated by invoking the next method.
options for the operation
-Suspends the specified promise
-Suspends the specified promise or a group of promises
-options for the operation
-Suspends the specified proxy function
-Suspends the specified proxy function or a group of functions
-options for the operation
-Suspends the specified request
-Suspends the specified request or a group of requests
-options for the operation
-Terminates the specified worker
-Terminates the specified worker or a group of workers
-options for the operation
-Returns a new function that allows invoking the passed function not more often than the specified delay
-Unmutes all async tasks
-Unmutes the specified iterable object
-Unmutes the specified iterable function or a group of iterable objects
-options for the operation
-Unmutes the specified promise
-Unmutes the specified promise or a group of promises
-options for the operation
-Unmutes the specified proxy function
-Unmutes the specified proxy function or a group of functions
-options for the operation
-Unmutes the specified request
-Unmutes the specified request or a group of requests
-options for the operation
-Unsuspends all async tasks
-Unsuspends the specified iterable object
-Unsuspends the specified iterable or a group of iterable objects
-options for the operation
-Unsuspends the specified promise
-Unsuspends the specified promise or a group of promises
-options for the operation
-Unsuspends the specified proxy function
-Unsuspends the specified proxy function or a group of functions
-options for the operation
-Unsuspends the specified request
-Unsuspends the specified request or a group of requests
-options for the operation
-Wraps the specified worker object.
-This method doesn't attach any hook or listeners to the object,
-but every time the same object is registered, Async will increment the number of links that relate to this object.
-After, when we try to destroy the worker by using one of Async's methods, like, terminateWorker,
-it will de-increment values of links. When the number of links is equal to zero,
-Async will try to call a "real" object destructor by using one of the possible destructor methods from
-the whitelist or by the specified destructor name, also if the worker is a function,
-it is interpreted as the destructor.
Terminates the specified worker
-name of the destructor method
-Cache for async operations
-Context of applying for async handlers
-Map for task identifiers
-The lock status. -If true, then all new tasks won't be registered.
-Set of used async namespaces
-Cache for initialized workers
-Map of namespaces for async operations
-Link to Async.namespaces
Wrapper for globalThis.cancelIdleCallback
Clears the specified "requestIdleCallback" timer or a group of timers
-options for the operation
-Cancels the specified iterable object.
-Notice that cancellation affects only objects that have already been activated by invoking the next method.
-So, for example, canceled iterable will throw an error on the next invoking of next.
Cancels the specified iterable or a group of iterable.
-Notice that cancellation affects only objects that have already been activated by invoking the next method.
-So, for example, canceled iterable will throw an error on the next invoking of next.
options for the operation
-Cancels the specified promise. -The canceled promise will be automatically rejected.
-Cancels the specified promise or a group of promises. -The canceled promises will be automatically rejected.
-options for the operation
-Cancels the specified proxy function
-Cancels the specified proxy function or a group of functions
-options for the operation
-Cancels the specified request. -The canceled promise will be automatically rejected.
-Cancels the specified request or a group of requests. -The canceled promises will be automatically rejected.
-options for the operation
-Cancels a task (or a group of tasks) from the specified namespace
-operation options or task link
-Clears all async tasks
-Wrapper for globalThis.cancelIdleCallback
Clears the specified "requestIdleCallback" timer or a group of timers
-options for the operation
-Wrapper for globalThis.clearImmediate
Clears the specified "setImmediate" timer or a group of timers
-options for the operation
-Wrapper for globalThis.clearInterval
Clears the specified "setInterval" timer or a group of timers
-options for the operation
-Cancels the specified iterable object.
-Notice that cancellation affects only objects that have already been activated by invoking the next method.
-So, for example, canceled iterable will throw an error on the next invoking of next.
Cancels the specified iterable object.
-Notice that cancellation affects only objects that have already been activated by invoking the next method.
-So, for example, canceled iterable will throw an error on the next invoking of next.
options for the operation
-Cancels the specified promise. -The canceled promise will be automatically rejected.
-Cancels the specified promise or a group of promises. -The canceled promises will be automatically rejected.
-options for the operation
-Cancels the specified proxy function
-Cancels the specified proxy function or a group of functions
-options for the operation
-Cancels the specified request. -The canceled promise will be automatically rejected.
-Cancels the specified request or a group of requests. -The canceled promises will be automatically rejected.
-options for the operation
-Wrapper for globalThis.clearTimeout
Clears the specified "setTimeout" timer or a group of timers
-options for the operation
-Terminates the specified worker
-Terminates the specified worker or a group of workers
-options for the operation
-Returns a new function that allows invoking the passed function only with the specified delay. -The next invocation of the function will cancel the previous.
-Returns an iterator from the passed iterable object. -Notice, an asynchronous iterator has more priority.
-Returns a cache object by the specified name
-Returns a promise that will be resolved on the process idle
-Creates a new asynchronous iterable object from the specified iterable and returns it.
-If the passed iterable doesn't have Symbol.asyncIterator, it will be created from a synchronous object iterator
-(the synchronous iterator will also be preserved).
Notice, until the created promise object isn't executed by invoking the next method,
-any async operations won't be registered.
Marks all async tasks from the namespace by the specified label
-operation options
-Marks a promise with the specified label
-Marks a promise or group of promises with the specified label
-additional options
-Marks a task (or a group of tasks) from the namespace by the specified label
-operation options or a link to the task
-Mutes all async tasks
-Mutes the specified "requestIdleCallback" timer
-Mutes the specified "requestIdleCallback" timer or a group of timers
-options for the operation
-Mutes the specified "setImmediate" timer
-Mutes the specified "setImmediate" timer or a group of timers
-options for the operation
-Mutes the specified "setInterval" timer
-Mutes the specified "setInterval" timer or a group of timers
-options for the operation
-Mutes the specified iterable object.
-Elements that are consumed during the object is muted will be ignored.
-Notice that muting affects only objects that have already been activated by invoking the next method.
Mutes the specified iterable object or a group of iterable objects.
-Elements, that are consumed during the object is muted will be ignored.
-Notice that muting affects only objects that have already been activated by invoking the next method.
options for the operation
-Mutes the specified promise. -If the promise is resolved during it muted, the promise wrapper will be rejected.
-Mutes the specified promise or a group of promises. -If the promises are resolved during muted, the promise wrappers will be rejected.
-options for the operation
-Mutes the specified proxy function
-Mutes the specified proxy function or a group of functions
-options for the operation
-Mutes the specified request. -If the request is resolved during it muted, the promise wrapper will be rejected.
-Mutes the specified request or a group of requests. -If the requests are resolved during muted, the promise wrappers will be rejected.
-options for the operation
-Mutes the specified "setTimeout" timer
-Mutes the specified "setTimeout" timer or a group of timers
-options for the operation
-Returns a promise that will be resolved on the next tick of the event loop
-Factory to create promise clear handlers
-Factory to create promise merge handlers
-Creates a new promise that wraps the passed promise and returns it.
-This method doesn't attach any hook or listeners to the object, -but if we cancel the operation by using one of Async's methods, like, "cancelPromise", -the promise will be rejected.
-The promise can be provided as it is or as a function, that returns a promise.
-Terminates the specified promise
-name of the destructor method
-Creates a new function that wraps the original and returns it.
-This method doesn't attach any hook or listeners to the object,
-but if we cancel the operation by using one of Async's methods, like, cancelProxy,
-the target function won't be invoked.
Registers the specified async task
-Creates a promise that wraps the passed request and returns it.
-This method doesn't attach any hook or listeners to the object, -but if we cancel the operation by using one of Async's methods, like, "cancelRequest", -the promise will be rejected.
-The request can be provided as a promise or function, that returns a promise.
-Notice, the method uses Async.promise, but with a different namespace: request instead of promise.
Wrapper for globalThis.requestIdleCallback
callback function
-Wrapper for globalThis.setImmediate
callback function
-Wrapper for globalThis.setInterval
callback function
-timer value
-Wrapper for globalThis.setTimeout
callback function
-timeout value
-Returns a promise that will be resolved after the specified timeout
-Suspends all async tasks
-Suspends the specified "requestIdleCallback" timer
-Suspends the specified "requestIdleCallback" timer or a group of timers
-options for the operation
-Suspends the specified "setImmediate" timer
-Suspends the specified "setImmediate" timer or a group of timers
-options for the operation
-Suspends the specified "setInterval" timer
-Suspends the specified "setInterval" timer or a group of timers
-options for the operation
-Suspends the specified iterable object.
-Notice that suspending affects only objects that have already been activated by invoking the next method.
Suspends the specified iterable or a group of iterable objects.
-Notice that suspending affects only objects that have already been activated by invoking the next method.
options for the operation
-Suspends the specified promise
-Suspends the specified promise or a group of promises
-options for the operation
-Suspends the specified proxy function
-Suspends the specified proxy function or a group of functions
-options for the operation
-Suspends the specified request
-Suspends the specified request or a group of requests
-options for the operation
-Suspends the specified "setTimeout" timer
-Suspends the specified "setTimeout" timer or a group of timers
-options for the operation
-Terminates the specified worker
-Terminates the specified worker or a group of workers
-options for the operation
-Returns a new function that allows invoking the passed function not more often than the specified delay
-Unmutes all async tasks
-Unmutes the specified "requestIdleCallback" timer
-Unmutes the specified "requestIdleCallback" timer or a group of timers
-options for the operation
-Unmutes the specified "setImmediate" timer
-Unmutes the specified "setImmediate" timer or a group of timers
-options for the operation
-Unmutes the specified "setInterval" timer
-Unmutes the specified "setInterval" timer or a group of timers
-options for the operation
-Unmutes the specified iterable object
-Unmutes the specified iterable function or a group of iterable objects
-options for the operation
-Unmutes the specified promise
-Unmutes the specified promise or a group of promises
-options for the operation
-Unmutes the specified proxy function
-Unmutes the specified proxy function or a group of functions
-options for the operation
-Unmutes the specified request
-Unmutes the specified request or a group of requests
-options for the operation
-Unmutes the specified "setTimeout" timer
-Unmutes the specified "setTimeout" timer or a group of timers
-options for the operation
-Unsuspends all async tasks
-Unsuspends the specified "requestIdleCallback" timer
-Unsuspends the specified "requestIdleCallback" timer or a group of timers
-options for the operation
-Unsuspends the specified "setImmediate" timer
-Unsuspends the specified "setImmediate" timer or a group of timers
-options for the operation
-Unsuspends the specified "setImmediate" timer
-Unsuspends the specified "setImmediate" timer or a group of timers
-options for the operation
-Unsuspends the specified iterable object
-Unsuspends the specified iterable or a group of iterable objects
-options for the operation
-Unsuspends the specified promise
-Unsuspends the specified promise or a group of promises
-options for the operation
-Unsuspends the specified proxy function
-Unsuspends the specified proxy function or a group of functions
-options for the operation
-Unsuspends the specified request
-Unsuspends the specified request or a group of requests
-options for the operation
-Unsuspends the specified "setTimeout" timer
-Unsuspends the specified "setTimeout" timer or a group of names
-options for the operation
-Returns a promise that will be resolved only when the specified function returns a positive value (== true)
-Wraps the specified worker object.
-This method doesn't attach any hook or listeners to the object,
-but every time the same object is registered, Async will increment the number of links that relate to this object.
-After, when we try to destroy the worker by using one of Async's methods, like, terminateWorker,
-it will de-increment values of links. When the number of links is equal to zero,
-Async will try to call a "real" object destructor by using one of the possible destructor methods from
-the whitelist or by the specified destructor name, also if the worker is a function,
-it is interpreted as the destructor.
Terminates the specified worker
-name of the destructor method
-Cache for async operations
-Context of applying for async handlers
-Map for task identifiers
-The lock status. -If true, then all new tasks won't be registered.
-Set of used async namespaces
-Cache for initialized workers
-Map of namespaces for async operations
-Link to Async.namespaces
Wrapper for globalThis.cancelIdleCallback
Clears the specified "requestIdleCallback" timer or a group of timers
-options for the operation
-Cancels the specified iterable object.
-Notice that cancellation affects only objects that have already been activated by invoking the next method.
-So, for example, canceled iterable will throw an error on the next invoking of next.
Cancels the specified iterable or a group of iterable.
-Notice that cancellation affects only objects that have already been activated by invoking the next method.
-So, for example, canceled iterable will throw an error on the next invoking of next.
options for the operation
-Cancels the specified promise. -The canceled promise will be automatically rejected.
-Cancels the specified promise or a group of promises. -The canceled promises will be automatically rejected.
-options for the operation
-Cancels the specified proxy function
-Cancels the specified proxy function or a group of functions
-options for the operation
-Cancels the specified request. -The canceled promise will be automatically rejected.
-Cancels the specified request or a group of requests. -The canceled promises will be automatically rejected.
-options for the operation
-Cancels a task (or a group of tasks) from the specified namespace
-operation options or task link
-Clears all async tasks
-Removes the specified event listener
-Removes the specified event listener or a group of listeners. -Notice, you can't remove event listeners by a label without providing a group.
-options for the operation
-Wrapper for globalThis.cancelIdleCallback
Clears the specified "requestIdleCallback" timer or a group of timers
-options for the operation
-Wrapper for globalThis.clearImmediate
Clears the specified "setImmediate" timer or a group of timers
-options for the operation
-Wrapper for globalThis.clearInterval
Clears the specified "setInterval" timer or a group of timers
-options for the operation
-Cancels the specified iterable object.
-Notice that cancellation affects only objects that have already been activated by invoking the next method.
-So, for example, canceled iterable will throw an error on the next invoking of next.
Cancels the specified iterable object.
-Notice that cancellation affects only objects that have already been activated by invoking the next method.
-So, for example, canceled iterable will throw an error on the next invoking of next.
options for the operation
-Cancels the specified promise. -The canceled promise will be automatically rejected.
-Cancels the specified promise or a group of promises. -The canceled promises will be automatically rejected.
-options for the operation
-Cancels the specified proxy function
-Cancels the specified proxy function or a group of functions
-options for the operation
-Cancels the specified request. -The canceled promise will be automatically rejected.
-Cancels the specified request or a group of requests. -The canceled promises will be automatically rejected.
-options for the operation
-Wrapper for globalThis.clearTimeout
Clears the specified "setTimeout" timer or a group of timers
-options for the operation
-Terminates the specified worker
-Terminates the specified worker or a group of workers
-options for the operation
-Returns a new function that allows invoking the passed function only with the specified delay. -The next invocation of the function will cancel the previous.
-Removes the passed event listener from the specified emitter
-event object
-Returns an iterator from the passed iterable object. -Notice, an asynchronous iterator has more priority.
-Returns a cache object by the specified name
-Returns a promise that will be resolved on the process idle
-Creates a new asynchronous iterable object from the specified iterable and returns it.
-If the passed iterable doesn't have Symbol.asyncIterator, it will be created from a synchronous object iterator
-(the synchronous iterator will also be preserved).
Notice, until the created promise object isn't executed by invoking the next method,
-any async operations won't be registered.
Marks all async tasks from the namespace by the specified label
-operation options
-Marks an event task with the specified label
-Marks an event task or group of tasks with the specified label
-additional options
-Marks a promise with the specified label
-Marks a promise or group of promises with the specified label
-additional options
-Marks a task (or a group of tasks) from the namespace by the specified label
-operation options or a link to the task
-Mutes all async tasks
-Mutes the specified event listener
-Mutes the specified event listener or a group of listeners. -Notice, you can't mute event listeners by a label without providing a group.
-options for the operation
-Mutes the specified "requestIdleCallback" timer
-Mutes the specified "requestIdleCallback" timer or a group of timers
-options for the operation
-Mutes the specified "setImmediate" timer
-Mutes the specified "setImmediate" timer or a group of timers
-options for the operation
-Mutes the specified "setInterval" timer
-Mutes the specified "setInterval" timer or a group of timers
-options for the operation
-Mutes the specified iterable object.
-Elements that are consumed during the object is muted will be ignored.
-Notice that muting affects only objects that have already been activated by invoking the next method.
Mutes the specified iterable object or a group of iterable objects.
-Elements, that are consumed during the object is muted will be ignored.
-Notice that muting affects only objects that have already been activated by invoking the next method.
options for the operation
-Mutes the specified promise. -If the promise is resolved during it muted, the promise wrapper will be rejected.
-Mutes the specified promise or a group of promises. -If the promises are resolved during muted, the promise wrappers will be rejected.
-options for the operation
-Mutes the specified proxy function
-Mutes the specified proxy function or a group of functions
-options for the operation
-Mutes the specified request. -If the request is resolved during it muted, the promise wrapper will be rejected.
-Mutes the specified request or a group of requests. -If the requests are resolved during muted, the promise wrappers will be rejected.
-options for the operation
-Mutes the specified "setTimeout" timer
-Mutes the specified "setTimeout" timer or a group of timers
-options for the operation
-Returns a promise that will be resolved on the next tick of the event loop
-Removes the specified event listener
-Removes the specified event listener or a group of listeners. -Notice, you can't remove event listeners by a label without providing a group.
-options for the operation
-Attaches an event listener from the specified event emitter. -If the emitter is a function, it is interpreted as the function to attach events. -Notice, if you don't provide a group for the operation, it will be taken from the event name.
-event emitter
-event or list of events (can also specify multiple events by using spaces)
-event handler
-Attaches an event listener from the specified event emitter. -If the emitter is a function, it is interpreted as the function to attach events. -Notice, if you don't provide a group for the operation, it will be taken from the event name.
-event emitter
-event or list of events (can also specify multiple events by using spaces)
-event handler
-options for the operation
-Factory to create promise clear handlers
-Factory to create promise merge handlers
-Attaches an event listener from the specified event emitter, but the event is listened only once. -If the emitter is a function, it is interpreted as the function to attach events. -Notice, if you don't provide a group for the operation, it will be taken from the event name.
-event emitter
-event or list of events (can also specify multiple events by using spaces)
-event handler
-Attaches an event listener from the specified event emitter, but the event is listened only once. -If the emitter is a function, it is interpreted as the function to attach events. -Notice, if you don't provide a group for the operation, it will be taken from the event name.
-event emitter
-event or list of events (can also specify multiple events with a space)
-event handler
-options for the operation
-Creates a new promise that wraps the passed promise and returns it.
-This method doesn't attach any hook or listeners to the object, -but if we cancel the operation by using one of Async's methods, like, "cancelPromise", -the promise will be rejected.
-The promise can be provided as it is or as a function, that returns a promise.
-Terminates the specified promise
-name of the destructor method
-Returns a promise that is resolved after emitting the specified event. -If the emitter is a function, it is interpreted as the function to attach events. -Notice, if you don't provide a group for the operation, it will be taken from the event name.
-event emitter
-event or list of events (can also specify multiple events with a space)
-options for the operation
-Returns a promise that is resolved after emitting the specified event. -If the emitter is a function, it is interpreted as the function to attach events. -Notice, if you don't provide a group for the operation, it will be taken from the event name.
-event emitter
-event or list of events (can also specify multiple events with a space)
-Creates a new function that wraps the original and returns it.
-This method doesn't attach any hook or listeners to the object,
-but if we cancel the operation by using one of Async's methods, like, cancelProxy,
-the target function won't be invoked.
Registers the specified async task
-Creates a promise that wraps the passed request and returns it.
-This method doesn't attach any hook or listeners to the object, -but if we cancel the operation by using one of Async's methods, like, "cancelRequest", -the promise will be rejected.
-The request can be provided as a promise or function, that returns a promise.
-Notice, the method uses Async.promise, but with a different namespace: request instead of promise.
Wrapper for globalThis.requestIdleCallback
callback function
-Wrapper for globalThis.setImmediate
callback function
-Wrapper for globalThis.setInterval
callback function
-timer value
-Wrapper for globalThis.setTimeout
callback function
-timeout value
-Returns a promise that will be resolved after the specified timeout
-Suspends all async tasks
-Suspends the specified event listener
-Suspends the specified event listener or a group of listeners. -Notice, you can't suspend event listeners by a label without providing a group.
-options for the operation
-Suspends the specified "requestIdleCallback" timer
-Suspends the specified "requestIdleCallback" timer or a group of timers
-options for the operation
-Suspends the specified "setImmediate" timer
-Suspends the specified "setImmediate" timer or a group of timers
-options for the operation
-Suspends the specified "setInterval" timer
-Suspends the specified "setInterval" timer or a group of timers
-options for the operation
-Suspends the specified iterable object.
-Notice that suspending affects only objects that have already been activated by invoking the next method.
Suspends the specified iterable or a group of iterable objects.
-Notice that suspending affects only objects that have already been activated by invoking the next method.
options for the operation
-Suspends the specified promise
-Suspends the specified promise or a group of promises
-options for the operation
-Suspends the specified proxy function
-Suspends the specified proxy function or a group of functions
-options for the operation
-Suspends the specified request
-Suspends the specified request or a group of requests
-options for the operation
-Suspends the specified "setTimeout" timer
-Suspends the specified "setTimeout" timer or a group of timers
-options for the operation
-Terminates the specified worker
-Terminates the specified worker or a group of workers
-options for the operation
-Returns a new function that allows invoking the passed function not more often than the specified delay
-Unmutes all async tasks
-Unmutes the specified event listener
-Unmutes the specified event listener or a group of listeners. -Notice, you can't unmute event listeners by a label without providing a group.
-options for the operation
-Unmutes the specified "requestIdleCallback" timer
-Unmutes the specified "requestIdleCallback" timer or a group of timers
-options for the operation
-Unmutes the specified "setImmediate" timer
-Unmutes the specified "setImmediate" timer or a group of timers
-options for the operation
-Unmutes the specified "setInterval" timer
-Unmutes the specified "setInterval" timer or a group of timers
-options for the operation
-Unmutes the specified iterable object
-Unmutes the specified iterable function or a group of iterable objects
-options for the operation
-Unmutes the specified promise
-Unmutes the specified promise or a group of promises
-options for the operation
-Unmutes the specified proxy function
-Unmutes the specified proxy function or a group of functions
-options for the operation
-Unmutes the specified request
-Unmutes the specified request or a group of requests
-options for the operation
-Unmutes the specified "setTimeout" timer
-Unmutes the specified "setTimeout" timer or a group of timers
-options for the operation
-Unsuspends all async tasks
-Unsuspends the specified event listener
-Unsuspends the specified event listener or a group of listeners. -Notice, you can't unsuspend event listeners by a label without providing a group.
-options for the operation
-Unsuspends the specified "requestIdleCallback" timer
-Unsuspends the specified "requestIdleCallback" timer or a group of timers
-options for the operation
-Unsuspends the specified "setImmediate" timer
-Unsuspends the specified "setImmediate" timer or a group of timers
-options for the operation
-Unsuspends the specified "setImmediate" timer
-Unsuspends the specified "setImmediate" timer or a group of timers
-options for the operation
-Unsuspends the specified iterable object
-Unsuspends the specified iterable or a group of iterable objects
-options for the operation
-Unsuspends the specified promise
-Unsuspends the specified promise or a group of promises
-options for the operation
-Unsuspends the specified proxy function
-Unsuspends the specified proxy function or a group of functions
-options for the operation
-Unsuspends the specified request
-Unsuspends the specified request or a group of requests
-options for the operation
-Unsuspends the specified "setTimeout" timer
-Unsuspends the specified "setTimeout" timer or a group of names
-options for the operation
-Returns a promise that will be resolved only when the specified function returns a positive value (== true)
-Wraps the specified worker object.
-This method doesn't attach any hook or listeners to the object,
-but every time the same object is registered, Async will increment the number of links that relate to this object.
-After, when we try to destroy the worker by using one of Async's methods, like, terminateWorker,
-it will de-increment values of links. When the number of links is equal to zero,
-Async will try to call a "real" object destructor by using one of the possible destructor methods from
-the whitelist or by the specified destructor name, also if the worker is a function,
-it is interpreted as the destructor.
Terminates the specified worker
-name of the destructor method
-The wrapper takes a link to the "raw" data provider and returns a new object that based -on the original, but all async methods and properties are wrapped by Async. -Notice, the wrapped methods can take additional Async parameters, like group or label. -If you don't provide a group, it will be taken from the provider name.
-The wrapper takes a link to the "raw" event emitter and returns a new object that based -on the original, but all async methods and properties are wrapped by Async. -Notice, the wrapped methods can take additional Async parameters, like group or label. -In addition, the wrapper adds new methods, like "on" or "off", to make the emitter API more standard.
-The wrapper takes a link to the "raw" async storage and returns a new object that based -on the original, but all async methods and properties are wrapped by Async. -Notice, the wrapped methods can take additional Async parameters, like group or label.
-API for async operations
-Map of pending operations by keys
-API to store data
-Index with keys and TTL-s of stored values
-Registers a task to update a cache item by the specified key
-function that doing something with the storage
-Returns a value of the persistentTTL descriptor by the specified key
Initializes a new cache instance from the past one
-Normalized the given TTL value and returns it
-Removes a value from the storage by the specified key
-Removes the persistentTTL descriptor from a cache item by the specified key.
-The method returns true if the operation has been successful, otherwise false
-(the requested item hasn't been found).
Sets a value to the storage by the specified key and ttl
-API for async operations
-Map of pending operations by keys
-API to store data
-Registers a task to update a cache item by the specified key
-function that doing something with the storage
-Returns a value of the persistentTTL descriptor by the specified key
Initializes a new cache instance from the past one
-Normalized the given TTL value and returns it
-Removes a value from the storage by the specified key
-Removes the persistentTTL descriptor from a cache item by the specified key.
-The method returns true if the operation has been successful, otherwise false
-(the requested item hasn't been found).
Sets a value to the storage by the specified key and ttl
-API for async operations
-Map of pending operations by keys
-API to store data
-Registers a task to update a cache item by the specified key
-function that doing something with the storage
-Returns a value from the storage by the specified key.
-Before checking the storage, the method will ask getCheckStorageState for permissions to do it.
This method is called before every operation that checks data from the storage, like, has or get
operation method
-data key within the storage
-Returns a value of the persistentTTL descriptor by the specified key
Initializes a new cache instance from the past one
-Normalized the given TTL value and returns it
-Removes a value from the storage by the specified key
-Removes the persistentTTL descriptor from a cache item by the specified key.
-The method returns true if the operation has been successful, otherwise false
-(the requested item hasn't been found).
Sets a value to the storage by the specified key and ttl
-A subtype of a persistent engine where getCheckStorageState will always return available: false.
-It allows you not to implement the get method.
API for async operations
-Map of pending operations by keys
-API to store data
-Registers a task to update a cache item by the specified key
-function that doing something with the storage
-Returns a value of the persistentTTL descriptor by the specified key
Initializes a new cache instance from the past one
-Normalized the given TTL value and returns it
-Removes a value from the storage by the specified key
-Removes the persistentTTL descriptor from a cache item by the specified key.
-The method returns true if the operation has been successful, otherwise false
-(the requested item hasn't been found).
Sets a value to the storage by the specified key and ttl
-API for async operations
-Map of pending operations by keys
-API to store data
-Registers a task to update a cache item by the specified key
-function that doing something with the storage
-Returns a value from the storage by the specified key.
-Before checking the storage, the method will ask getCheckStorageState for permissions to do it.
This method is called before every operation that checks data from the storage, like, has or get
Returns a value of the persistentTTL descriptor by the specified key
Initializes a new cache instance from the past one
-Normalized the given TTL value and returns it
-Removes a value from the storage by the specified key
-Removes the persistentTTL descriptor from a cache item by the specified key.
-The method returns true if the operation has been successful, otherwise false
-(the requested item hasn't been found).
Sets a value to the storage by the specified key and ttl
-API for async operations
-Map of pending operations by keys
-API to store data
-Registers a task to update a cache item by the specified key
-function that doing something with the storage
-Returns a value from the storage by the specified key.
-Before checking the storage, the method will ask getCheckStorageState for permissions to do it.
This method is called before every operation that checks data from the storage, like, has or get
Returns a value of the persistentTTL descriptor by the specified key
Initializes a new cache instance from the past one
-Normalized the given TTL value and returns it
-Removes a value from the storage by the specified key
-Removes the persistentTTL descriptor from a cache item by the specified key.
-The method returns true if the operation has been successful, otherwise false
-(the requested item hasn't been found).
Sets a value to the storage by the specified key and ttl
-cache object to wrap
-storage object to save cache items
-Original cache object
-Engine to save cache items within a storage
-Object that stores keys of all properties that have already been fetched from the storage
-Default TTL to store items
-Wrapped cache object
-Checks a cache item by the specified key in the persistent storage
-Returns the default implementation for the specified cache method with adding a feature of persistent storing
-Returns the default implementation for the specified cache method with adding a feature of persistent storing
-Returns an instance of the wrapped cache
-Implements API of the wrapped cache object
-Loopback class for a cache data structure
-Cache object
-Returns an iterator by the cache keys
-Implementation for an in-memory data structure with support for limiting of values in the cache
-value type
-key type (string by default)
Number of maximum records in the cache
-Queue object
-Cache object
-Returns an iterator by the cache keys
-Sets a new capacity of the cache. -The method returns a map of truncated elements that the cache can't fit anymore.
-Implementation for a simple in-memory cache data structure
-value type
-key type (string by default)
Cache object
-Returns an iterator by the cache keys
-Default data provider
-Default HTTP request method for the "add" method
-Advanced part of URL for a request of all request methods -(it is concatenated with the base part)
-Provider alias
-API for async operations
-Base part of URL for a request for the "add" method
-Base part of URL for a request for the "del" method
-Base part of URL for a request for the "get" method
-Base part of URL for a request for the "peek" method
-Base part of URL for a request of all request methods
-Base part of URL for a request for the "upd" method
-Cache identifier
-Socket connection
-HTTP request method for all request methods. -This parameter will override other method parameters, such as "getMethod" or "delMethod".
-Default HTTP request method for the "del" method
-Event emitter to broadcast provider events
-Event name for requests. -Please notice that all request methods except "get", "peek" and "request" emit events by default.
-List of additional data providers for the "get" method. -It can be useful if you have some providers that you want combine to one.
-Default HTTP request method for the "get" method
-Global event emitter to broadcast provider events
-Default HTTP request method for the "peek" method
-URL for a socket connection
-Default HTTP request method for the "upd" method
-Map of data decoder sequences. -The key of a map element represent a name of the provider method: 'get', 'post', etc. -The value of a map element represent a sequence of decoders for the specified provider method.
-Map of data encoder sequences. -The key of a map element represent a name of the provider method: 'get', 'post', etc. -The value of a map element represent a sequence of encoders for the specified provider method.
-Sequence of middlewares that is provided to the request function. -An object form is easily to extend, bur you can choose any different form.
-Map of data mocks.
-This object can be used with a middleware that implements API for data mocking,
-for example attachMock from 'core/data/middlewares'.
The key of a map element represent a method request type: 'GET', 'POST', etc. -The value of a map element represent a list of parameters to match.
-Transport function for a request. -Basically, you can use an overload of the request API for flexibly extending.
-Creates a new remote request with the specified options
-request path URL
-request options
-Returns a wrapped request constructor with the specified options. -This overload helps to organize the "builder" pattern.
-request options
-Returns a function to create a new remote request with the specified options. -This overload helps to create a factory of requests.
-request path URL
-function to resolve a request: it takes a request URL, request environment, and arguments - from invoking the outer function and can modify some request parameters. - Also, if the function returns a new string, the string will be appended to the request URL, or - if the function returns a string wrapped with an array, the string fully overrides the original URL.
-request options
-Alias for the request function
-Creates a new remote request with the specified options
-request path URL
-request options
-Returns a wrapped request constructor with the specified options. -This overload helps to organize the "builder" pattern.
-request options
-Returns a function to create a new remote request with the specified options. -This overload helps to create a factory of requests.
-request path URL
-function to resolve a request: it takes a request URL, request environment, and arguments - from invoking the outer function and can modify some request parameters. - Also, if the function returns a new string, the string will be appended to the request URL, or - if the function returns a string wrapped with an array, the string fully overrides the original URL.
-request options
-Add new data to the provider. -This method is similar for a POST request.
-Returns the base part of URL of any request
-Sets the base part of URL for any request. -This method returns a new provider object with context.
-Connects to a socket server and returns the connection
-Deletes data of the provider by a query. -This method is similar for a DELETE request.
-Drops the request cache of the current provider
-Requests the provider for data by a query. -This method is similar for a GET request.
-Returns an object with authentication parameters
-additional parameters
-Returns a key to the class instance cache
-Returns an event cache key by the specified parameters
-event name
-event data
-Returns an object with request options by the specified model name and object with additional parameters
-model method
-Initializes the socket behaviour after successful connecting
-Returns the custom HTTP request method of any request
-Sets the custom HTTP request method for any request. -This method returns a new provider object with context.
-Returns the custom logical name of any request. -If a request has the name, then it will fire an event with the same name after successful receiving.
-Sets the custom logical name for any request. -If a request has the name, then it will fire an event with the same name after successful receiving. -This method returns a new provider object with context.
-Checks accessibility of the provider by a query. -This method is similar for a HEAD request.
-Sends custom data to the provider without any logically effect. -This method is similar for a POST request.
-Function to resolve a request: it takes a request URL and request environment -and can modify some request parameters.
-Also, if the function returns a new string, the string will be appended to the request URL, or -if the function returns a string that wrapped with an array, the string fully override the original URL.
-request URL
-request parameters
-Sets a readonly value by the specified key to the current provider
-Updates data of the provider by a query. -This method is similar for a PUT request.
-Updates the specified request with adding caching, etc.
-request url
-request factory
-Updates the specified request with adding caching, etc.
-request url
-event name that is fired after resolving of the request
-request factory
-Returns the full URL of any request
-Sets an extra URL part for any request (it is concatenated with the base part of URL). -This method returns a new provider object with context.
-Borrows API from the specified RequestPromise object to the passed RequestResponse object and returns it
Finds an element from an object by the specified parameters
-object to search
-search parameters
-Default HTTP request method for the "add" method
-Advanced part of URL for a request of all request methods -(it is concatenated with the base part)
-Provider alias
-API for async operations
-Base part of URL for a request for the "add" method
-Base part of URL for a request for the "del" method
-Base part of URL for a request for the "get" method
-Base part of URL for a request for the "peek" method
-Base part of URL for a request of all request methods
-Base part of URL for a request for the "upd" method
-Cache identifier
-Socket connection
-HTTP request method for all request methods. -This parameter will override other method parameters, such as "getMethod" or "delMethod".
-Default HTTP request method for the "del" method
-Event emitter to broadcast provider events
-Event name for requests. -Please notice that all request methods except "get", "peek" and "request" emit events by default.
-List of additional data providers for the "get" method. -It can be useful if you have some providers that you want combine to one.
-Default HTTP request method for the "get" method
-Global event emitter to broadcast provider events
-Default HTTP request method for the "peek" method
-URL for a socket connection
-Default HTTP request method for the "upd" method
-Map of data decoder sequences. -The key of a map element represent a name of the provider method: 'get', 'post', etc. -The value of a map element represent a sequence of decoders for the specified provider method.
-Map of data encoder sequences. -The key of a map element represent a name of the provider method: 'get', 'post', etc. -The value of a map element represent a sequence of encoders for the specified provider method.
-Sequence of middlewares that is provided to the request function. -An object form is easily to extend, bur you can choose any different form.
-Map of data mocks.
-This object can be used with a middleware that implements API for data mocking,
-for example attachMock from 'core/data/middlewares'.
The key of a map element represent a method request type: 'GET', 'POST', etc. -The value of a map element represent a list of parameters to match.
-Transport function for a request. -Basically, you can use an overload of the request API for flexibly extending.
-Creates a new remote request with the specified options
-request path URL
-request options
-Returns a wrapped request constructor with the specified options. -This overload helps to organize the "builder" pattern.
-request options
-Returns a function to create a new remote request with the specified options. -This overload helps to create a factory of requests.
-request path URL
-function to resolve a request: it takes a request URL, request environment, and arguments - from invoking the outer function and can modify some request parameters. - Also, if the function returns a new string, the string will be appended to the request URL, or - if the function returns a string wrapped with an array, the string fully overrides the original URL.
-request options
-Full name of the provider including a namespace
-Alias for the request function
-Creates a new remote request with the specified options
-request path URL
-request options
-Returns a wrapped request constructor with the specified options. -This overload helps to organize the "builder" pattern.
-request options
-Returns a function to create a new remote request with the specified options. -This overload helps to create a factory of requests.
-request path URL
-function to resolve a request: it takes a request URL, request environment, and arguments - from invoking the outer function and can modify some request parameters. - Also, if the function returns a new string, the string will be appended to the request URL, or - if the function returns a string wrapped with an array, the string fully overrides the original URL.
-request options
-Add new data to the provider. -This method is similar for a POST request.
-Returns the base part of URL of any request
-Sets the base part of URL for any request. -This method returns a new provider object with context.
-Connects to a socket server and returns the connection
-Deletes data of the provider by a query. -This method is similar for a DELETE request.
-Drops the request cache of the current provider
-Requests the provider for data by a query. -This method is similar for a GET request.
-Returns an object with authentication parameters
-additional parameters
-Returns a key to the class instance cache
-Returns an event cache key by the specified parameters
-event name
-event data
-Returns an object with request options by the specified model name and object with additional parameters
-model method
-Initializes the socket behaviour after successful connecting
-Returns the custom HTTP request method of any request
-Sets the custom HTTP request method for any request. -This method returns a new provider object with context.
-Returns the custom logical name of any request. -If a request has the name, then it will fire an event with the same name after successful receiving.
-Sets the custom logical name for any request. -If a request has the name, then it will fire an event with the same name after successful receiving. -This method returns a new provider object with context.
-Checks accessibility of the provider by a query. -This method is similar for a HEAD request.
-Sends custom data to the provider without any logically effect. -This method is similar for a POST request.
-Function to resolve a request: it takes a request URL and request environment -and can modify some request parameters.
-Also, if the function returns a new string, the string will be appended to the request URL, or -if the function returns a string that wrapped with an array, the string fully override the original URL.
-request URL
-request parameters
-Sets a readonly value by the specified key to the current provider
-Updates data of the provider by a query. -This method is similar for a PUT request.
-Updates the specified request with adding caching, etc.
-request url
-request factory
-Updates the specified request with adding caching, etc.
-request url
-event name that is fired after resolving of the request
-request factory
-Returns the full URL of any request
-Sets an extra URL part for any request (it is concatenated with the base part of URL). -This method returns a new provider object with context.
-Finds an element from an object by the specified parameters
-object to search
-search parameters
-Default HTTP request method for the "add" method
-Advanced part of URL for a request of all request methods -(it is concatenated with the base part)
-Base part of URL for a request for the "add" method
-Base part of URL for a request for the "del" method
-Base part of URL for a request for the "get" method
-Base part of URL for a request for the "peek" method
-Base part of URL for a request of all request methods
-Base part of URL for a request for the "upd" method
-HTTP request method for all request methods. -This parameter will override other method parameters, such as "getMethod" or "delMethod".
-Default HTTP request method for the "del" method
-Event name for requests. -Please notice that all request methods except "get", "peek" and "request" emit events by default.
-List of additional data providers for the "get" method. -It can be useful if you have some providers that you want combine to one.
-Default HTTP request method for the "get" method
-Global event emitter to broadcast provider events
-Default HTTP request method for the "peek" method
-URL for a socket connection
-Default HTTP request method for the "upd" method
-Map of data decoder sequences. -The key of a map element represent a name of the provider method: 'get', 'post', etc. -The value of a map element represent a sequence of decoders for the specified provider method.
-Map of data encoder sequences. -The key of a map element represent a name of the provider method: 'get', 'post', etc. -The value of a map element represent a sequence of encoders for the specified provider method.
-Sequence of middlewares that is provided to the request function. -An object form is easily to extend, bur you can choose any different form.
-Map of data mocks.
-This object can be used with a middleware that implements API for data mocking,
-for example attachMock from 'core/data/middlewares'.
The key of a map element represent a method request type: 'GET', 'POST', etc. -The value of a map element represent a list of parameters to match.
-Creates a new remote request with the specified options
-request path URL
-request options
-Returns a wrapped request constructor with the specified options. -This overload helps to organize the "builder" pattern.
-request options
-Returns a function to create a new remote request with the specified options. -This overload helps to create a factory of requests.
-request path URL
-function to resolve a request: it takes a request URL, request environment, and arguments - from invoking the outer function and can modify some request parameters. - Also, if the function returns a new string, the string will be appended to the request URL, or - if the function returns a string wrapped with an array, the string fully overrides the original URL.
-request options
-Alias for the request function
-Creates a new remote request with the specified options
-request path URL
-request options
-Returns a wrapped request constructor with the specified options. -This overload helps to organize the "builder" pattern.
-request options
-Returns a function to create a new remote request with the specified options. -This overload helps to create a factory of requests.
-request path URL
-function to resolve a request: it takes a request URL, request environment, and arguments - from invoking the outer function and can modify some request parameters. - Also, if the function returns a new string, the string will be appended to the request URL, or - if the function returns a string wrapped with an array, the string fully overrides the original URL.
-request options
-Finds an element from an object by the specified parameters
-object to search
-search parameters
-Superclass of any error to inherit
-An error that causes the current error
-Internal storage for an error message
-Formats internal error's data to produce a message.
-The method calls when accessing the message property.
An error that causes the current error
-Internal storage for an error message
-Formats internal error's data to produce a message.
-The method calls when accessing the message property.
Property key of the active assembling value
-Function to transform a value after assembling.
-Its API is identical to the reviver from JSON.parse.
Stack of nested assembled items and keys contained within the active assembling value
-Handler to process an array start
-Handler to process an object start
-A value of the active assembled item. -If it is a container (object or array), all new assembled values will be added to it.
-Depth of the assembling structure
-Indicates that the active value is fully assembled
-Sets the value assembling status
-Creates a handler to process starting of an object or array
-constructor to create a structure
-Handler to process an array end
-Handler to process an object end
-Handler to process ending of primitive values
-Handler to process a falsy boolean value
-Handler to process an object key value
-Handler to process nullish values
-Handler to process a number value
-Processes the passed JSON token and yields the assembled values
-Saves an assembled value into the internal structure
-Handler to process a string value
-Handler to process a truly boolean value
-Depth of the current structure
-Name of the next expected token from a stream
-Function to filter a sequence of parsed tokens
-If true the filtration will return all matched filter results, otherwise only the first match will be returned
-Method to pass key tokens
-Method to pass numeric tokens
-Method to pass string tokens
-Name of the previous parsed token
-Method to skip key tokens
-Method to skip numeric tokens
-Method to skip string tokens
-Stack of processed tokens
-Processes the passed JSON token and yields tokens
-Sets a new process function to parse JSON chunk and yield tokens
-Check the specified token for filter satisfaction
-Checks that specified token is matched for the filter
-Closes all unclosed tokens and returns a Generator of filtered tokens. -The method must be called after the end of filtration.
-Passes the passed token into an output token stream
-Passes the passed object token into an output token stream
-Creates a function to pass tokens into an output token stream
-Skips the passed token from an output token stream
-Skips the passed object token from an output token stream
-Creates a function to skip tokens from an output token stream
-Creates a function to filter only chunks by the specified path
-Creates a function to filter only chunks with paths matched to the specified regular expression
-Depth of the current structure
-Name of the next expected token from a stream
-Function to filter a sequence of parsed tokens
-If true the filtration will return all matched filter results, otherwise only the first match will be returned
-Stack for the current object that is being filtered
-Method to pass key tokens
-Method to pass numeric tokens
-Method to pass string tokens
-Name of the previous parsed token
-Method to skip key tokens
-Method to skip numeric tokens
-Method to skip string tokens
-Stack of processed tokens
-Processes the passed JSON token and yields tokens
-Sets a new process function to parse JSON chunk and yield tokens
-Check the specified token for filter satisfaction
-Closes all unclosed tokens and returns a Generator of filtered tokens. -The method must be called after the end of filtration.
-Passes the passed token into an output token stream
-Passes the passed object token into an output token stream
-Creates a function to pass tokens into an output token stream
-Skips the passed token from an output token stream
-Skips the passed object token from an output token stream
-Creates a function to skip tokens from an output token stream
-Creates a function to filter only chunks by the specified path
-Creates a function to filter only chunks with paths matched to the specified regular expression
-Depth of the current structure
-Name of the next expected token from a stream
-Function to filter a sequence of parsed tokens
-If true the filtration will return all matched filter results, otherwise only the first match will be returned
-Method to pass key tokens
-Method to pass numeric tokens
-Method to pass string tokens
-Name of the previous parsed token
-Method to skip key tokens
-Method to skip numeric tokens
-Method to skip string tokens
-Stack of processed tokens
-Processes the passed JSON token and yields tokens
-Sets a new process function to parse JSON chunk and yield tokens
-Check the specified token for filter satisfaction
-Closes all unclosed tokens and returns a Generator of filtered tokens. -The method must be called after the end of filtration.
-Passes the passed token into an output token stream
-Passes the passed object token into an output token stream
-Creates a function to pass tokens into an output token stream
-Skips the passed token from an output token stream
-Skips the passed object token from an output token stream
-Creates a function to skip tokens from an output token stream
-Creates a function to filter only chunks by the specified path
-Creates a function to filter only chunks with paths matched to the specified regular expression
-Accumulator for the current parsed structure
-The current piece of JSON
-The next expected parser state from a stream
-The current index in a buffer parsing process
-Is the parser parsing a number now
-The current match value after RegExp execution
-The current parent of a parsed structure
-Dictionary with RegExp-s to different types of data
-An array of parent objects for the current parsed structure
-The current parsed value
-Closes all unclosed tokens and returns a Generator of tokens. -The method must be called after the end of parsing.
-Processes the passed JSON chunk and yields tokens via an asynchronous Generator
-Parses the specified iterable object as a JSON stream and yields tokens via a Generator
-Parses the specified iterable object as a JSON stream and yields tokens or values via a Generator
-Instance of a token assembler
-Index of the current streamed array element
-True if the streamed structure is already checked
-Actual depth of the streamed structure
-Checks that specified token is matched for the streamer type
-Processes the passed JSON token and yields the assembled value
-Method to yield assembled tokens
-Instance of a token assembler
-True if the streamed structure is already checked
-Actual depth of the streamed structure
-Checks that specified token is matched for the streamer type
-Processes the passed JSON token and yields the assembled value
-Method to yield assembled tokens
-Instance of a token assembler
-True if the streamed structure is already checked
-Last key of the current streamed object property
-Actual depth of the streamed structure
-Checks that specified token is matched for the streamer type
-Processes the passed JSON token and yields the assembled value
-Method to yield assembled tokens
-Implementation of persistent asynchronous key-value storage based on IndexedDB
-Double-ended two-way linked list
-linked list node data
-A link to the first node of the list
-A link to the last node of the list
-Internal length value of the list
-Data of the first node in the list
-Data of the last node in the list
-Number of nodes in the list
-Returns an iterator over the data from the list
-Clears all nodes from the list
-Returns true if the list contains a node with the given data
-Removes the last node from the list and returns its data as the result. -This method changes the length of the list.
-Adds the passed data to the end of the list and returns its new length
-Returns an iterator over the data in the list. -The traversal will proceed from the last node to the first.
-Removes the first node from the list and returns its data as the result. -This method changes the length of the list.
-Returns a shallow copy of a portion of a list into a new LinkedList selected from start to end (end not included) -where start and end represent the index of nodes in that list. The original list will not be modified.
-Adds the passed data to the beginning of the list and returns its new length
-Returns an iterator over the data from the list
-Linked list node
-node data
-Node data
-A link to the next node
-A link to the previous node
-Returns a string representing of a style for the specified log level
-level of logging that needs a style
-Prints the specified event to a console
-log event to print
-Processes the events -(if it has data to pass to the next middleware, calls the next callback)
-Returns true if config patterns allow to log a record with the specified context
-Middleware to omit duplicated errors
-Errors that have already been occurred
-Processes the events -(if it has data to pass to the next middleware, calls the next callback)
-Returns true if the passed event has an error that's already occurred
-log event from a pipeline
-Middleware to extract information from an error log event and store
-it within the additionals dictionary of the event
Processes the events -(if it has data to pass to the next middleware, calls the next callback)
-Returns an error's info structure
-error, which details should be returned
-if false then adds name and message of the passed error to its info
maximum depth of nested errors
-An error that causes the current error
-Internal storage for an error message
-Formats internal error's data to produce a message.
-The method calls when accessing the message property.
An error that causes the current error
-Internal storage for an error message
-Formats internal error's data to produce a message.
-The method calls when accessing the message property.
Constructor function of an error
-Extracts details from the passed error
-Class to create a custom property descriptor
-Original property descriptor
-Returns a value from the descriptor
-receiver for a get method
-Sets a new value to the descriptor
-receiver for a set method
-Represents abstraction that can measure the difference between time moments and create new performance timers
-engine instance that sends metrics to the target destination
-An engine's instance that sends metrics to the target destination
-Predicate to filter metrics by their names.
-If it returns false, the metrics will not send to the engine.
Internal storage for the current start/finish metrics
Internal storage for the following identifier of each namespace
-Salt for each runner instance.
-It is used to generate a time, so the times from the different runners cannot be used interchangeably.
-It prevents sending start/finish metrics by mistake.
Time offset from the application start. -It may be considered as the time from which all metrics are measured for the current runner instance.
-Returns a new instance of the performance timer
-timer group
-Returns a timestamp taking into account the runner's timer origin
-Combines the passed namespaces together
-namespaces to combine
-Implementation of an object pool structure
-pool resource
-extra arguments to pass to the resource factory during initialization
-Set of all available resources
-Map of active borrow events
-Store of borrowed pool resources
-Event emitter to broadcast pool events
-Queue of active events
-A function to calculate a hash string for the specified arguments
-The maximum number of resources that the pool can contain
-Handler: taking some resource via borrow methods
Handler: clearing of all pool resources
-Handler: releasing of some resource
-Handler: taking some resource via take methods
A function to destroy one resource from the pool
-A factory to create a new resource for the pool.
-The function take arguments that are passed to takeOrCreate, borrowAndCreate, etc.
Store of pool resources
-Set of all unavailable resources
-Number of available resources that are stored in the pool
-Number of resources that are stored in the pool
-Borrows an available resource from the pool. -The passed arguments will be used to calculate a resource hash. Also, they will be provided to hook handlers.
-When a resource is borrowed, it won’t be dropped from the pool. I.e. you can share it with other consumers. -Mind, you can’t take this resource from the pool when it’s borrowed.
-The returned result is wrapped with a structure that contains methods to release or drop this resource. -If the pool is empty, the structure value field will be nullish.
-Borrows an available resource from the pool. -The passed arguments will be used to calculate a resource hash. Also, they will be provided to hook handlers.
-When a resource is borrowed, it won’t be dropped from the pool. I.e. you can share it with other consumers. -Mind, you can’t take this resource from the pool when it’s borrowed.
-The returned result is wrapped with a structure that contains methods to release or drop this resource. -If the pool is empty, it creates a new resource and returns it.
-Returns a promise with a borrowed resource from the pull. -The passed arguments will be used to calculate a resource hash. Also, they will be provided to hook handlers.
-When a resource is borrowed, it won’t be dropped from the pool. I.e. you can share it with other consumers. -Mind, you can’t take this resource from the pool when it’s borrowed.
-The returned result is wrapped with a structure that contains methods to release or drop this resource. -If the pool is empty, the promise will wait till it release.
-Checks if you can borrow a resource. -The passed arguments will be used to calculate a resource hash.
-Returns how many elements of the specified kind you can take. -The method takes arguments that will be used to calculate a resource hash.
-Clears the pool, i.e. drops all created resource. -The method takes arguments that will be provided to hook handlers.
-Creates a resource and stores it in the pool. -The method takes arguments that will be provided to a resource factory.
-Releases the specified resource. -The method takes arguments that will be provided to hook handlers.
-Returns an available resource from the pool. -The passed arguments will be used to calculate a resource hash. Also, they will be provided to hook handlers.
-The returned result is wrapped with a structure that contains methods to release or drop this resource. -If the pool is empty, the structure value field will be nullish.
-Returns an available resource from the pool. -The passed arguments will be used to calculate a resource hash. Also, they will be provided to hook handlers.
-The returned result is wrapped with a structure that contains methods to release or drop this resource. -If the pool is empty, it creates a new resource and returns it.
-Returns a promise with an available resource from the pull. -The passed arguments will be used to calculate a resource hash. Also, they will be provided to hook handlers.
-The returned result is wrapped with a structure that contains methods to release or drop this resource. -If the pool is empty, the promise will wait till it release.
-Wraps the specified resource and returns the wrapper
-List of handlers to handle the promise fulfilling
-List of handlers to handle the promise rejection
-Actual promise state
-Resolved promise value
-True if the current promise is pending
-Executes a function with the specified parameters
-arguments for the function
-Attaches a handler for the promise' rejected state. -The method returns a new promise that will be resolved with a value that returns from the passed handler.
-Attaches a common callback for the promise fulfilled and rejected states. -The method returns a new promise with the state and value from the current. -A value from the passed callback will be ignored unless it equals a rejected promise or exception.
-Attaches handlers for the promise fulfilled and/or rejected states. -The method returns a new promise that will be resolved with a value that returns from the passed handlers.
-Returns the promise' value if it is fulfilled, otherwise throws an exception
-Takes an iterable of promises and returns a single SyncPromise that resolves to an array of the results -of the input promises. This returned promise will resolve when all the input's promises have been resolved or -if the input iterable contains no promises. It rejects immediately upon any of the input promises rejecting or -non-promises throwing an error and will reject with this first rejection message/error.
-Returns a promise that resolves after all the given promises have either been fulfilled or rejected, -with an array of objects describing each promise's outcome.
-It is typically used when you have multiple asynchronous tasks that are not dependent on one another to -complete successfully, or you'd always like to know the result of each promise.
-In comparison, the SyncPromise returned by SyncPromise.all() may be more appropriate
-if the tasks are dependent on each other / if you'd like to reject upon any of them reject immediately.
Takes an iterable of SyncPromise objects and, as soon as one of the promises in the iterable fulfills, -returns a single promise that resolves with the value from that promise. If no promises in the iterable fulfill -(if all the given promises are rejected), then the returned promise is rejected with an AggregateError, -a new subclass of Error that groups together individual errors.
-Returns a SyncPromise object that is rejected with a given reason
-Returns a SyncPromise object that is resolved with a given value.
-If the value is a promise, that promise is returned; if the value is a thenable (i.e., has a "then" method), -the returned promise will "follow" that thenable, adopting its eventual state; otherwise, -the returned promise will be fulfilled with the value.
-This function flattens nested layers of promise-like objects -(e.g., a promise that resolves to a promise that resolves to something) into a single layer.
-Returns a new resolved SyncPromise object with an undefined value
-List of handlers to handle the promise fulfilling
-List of handlers to handle the promise rejection
-Actual promise state
-Resolved promise value
-True if the current promise is pending
-Executes a function with the specified parameters
-arguments for the function
-Attaches a handler for the promise' rejected state. -The method returns a new promise that will be resolved with a value that returns from the passed handler.
-Attaches a common callback for the promise fulfilled and rejected states. -The method returns a new promise with the state and value from the current. -A value from the passed callback will be ignored unless it equals a rejected promise or exception.
-Attaches handlers for the promise fulfilled and/or rejected states. -The method returns a new promise that will be resolved with a value that returns from the passed handlers.
-Returns the promise' value if it is fulfilled, otherwise throws an exception
-Takes an iterable of promises and returns a single SyncPromise that resolves to an array of the results -of the input promises. This returned promise will resolve when all the input's promises have been resolved or -if the input iterable contains no promises. It rejects immediately upon any of the input promises rejecting or -non-promises throwing an error and will reject with this first rejection message/error.
-Returns a promise that resolves after all the given promises have either been fulfilled or rejected, -with an array of objects describing each promise's outcome.
-It is typically used when you have multiple asynchronous tasks that are not dependent on one another to -complete successfully, or you'd always like to know the result of each promise.
-In comparison, the SyncPromise returned by SyncPromise.all() may be more appropriate
-if the tasks are dependent on each other / if you'd like to reject upon any of them reject immediately.
Takes an iterable of SyncPromise objects and, as soon as one of the promises in the iterable fulfills, -returns a single promise that resolves with the value from that promise. If no promises in the iterable fulfill -(if all the given promises are rejected), then the returned promise is rejected with an AggregateError, -a new subclass of Error that groups together individual errors.
-Returns a SyncPromise object that is rejected with a given reason
-Returns a SyncPromise object that is resolved with a given value.
-If the value is a promise, that promise is returned; if the value is a thenable (i.e., has a "then" method), -the returned promise will "follow" that thenable, adopting its eventual state; otherwise, -the returned promise will be fulfilled with the value.
-This function flattens nested layers of promise-like objects -(e.g., a promise that resolves to a promise that resolves to something) into a single layer.
-Returns a new resolved SyncPromise object with an undefined value
-Class is similar to the native promise class but works synchronously
-List of handlers to handle the promise fulfilling
-List of handlers to handle the promise rejection
-Actual promise state
-Resolved promise value
-True if the current promise is pending
-Executes a function with the specified parameters
-arguments for the function
-Attaches a handler for the promise' rejected state. -The method returns a new promise that will be resolved with a value that returns from the passed handler.
-Attaches a common callback for the promise fulfilled and rejected states. -The method returns a new promise with the state and value from the current. -A value from the passed callback will be ignored unless it equals a rejected promise or exception.
-Attaches handlers for the promise fulfilled and/or rejected states. -The method returns a new promise that will be resolved with a value that returns from the passed handlers.
-Returns the promise' value if it is fulfilled, otherwise throws an exception
-Takes an iterable of promises and returns a single SyncPromise that resolves to an array of the results -of the input promises. This returned promise will resolve when all the input's promises have been resolved or -if the input iterable contains no promises. It rejects immediately upon any of the input promises rejecting or -non-promises throwing an error and will reject with this first rejection message/error.
-Returns a promise that resolves after all the given promises have either been fulfilled or rejected, -with an array of objects describing each promise's outcome.
-It is typically used when you have multiple asynchronous tasks that are not dependent on one another to -complete successfully, or you'd always like to know the result of each promise.
-In comparison, the SyncPromise returned by SyncPromise.all() may be more appropriate
-if the tasks are dependent on each other / if you'd like to reject upon any of them reject immediately.
Takes an iterable of SyncPromise objects and, as soon as one of the promises in the iterable fulfills, -returns a single promise that resolves with the value from that promise. If no promises in the iterable fulfill -(if all the given promises are rejected), then the returned promise is rejected with an AggregateError, -a new subclass of Error that groups together individual errors.
-Returns a SyncPromise object that is rejected with a given reason
-Returns a SyncPromise object that is resolved with a given value.
-If the value is a promise, that promise is returned; if the value is a thenable (i.e., has a "then" method), -the returned promise will "follow" that thenable, adopting its eventual state; otherwise, -the returned promise will be fulfilled with the value.
-This function flattens nested layers of promise-like objects -(e.g., a promise that resolves to a promise that resolves to something) into a single layer.
-Returns a new resolved SyncPromise object with an undefined value
-Class wraps promise-like objects and adds to them some extra functionality, -such as possibility of cancellation, etc.
-promise resolved value
-If true, then the promise was aborted
-Handler of the native promise rejection that was raised by a reason of abort
-Handler of the native promise rejection
-Handler of the native promise resolving
-Number of pending child promises
-Internal native promise instance
-Actual promise state
-Resolved promise value
-True if the current promise is pending
-Aborts the current promise (the promise will be rejected)
-Executes a function with the specified parameters
-arguments for the function
-Attaches a handler for the promise' rejected state. -The method returns a new promise that will be resolved with a value that returns from the passed handler.
-Attaches a common callback for the promise fulfilled and rejected states. -The method returns a new promise with the state and value from the current. -A value from the passed callback will be ignored unless it equals a rejected promise or exception.
-Attaches handlers for the promise fulfilled and/or rejected states. -The method returns a new promise that will be resolved with a value that returns from the passed handlers.
-Takes an iterable of promises and returns a single AbortablePromise that resolves to an array of the results -of the input promises. This returned promise will resolve when all the input's promises have been resolved or -if the input iterable contains no promises. It rejects immediately upon any of the input promises rejecting or -non-promises throwing an error and will reject with this first rejection message/error.
-Returns a promise that resolves after all the given promises have either been fulfilled or rejected, -with an array of objects describing each promise's outcome.
-It is typically used when you have multiple asynchronous tasks that are not dependent on one another to -complete successfully, or you'd always like to know the result of each promise.
-In comparison, the AbortablePromise returned by AbortablePromise.all() may be more appropriate
-if the tasks are dependent on each other / if you'd like to reject upon any of them reject immediately.
Returns an AbortablePromise object that is resolved with a given value.
-If the value is a promise, that promise is returned; if the value is a thenable (i.e., has a "then" method), -the returned promise will "follow" that thenable, adopting its eventual state; otherwise, -the returned promise will be fulfilled with the value.
-This function flattens nested layers of promise-like objects -(e.g., a promise that resolves to a promise that resolves to something) into a single layer.
-Returns a new resolved AbortablePromise object with an undefined value
-Returns an AbortablePromise object that is resolved with a given value. -If the resolved value is a function, it will be invoked. -The result of the invoking will be provided as a value of the promise.
-If the value is a promise, that promise is returned; if the value is a thenable (i.e., has a "then" method), -the returned promise will "follow" that thenable, adopting its eventual state; otherwise, -the returned promise will be fulfilled with the value.
-This function flattens nested layers of promise-like objects -(e.g., a promise that resolves to a promise that resolves to something) into a single layer.
-Returns a new resolved AbortablePromise object with an undefined value
-The method wraps the specified abort reason to ignore with tied promises, -i.e., this reason won't reject all child promises
-An abstract class for any queue data structure
-queue element
-The first element in the queue
-Number of elements in the queue
-Returns an iterator over the queue elements
-Clears the queue
-Creates a new queue based on the current one and returns it
-Removes the head element from the queue and returns it
-Adds a new element to the queue
-Alias to pop
Alias to push
Returns an iterator over the queue elements
-Implementation of a queue data structure with support of task merging by a specified hash function
-the queue element
-Type: the internal queue to store elements
-Returns a new blank internal queue to store elements
-A function to calculate task hashes
-The internal queue to store elements
-A map of registered tasks
-The first element in the queue
-Number of elements in the queue
-Returns an iterator over the queue elements
-Clears the queue
-Creates a new queue based on the current one and returns it
-Removes the head element from the queue and returns it
-Adds a new element to the queue
-Alias to pop
Alias to push
Returns an iterator over the queue elements
-Implementation of an ordered queue data structure based on a binary heap
-the queue element
-a function to compare tasks
-Type: the internal queue to store elements
-A function to compare tasks
-Returns a new blank internal queue to store elements
-The internal queue to store elements
-An index of the last element from the queue
-The first element in the queue
-Number of elements in the queue
-Returns an iterator over the queue elements
-Clears the queue
-Creates a new queue based on the current one and returns it
-Pushes the last queue element to the top
-Removes the head element from the queue and returns it
-Adds a new element to the queue
-Alias to pop
Pushes the first queue element down
-Alias to push
Returns an iterator over the queue elements
-Implementation of a queue data structure based on a linked-list
-the queue element
-Type: the internal queue to store elements
-Returns a new blank internal queue to store elements
-The internal queue to store elements
-The first element in the queue
-Number of elements in the queue
-Returns an iterator over the queue elements
-Clears the queue
-Creates a new queue based on the current one and returns it
-Removes the head element from the queue and returns it
-Adds a new element to the queue
-Alias to pop
Alias to push
Returns an iterator over the queue elements
-An abstract class for a worker queue data structure
-the task element
-the worker value
-Type: a queue of tasks
-Number of active workers
-The maximum number of concurrent workers
-Returns a new blank internal queue of tasks
-The first element in the queue
-How often to update task statuses (in milliseconds)
-A queue of tasks
-The worker constructor
-Number of elements in the queue
-Returns an asynchronous iterator over the queue elements
-Returns an iterator over the queue elements
-Clears the queue
-Creates a new queue based on the current one and returns it
-Executes a task chunk from the queue (deferred version)
-Executes a task chunk from the queue
-Removes the head element from the queue and returns it
-Adds a new element to the queue
-Provides a task result to the specified promise resolve function
-Alias to pop
Starts an execution of tasks from the queue
-Alias to push
Returns an iterator over the queue elements
-Implementation of a worker queue data structure with support of task merging by a specified hash function
-the task element
-the worker value
-Type: a queue of tasks
-Number of active workers
-The maximum number of concurrent workers
-Returns a new blank internal queue of tasks
-A function to calculate task hashes
-How often to update task statuses (in milliseconds)
-A queue of tasks
-A map of registered tasks
-The worker constructor
-The first element in the queue
-Returns an asynchronous iterator over the queue elements
-Returns an iterator over the queue elements
-Clears the queue
-Creates a new queue based on the current one and returns it
-Executes a task chunk from the queue (deferred version)
-Executes a task chunk from the queue
-Removes the head element from the queue and returns it
-Adds a new element to the queue
-Provides a task result to the specified promise resolve function
-Alias to pop
Starts an execution of tasks from the queue
-Alias to push
Returns an iterator over the queue elements
-Implementation of a worker queue data structure
-the task element
-the worker value
-Type: a queue of tasks
-Number of active workers
-The maximum number of concurrent workers
-Returns a new blank internal queue of tasks
-How often to update task statuses (in milliseconds)
-A queue of tasks
-The worker constructor
-The first element in the queue
-Returns an asynchronous iterator over the queue elements
-Returns an iterator over the queue elements
-Clears the queue
-Creates a new queue based on the current one and returns it
-Executes a task chunk from the queue (deferred version)
-Executes a task chunk from the queue
-Removes the head element from the queue and returns it
-Adds a new element to the queue
-Provides a task result to the specified promise resolve function
-Alias to pop
Starts an execution of tasks from the queue
-Alias to push
Returns an iterator over the queue elements
-A class to create a range with the specified type. -The class supports ranges of numbers, strings, and dates.
-range type value
-Top bound
-True if the range is reversed
-Bottom bound
-Range type
-Returns an iterator from the range
-Clamps an element to be within the range if it falls outside.
-If the range is invalid or empty, the method always returns null.
Clones the range and returns a new
-Returns true if the specified element is contained inside the range -(the element can be a simple value or another range)
-Returns an iterator from the range that produces pairs of iteration indices and values
-Returns an iterator from the range that produces iteration indices
-Returns a new range with the latest starting point as its start, and the earliest ending point as its end. -If the two ranges do not intersect, this will effectively produce an empty range.
-The method preserves element ordering of the first range. -The intersection of ranges with different types will always produce an empty range.
-Returns true if the range is valid
-Clones the range with reversing of element ordering and returns a new
-Returns a span of the range. -The span includes both the start and the end.
-If the range is a date range, the value is in milliseconds.
-If the range is invalid or empty, the method always returns 0.
Creates an array from the range and returns it. -Mind, you can't transform infinite ranges to arrays, but you free to use iterators.
-Creates a string from the range and returns it. -If the range invalid or empty, the method always returns an empty string.
-Converts a value to the real range type
-Returns a new range with the earliest starting point as its start, and the latest ending point as its end. -If the two ranges do not intersect, this will effectively remove the "gap" between them.
-The method preserves element ordering of the first range. -The union of ranges with different types will always produce an empty range.
-Returns an iterator from the range
-Class to wrap any request error
-An error that causes the current error
-Error details
-Internal storage for an error message
-Error type
-Default error type: a request was aborted
-Default error type: a request was failed because of an internal request engine' error
-Default error type: a server has responded with a non-ok status
-Default error type: a request was failed because there is no connection to a network
-Default error type: a request was aborted because of a timeout
-Formats internal error's data to produce a message.
-The method calls when accessing the message property.
Extractor to get details from RequestError
Parameters to define which header makes its way to the result
-Constructor function of an error
-Extracts details from the passed error
-an error, which details should be extracted
-Filters the specified headers according to settings
-headers that need to be filtered
-Class to create a set of HTTP headers
-Request query object (to interpolate values from headers)
-Returns an iterator over headers. -It produces tuples with headers' names and values.
-Appends a new value into an existing header or adds the header if it does not already exist. -To set multiple values for one header, provide its value as a list of values.
-Deletes a header by the specified name
-Returns an iterator over headers. -It produces tuples with headers' names and values.
-Iterates over the headers and invokes the given callback function at each header
-Returns a header value by the specified name
-Returns true if the structure contains a header by the specified name
-Returns an iterator over headers' names
-Normalizes the specified header name
-Normalizes the specified header value
-Sets a new header value by the specified name. -To set multiple values for one header, provide its value as a list of values.
-Returns an iterator over headers' values
-Context of a request
-response data
-Storage to cache the resolved request
-Cache TTL identifier
-True if the request can be cached
-Promise that resolves when the instance is already initialized
-Request parameters
-Link to a parent operation promise
-Storage to cache the request while it is pending a response
-True if the request can provide parameters only as a query string
-Sequence of response data decoders
-Sets a new sequence of response data decoders
-Sequence of request data encoders
-Sets a new sequence of request data encoders
-Alias for params.headers
Alias for params.query
Sequence of response data decoders
-Sets a new sequence of response data decoders
-Drops the request cache
-Generates a string cache key for specified URL and returns it
-Returns an absolute URL for the request API
-Resolves request parameters and returns an absolute URL for the request
-Returns an absolute URL for the request
-Middleware to cache a response object
-response object
-A middleware to wrap the specified response value with RequestResponseObject.
-Use it when wrapping some raw data as the core/request response.
Wraps the specified promise: attaches the pending cache, etc.
-Forks the specified request context and decorates it with additional parameters
-request path URL
-function to resolve a request
-additional arguments for the resolver
-Storage to cache the resolved request
-Cache TTL identifier
-True if the request can be cached
-Promise that resolves when the instance is already initialized
-Request parameters
-Link to a parent operation promise
-Storage to cache the request while it is pending a response
-True if the request can provide parameters only as a query string
-Sequence of response data decoders
-Sets a new sequence of response data decoders
-Sequence of request data encoders
-Sets a new sequence of request data encoders
-Alias for params.headers
Alias for params.query
Sequence of response data decoders
-Sets a new sequence of response data decoders
-Drops the request cache
-Generates a string cache key for specified URL and returns it
-Returns an absolute URL for the request API
-Resolves request parameters and returns an absolute URL for the request
-Returns an absolute URL for the request
-Storage to cache the resolved request
-Cache TTL identifier
-True if the request can be cached
-Promise that resolves when the instance is already initialized
-Request parameters
-Link to a parent operation promise
-Storage to cache the request while it is pending a response
-True if the request can provide parameters only as a query string
-Sequence of response data decoders
-Sets a new sequence of response data decoders
-Sequence of request data encoders
-Sets a new sequence of request data encoders
-Alias for params.headers
Alias for params.query
Sequence of response data decoders
-Sets a new sequence of response data decoders
-Drops the request cache
-Generates a string cache key for specified URL and returns it
-Returns an absolute URL for the request API
-Resolves request parameters and returns an absolute URL for the request
-Returns an absolute URL for the request
-Middleware to cache a response object
-response object
-A middleware to wrap the specified response value with RequestResponseObject.
-Use it when wrapping some raw data as the core/request response.
Wraps the specified promise: attaches the pending cache, etc.
-Storage to cache the resolved request
-Cache TTL identifier
-True if the request can be cached
-Promise that resolves when the instance is already initialized
-Request parameters
-Link to a parent operation promise
-Storage to cache the request while it is pending a response
-True if the request can provide parameters only as a query string
-Sequence of response data decoders
-Sets a new sequence of response data decoders
-Sequence of request data encoders
-Sets a new sequence of request data encoders
-Alias for params.headers
Alias for params.query
Sequence of response data decoders
-Sets a new sequence of response data decoders
-Buffer of added values
-True, if an asynchronous iterator from Symbol.asyncIterator was called
Current pending promise that resolves when a new value is added
-Returns a boolean stating whether the stream is open or not
-Returns an async iterator allowing to go through the stream
-Returns an iterator allowing to go through all items that were already added
-Adds a new value to the stream if it is opened, otherwise does nothing
-item to add
-Closes the stream
-Destroys the stream
-Class to work with server response data
-response data type
-Response body value
-Creates a clone of a response object, identical in every way, but stored in a different variable
-List of response decoders
-Event emitter to broadcast response events
-Set of response headers
-A meta flag that indicates that the request is important: is usually used with decoders to indicate that -the request needs to be executed as soon as possible
-Reviver function for JSON.parse
True if the response status matches with a successful status codes -(by default it should match range from 200 to 299)
-A list of status codes (or a single code) that match successful operation. -Also, you can pass a range of codes.
-Parent operation promise
-True if the response was obtained through a redirect
-Original type of the response data
-Response status code
-Response status text
-List of response decoders to apply for chunks when you are parsing response in a stream form
-Mode type of the response
-The resolved request URL (after resolving redirects, etc.)
-True, if the response body is already read
-Sets a new status of bodyUsed
Type of the response data
-Sets a new type of the response data
-True, if the response body is already read as a stream
-Sets a new status of streamUsed
Returns an iterator by the response body.
-Mind, when you parse response via iterator, you won't be able to use other parse methods, like json or text.
Applies the given decoders to the specified data and returns a promise with the result
-Applies the given decoders to the specified data stream and yields values via an asynchronous iterator
-Parses the response body as an ArrayBuffer and returns it
-Parses the response body as a Blob structure and returns it
-Parses the response body and returns a promise with the result. -The operation result is memoized, and you can't parse the response as a stream after invoking this method.
-A way to parse data is based on the response Content-Type header or a passed responseType constructor option.
-Also, a sequence of decoders is applied to the parsed result if they are passed with a decoders
-constructor option.
Parses the response body as a stream and yields chunks via an async iterator. -You can't parse the response as a whole data after invoking this method.
-A way to parse data chunks is based on the response Content-Type header or a passed responseType
-constructor option. Also, a sequence of stream decoders is applied to the parsed chunk if they are
-passed with a streamDecoders constructor option.
Converts the specified data to a Blob structure and returns it
-Converts the specified data to a string and returns it
-Parses the response body as a Document instance and returns it
-Parses the response body as a FormData object and returns it
-Returns an HTTP header value by the specified name
-Parses the response body as a JSON object and returns it
-Parses the response data stream as a JSON tokens and yields them via an async iterator
-Reads the response body or throws an exception if reading is impossible
-Parses the response data stream as an ArrayBuffer chunks and yields them via an async iterator
-Parses the response body as a string and returns it
-Parses the response data stream as a text chunks and yields them via an async iterator
-This library provides a bunch of isomorphic modules and configurations to work as a foundation for another V4 libraries and contents many base classes and structures, such as queue, persistent key-value storage, subclasses to work with promises, etc.
- - - -// Register Prelude in the top level of your project
require('@v4fire/core');
const {watch} = require('@v4fire/core/lib/core/object/watch').default;
const {proxy} = watch({a: 1}, console.log);
proxy.a++;
-
-Also, you can require modules by using import.
// Register Prelude in the top level of your project
import '@v4fire/core';
import watch from '@v4fire/core/lib/core/object/watch/index.js';
const {proxy} = watch({a: 1}, console.log);
proxy.a++;
-
-
-
- At first, you should install dependencies using npm:
npm ci
-
-After this you should compile a configuration for TypeScript:
-npx gulp build:tsconfig
-
-
-
- All build config files are placed within the config folder. File names of config files are tied with a value of the NODE_ENV environment variable.
-Build scripts, such as Gulp or Webpack, are contained within the build folder.
To build your project, you should run the following script:
-npm run build
-
-
-
- Before running tests, your project should be built. There are several scripts that run tests:
-// runs tests that check typing
npm run test:typescript
// runs tests that check code quality
npm run test:eslint
// runs both previous tests
npm run test:linters
// runs unit tests
npm run test:jasmine
// runs all tests
npm test
-
-
-
- During test development, it's convenient when the project is rebuilt automatically after changes in code. -For this purpose, you can use the following script:
-npm run dev
-
-Then you can run tests that you are currently developing:
-npx jasmine ./dist/server/path/to/*.spec.js
-
-Performs left-to-right function composition. -The first argument may have any arity; the remaining arguments must be unary.
-If any function from parameters returns a Promise, the next function from the parameters -will take the resolved value of that promise, -the final result of calling the composition function is also a promise.
-Performs left-to-right function composition. -The first argument may have any arity; the remaining arguments must be unary.
-If any function from parameters returns a Promise, the next function from the parameters -will take the resolved value of that promise, -the final result of calling the composition function is also a promise.
-Returns a curried equivalent of the function.
-The curried function has two unusual capabilities. -First, its arguments needn't be provided one at a time. -If f is a ternary function and g is f.curry(), the following are equivalent:
-g(1)(2)(3)
g(1)(2, 3)
g(1, 2)(3)
g(1, 2, 3)
-
-Secondly, the special placeholder value Function.__ may be used to specify "gaps", allowing partial application -of any combination of arguments, regardless of their positions. If g is as above and _ is Function.__, -the following are equivalent:
-g(1, 2, 3)
g(_, 2, 3)(1)
g(_, _, 3)(1)(2)
g(_, _, 3)(1, 2)
g(_, 2)(1)(3)
g(_, 2)(1, 3)
g(_, 2)(_, 3)(1)
-
-Returns a curried equivalent of the function.
-The curried function has two unusual capabilities. -First, its arguments needn't be provided one at a time. -If f is a ternary function and g is f.curry(), the following are equivalent:
-g(1)(2)(3)
g(1)(2, 3)
g(1, 2)(3)
g(1, 2, 3)
-
-Secondly, the special placeholder value Function.__ may be used to specify "gaps", allowing partial application -of any combination of arguments, regardless of their positions. If g is as above and _ is Function.__, -the following are equivalent:
-g(1, 2, 3)
g(_, 2, 3)(1)
g(_, _, 3)(1)(2)
g(_, _, 3)(1, 2)
g(_, 2)(1)(3)
g(_, 2)(1, 3)
g(_, 2)(_, 3)(1)
-
-Returns a new function that allows to invoke the target function only with the specified delay. -The next invocation of the function will cancel the previous.
-Returns a new function that allows to invoke the target function only with the specified delay. -The next invocation of the function will cancel the previous.
-Returns a new function that allows to invoke the target function only once
-Returns a new function that allows to invoke the target function only once
-Returns a new function based on the target that wraps the returning value into the Either structure. -If the first argument of the created function is taken null or undefined, the function returns the rejected value.
-Returns a new function based on the target that wraps the returning value into the Either structure. -If the first argument of the created function is taken null or undefined, the function returns the rejected value.
-Returns a new function based on the target that wraps the returning value into the Either structure. -If the first argument of the created function is taken null or undefined, the function returns the rejected value.
-Returns a new function based on the target that wraps the returning value into the Either structure. -If the first argument of the created function is taken null or undefined, the function returns the rejected value.
-Returns a new function based on the target that wraps the returning value into the Either structure. -If the first argument of the created function is taken null or undefined, the function returns the rejected value.
-Returns a new function based on the target that wraps the returning value into the Either structure. -If the first argument of the created function is taken null or undefined, the function returns the rejected value.
-Returns a new function based on the target that wraps the returning value into the Either structure
-Returns a new function based on the target that wraps the returning value into the Either structure
-Returns a new function based on the target that wraps the returning value into the Either structure
-Returns a new function based on the target that wraps the returning value into the Either structure
-Returns a new function that allows to invoke the target function not more often than the specified delay. -The first invoking of a function will run immediately, but all rest invokes will be merged to one and -executes after the specified delay.
-Returns a new function that allows to invoke the target function not more often than the specified delay. -The first invoking of a function will run immediately, but all rest invokes will be merged to one and -executes after the specified delay.
-options for the operation
-Returns a new function that allows to invoke the target function not more often than the specified delay. -The first invoking of a function will run immediately, but all rest invokes will be merged to one and -executes after the specified delay.
-Returns a new function that allows to invoke the target function not more often than the specified delay. -The first invoking of a function will run immediately, but all rest invokes will be merged to one and -executes after the specified delay.
-options for the operation
-Performs left-to-right function composition. -The first argument may have any arity; the remaining arguments must be unary.
-If any function from parameters returns a Promise, the next function from the parameters -will take the resolved value of that promise, -the final result of calling the composition function is also a promise.
-Performs left-to-right function composition. -The first argument may have any arity; the remaining arguments must be unary.
-If any function from parameters returns a Promise, the next function from the parameters -will take the resolved value of that promise, -the final result of calling the composition function is also a promise.
-Returns a curried equivalent of the function.
-The curried function has two unusual capabilities. -First, its arguments needn't be provided one at a time. -If f is a ternary function and g is f.curry(), the following are equivalent:
-g(1)(2)(3)
g(1)(2, 3)
g(1, 2)(3)
g(1, 2, 3)
-
-Secondly, the special placeholder value Function.__ may be used to specify "gaps", allowing partial application -of any combination of arguments, regardless of their positions. If g is as above and _ is Function.__, -the following are equivalent:
-g(1, 2, 3)
g(_, 2, 3)(1)
g(_, _, 3)(1)(2)
g(_, _, 3)(1, 2)
g(_, 2)(1)(3)
g(_, 2)(1, 3)
g(_, 2)(_, 3)(1)
-
-Returns a curried equivalent of the function.
-The curried function has two unusual capabilities. -First, its arguments needn't be provided one at a time. -If f is a ternary function and g is f.curry(), the following are equivalent:
-g(1)(2)(3)
g(1)(2, 3)
g(1, 2)(3)
g(1, 2, 3)
-
-Secondly, the special placeholder value Function.__ may be used to specify "gaps", allowing partial application -of any combination of arguments, regardless of their positions. If g is as above and _ is Function.__, -the following are equivalent:
-g(1, 2, 3)
g(_, 2, 3)(1)
g(_, _, 3)(1)(2)
g(_, _, 3)(1, 2)
g(_, 2)(1)(3)
g(_, 2)(1, 3)
g(_, 2)(_, 3)(1)
-
-Returns a new function that allows to invoke the target function only with the specified delay. -The next invocation of the function will cancel the previous.
-Returns a new function that allows to invoke the target function only with the specified delay. -The next invocation of the function will cancel the previous.
-Returns a new function that allows to invoke the target function only once
-Returns a new function that allows to invoke the target function only once
-Returns a new function based on the target that wraps the returning value into the Either structure. -If the first argument of the created function is taken null or undefined, the function returns the rejected value.
-Returns a new function based on the target that wraps the returning value into the Either structure. -If the first argument of the created function is taken null or undefined, the function returns the rejected value.
-Returns a new function based on the target that wraps the returning value into the Either structure. -If the first argument of the created function is taken null or undefined, the function returns the rejected value.
-Returns a new function based on the target that wraps the returning value into the Either structure. -If the first argument of the created function is taken null or undefined, the function returns the rejected value.
-Returns a new function based on the target that wraps the returning value into the Either structure. -If the first argument of the created function is taken null or undefined, the function returns the rejected value.
-Returns a new function based on the target that wraps the returning value into the Either structure. -If the first argument of the created function is taken null or undefined, the function returns the rejected value.
-Returns a new function based on the target that wraps the returning value into the Either structure
-Returns a new function based on the target that wraps the returning value into the Either structure
-Returns a new function based on the target that wraps the returning value into the Either structure
-Returns a new function based on the target that wraps the returning value into the Either structure
-Returns a new function that allows to invoke the target function not more often than the specified delay. -The first invoking of a function will run immediately, but all rest invokes will be merged to one and -executes after the specified delay.
-Returns a new function that allows to invoke the target function not more often than the specified delay. -The first invoking of a function will run immediately, but all rest invokes will be merged to one and -executes after the specified delay.
-options for the operation
-Returns a new function that allows to invoke the target function not more often than the specified delay. -The first invoking of a function will run immediately, but all rest invokes will be merged to one and -executes after the specified delay.
-Returns a new function that allows to invoke the target function not more often than the specified delay. -The first invoking of a function will run immediately, but all rest invokes will be merged to one and -executes after the specified delay.
-options for the operation
-If false, then a date millisecond is taken from the beginning of the now second
-If false, then a date month is taken from the beginning of the now hour
-If false, then a date second is taken from the beginning of the now minute
-If true, then the callback function takes an element descriptor instead of a value
-Strategy to iterate object properties:
-'own' - the object iterates only own properties (by default)'inherited' - the object iterates only inherited properties
-(for-in with the negative hasOwnProperty check)'all' - the object iterates inherited properties too (for-in without the hasOwnProperty check)If true, the function will iterate all object properties, but not only enumerable. -Non-enumerable properties from a prototype are ignored.
-Function that returns a key value
-element value
-element index
-Function that returns a key value
-element value
-element index
-Function that returns an element value
-element value
-element index
-Function that returns an element value
-element value
-element index
-If true, then to merge two arrays will be used a concatenation strategy (works only with the deep mode).
-Also, the parameter can be passed as a function to concatenate arrays.
If true, then object properties are copied recursively. -Also, this mode enables copying properties from a prototype.
-Strategy to resolve collisions of properties when merging:
-'all' - all properties are merged in spite of possible collisions (by default)'new' - properties with collisions aren't merged'exist' - properties without collisions aren't mergedIf true, all properties with undefined value aren't copied
-Should or shouldn't copy property descriptors too.
-If passed onlyAccessors, the descriptor properties like enumerable or configurable are ignored.
If true, the function will merge all object properties, but not only enumerable. -Non-enumerable properties from a prototype are ignored.
-If true, then merging preserve prototypes of properties
-(works only with the deep mode)
Function to filter values that support deep extending
-(works only with the deep mode)
element value
-element key
-element container
-Function to filter values that support deep extending
-(works only with the deep mode)
element value
-element key
-element container
-Function to filter values that shouldn't be copied
-element value
-element key
-element container
-Function to filter values that shouldn't be copied
-element value
-element key
-element container
-If true, then a new value will be concatenated with the old
-Character to declare the path
-Function to set a value
-Function to set a value
-If false, then the operation isn't cached
-If true, then the operation can be reverted
-Engine to send analytic events
-Group name of the task to clear
-Identifier of the task to clear
-Label of the task to clear
-Namespace of the task to clear
-If true, then a cleanup handler of the task is prevented
-If true, the operation was registered as a promise
-Reason to clear or mark the task
-Link to a task that replaces the current
-Group name of a task
-Strategy to join competitive tasks (with the same labels):
-true - all tasks are joined to the first;'replace' - all tasks are joined (replaced) to the last (only for promises).Label of a task (the previous task with the same label will be canceled)
-Handler/s of task clearing
-Handler/s of task merging: a task should merge to another task with the same label and with "join: true" strategy
-Handler/s of muted task calling. -These handlers are invoked when occurring calling the task if it is muted.
-If true, then a task namespace is marked as promisified
-Group name of a task
-Strategy to join competitive tasks (with the same labels):
-true - all tasks are joined to the first;'replace' - all tasks are joined (replaced) to the last (only for promises).Label of a task (the previous task with the same label will be canceled)
-Handler/s of task clearing
-Handler/s of task merging: a task should merge to another task with the same label and with "join: true" strategy
-Handler/s of muted task calling. -These handlers are invoked when occurring calling the task if it is muted.
-If true, then a task namespace is marked as promisified
-If false, then the proxy supports multiple callings
-Group name of a task
-Strategy to join competitive tasks (with the same labels):
-true - all tasks are joined to the first;'replace' - all tasks are joined (replaced) to the last (only for promises).Label of a task (the previous task with the same label will be canceled)
-Function to clear memory of the proxy
-Group name of a task
-Strategy to join competitive tasks (with the same labels):
-true - all tasks are joined to the first;'replace' - all tasks are joined (replaced) to the last (only for promises).Label of a task (the previous task with the same label will be canceled)
-Namespace of the proxy
-Handler/s of task clearing
-Handler/s of task merging: a task should merge to another task with the same label and with "join: true" strategy
-Handler/s of muted task calling. -These handlers are invoked when occurring calling the task if it is muted.
-If true, then a task namespace is marked as promisified
-If false, then the proxy supports multiple callings
-Performs left-to-right function composition. -The first argument may have any arity; the remaining arguments must be unary.
-If any function from parameters returns a Promise, the next function from the parameters -will take the resolved value of that promise, -the final result of calling the composition function is also a promise.
-Performs left-to-right function composition. -The first argument may have any arity; the remaining arguments must be unary.
-If any function from parameters returns a Promise, the next function from the parameters -will take the resolved value of that promise, -the final result of calling the composition function is also a promise.
-Returns a curried equivalent of the function.
-The curried function has two unusual capabilities. -First, its arguments needn't be provided one at a time. -If f is a ternary function and g is f.curry(), the following are equivalent:
-g(1)(2)(3)
g(1)(2, 3)
g(1, 2)(3)
g(1, 2, 3)
-
-Secondly, the special placeholder value Function.__ may be used to specify "gaps", allowing partial application -of any combination of arguments, regardless of their positions. If g is as above and _ is Function.__, -the following are equivalent:
-g(1, 2, 3)
g(_, 2, 3)(1)
g(_, _, 3)(1)(2)
g(_, _, 3)(1, 2)
g(_, 2)(1)(3)
g(_, 2)(1, 3)
g(_, 2)(_, 3)(1)
-
-Returns a curried equivalent of the function.
-The curried function has two unusual capabilities. -First, its arguments needn't be provided one at a time. -If f is a ternary function and g is f.curry(), the following are equivalent:
-g(1)(2)(3)
g(1)(2, 3)
g(1, 2)(3)
g(1, 2, 3)
-
-Secondly, the special placeholder value Function.__ may be used to specify "gaps", allowing partial application -of any combination of arguments, regardless of their positions. If g is as above and _ is Function.__, -the following are equivalent:
-g(1, 2, 3)
g(_, 2, 3)(1)
g(_, _, 3)(1)(2)
g(_, _, 3)(1, 2)
g(_, 2)(1)(3)
g(_, 2)(1, 3)
g(_, 2)(_, 3)(1)
-
-Returns a new function that allows to invoke the target function only with the specified delay. -The next invocation of the function will cancel the previous.
-Returns a new function that allows to invoke the target function only with the specified delay. -The next invocation of the function will cancel the previous.
-Returns a new function that allows to invoke the target function only once
-Returns a new function that allows to invoke the target function only once
-Returns a new function based on the target that wraps the returning value into the Either structure. -If the first argument of the created function is taken null or undefined, the function returns the rejected value.
-Returns a new function based on the target that wraps the returning value into the Either structure. -If the first argument of the created function is taken null or undefined, the function returns the rejected value.
-Returns a new function based on the target that wraps the returning value into the Either structure. -If the first argument of the created function is taken null or undefined, the function returns the rejected value.
-Returns a new function based on the target that wraps the returning value into the Either structure. -If the first argument of the created function is taken null or undefined, the function returns the rejected value.
-Returns a new function based on the target that wraps the returning value into the Either structure. -If the first argument of the created function is taken null or undefined, the function returns the rejected value.
-Returns a new function based on the target that wraps the returning value into the Either structure. -If the first argument of the created function is taken null or undefined, the function returns the rejected value.
-Returns a new function based on the target that wraps the returning value into the Either structure
-Returns a new function based on the target that wraps the returning value into the Either structure
-Returns a new function based on the target that wraps the returning value into the Either structure
-Returns a new function based on the target that wraps the returning value into the Either structure
-Returns a new function that allows to invoke the target function not more often than the specified delay. -The first invoking of a function will run immediately, but all rest invokes will be merged to one and -executes after the specified delay.
-Returns a new function that allows to invoke the target function not more often than the specified delay. -The first invoking of a function will run immediately, but all rest invokes will be merged to one and -executes after the specified delay.
-options for the operation
-Returns a new function that allows to invoke the target function not more often than the specified delay. -The first invoking of a function will run immediately, but all rest invokes will be merged to one and -executes after the specified delay.
-Returns a new function that allows to invoke the target function not more often than the specified delay. -The first invoking of a function will run immediately, but all rest invokes will be merged to one and -executes after the specified delay.
-options for the operation
-Performs left-to-right function composition. -The first argument may have any arity; the remaining arguments must be unary.
-If any function from parameters returns a Promise, the next function from the parameters -will take the resolved value of that promise, -the final result of calling the composition function is also a promise.
-Performs left-to-right function composition. -The first argument may have any arity; the remaining arguments must be unary.
-If any function from parameters returns a Promise, the next function from the parameters -will take the resolved value of that promise, -the final result of calling the composition function is also a promise.
-Returns a curried equivalent of the function.
-The curried function has two unusual capabilities. -First, its arguments needn't be provided one at a time. -If f is a ternary function and g is f.curry(), the following are equivalent:
-g(1)(2)(3)
g(1)(2, 3)
g(1, 2)(3)
g(1, 2, 3)
-
-Secondly, the special placeholder value Function.__ may be used to specify "gaps", allowing partial application -of any combination of arguments, regardless of their positions. If g is as above and _ is Function.__, -the following are equivalent:
-g(1, 2, 3)
g(_, 2, 3)(1)
g(_, _, 3)(1)(2)
g(_, _, 3)(1, 2)
g(_, 2)(1)(3)
g(_, 2)(1, 3)
g(_, 2)(_, 3)(1)
-
-Returns a curried equivalent of the function.
-The curried function has two unusual capabilities. -First, its arguments needn't be provided one at a time. -If f is a ternary function and g is f.curry(), the following are equivalent:
-g(1)(2)(3)
g(1)(2, 3)
g(1, 2)(3)
g(1, 2, 3)
-
-Secondly, the special placeholder value Function.__ may be used to specify "gaps", allowing partial application -of any combination of arguments, regardless of their positions. If g is as above and _ is Function.__, -the following are equivalent:
-g(1, 2, 3)
g(_, 2, 3)(1)
g(_, _, 3)(1)(2)
g(_, _, 3)(1, 2)
g(_, 2)(1)(3)
g(_, 2)(1, 3)
g(_, 2)(_, 3)(1)
-
-Returns a new function that allows to invoke the target function only with the specified delay. -The next invocation of the function will cancel the previous.
-Returns a new function that allows to invoke the target function only with the specified delay. -The next invocation of the function will cancel the previous.
-Returns a new function that allows to invoke the target function only once
-Returns a new function that allows to invoke the target function only once
-Returns a new function based on the target that wraps the returning value into the Either structure. -If the first argument of the created function is taken null or undefined, the function returns the rejected value.
-Returns a new function based on the target that wraps the returning value into the Either structure. -If the first argument of the created function is taken null or undefined, the function returns the rejected value.
-Returns a new function based on the target that wraps the returning value into the Either structure. -If the first argument of the created function is taken null or undefined, the function returns the rejected value.
-Returns a new function based on the target that wraps the returning value into the Either structure. -If the first argument of the created function is taken null or undefined, the function returns the rejected value.
-Returns a new function based on the target that wraps the returning value into the Either structure. -If the first argument of the created function is taken null or undefined, the function returns the rejected value.
-Returns a new function based on the target that wraps the returning value into the Either structure. -If the first argument of the created function is taken null or undefined, the function returns the rejected value.
-Returns a new function based on the target that wraps the returning value into the Either structure
-Returns a new function based on the target that wraps the returning value into the Either structure
-Returns a new function based on the target that wraps the returning value into the Either structure
-Returns a new function based on the target that wraps the returning value into the Either structure
-Returns a new function that allows to invoke the target function not more often than the specified delay. -The first invoking of a function will run immediately, but all rest invokes will be merged to one and -executes after the specified delay.
-Returns a new function that allows to invoke the target function not more often than the specified delay. -The first invoking of a function will run immediately, but all rest invokes will be merged to one and -executes after the specified delay.
-options for the operation
-Returns a new function that allows to invoke the target function not more often than the specified delay. -The first invoking of a function will run immediately, but all rest invokes will be merged to one and -executes after the specified delay.
-Returns a new function that allows to invoke the target function not more often than the specified delay. -The first invoking of a function will run immediately, but all rest invokes will be merged to one and -executes after the specified delay.
-options for the operation
-Group name of the task to clear
-Identifier of the task to clear
-Label of the task to clear
-If true, then a cleanup handler of the task is prevented
-Group name of the task to clear
-Identifier of the task to clear
-Label of the task to clear
-Namespace of the proxy to clear
-If true, then a cleanup handler of the task is prevented
-Registered task object
-Function to clear the task
-Group name the task
-Task unique identifier
-Label of the task
-True if the task is muted
-Raw task object
-Name of the raw task object
-List of clear handlers
-List of complete handlers:
-[0] - onFulfilled -[1] - onRejected
-True if the task is paused
-Queue of pending handlers -(if the task is paused)
-Unregisters the task
-Group name of a task
-Strategy to join competitive tasks (with the same labels):
-true - all tasks are joined to the first;'replace' - all tasks are joined (replaced) to the last (only for promises).Label of a task (the previous task with the same label will be canceled)
-Handler/s of task clearing
-Handler/s of task merging: a task should merge to another task with the same label and with "join: true" strategy
-Handler/s of muted task calling. -These handlers are invoked when occurring calling the task if it is muted.
-Additional options for the emitter
-If true, then a task namespace is marked as promisified
-If false, then the proxy supports multiple callings
-Group name of a task
-Strategy to join competitive tasks (with the same labels):
-true - all tasks are joined to the first;'replace' - all tasks are joined (replaced) to the last (only for promises).Label of a task (the previous task with the same label will be canceled)
-Handler/s of task clearing
-Handler/s of task merging: a task should merge to another task with the same label and with "join: true" strategy
-Handler/s of muted task calling. -These handlers are invoked when occurring calling the task if it is muted.
-Additional options for the emitter
-If true, then a task namespace is marked as promisified
-Group name of a task
-Event handler (the result of invoking is provided to a promise)
-Strategy to join competitive tasks (with the same labels):
-true - all tasks are joined to the first;'replace' - all tasks are joined (replaced) to the last (only for promises).Label of a task (the previous task with the same label will be canceled)
-Additional options for the emitter
-Name of a destructor method
-Group name of a task
-Strategy to join competitive tasks (with the same labels):
-true - all tasks are joined to the first;'replace' - all tasks are joined (replaced) to the last (only for promises).Label of a task (the previous task with the same label will be canceled)
-Namespace of the proxy
-Handler/s of muted promise resolving. -These handlers are invoked when occurring resolving the promise if it is muted.
-Name of a destructor method
-Group name of a task
-Strategy to join competitive tasks (with the same labels):
-true - all tasks are joined to the first;'replace' - all tasks are joined (replaced) to the last (only for promises).Label of a task (the previous task with the same label will be canceled)
-Function to clear memory of the proxy
-Name of a destructor method
-Group name of a task
-Strategy to join competitive tasks (with the same labels):
-true - all tasks are joined to the first;'replace' - all tasks are joined (replaced) to the last (only for promises).Label of a task (the previous task with the same label will be canceled)
-Namespace of the proxy
-Handler/s of task clearing
-Handler/s of task merging: a task should merge to another task with the same label and with "join: true" strategy
-Handler/s of muted task calling. -These handlers are invoked when occurring calling the task if it is muted.
-If true, then a task namespace is marked as promisified
-If false, then the proxy supports multiple callings
-Group name of a task
-Strategy to join competitive tasks (with the same labels):
-true - all tasks are joined to the first;'replace' - all tasks are joined (replaced) to the last (only for promises).Label of a task (the previous task with the same label will be canceled)
-Timeout value for the native requestIdleCallback function
-Group name of a task
-Strategy to join competitive tasks (with the same labels):
-true - all tasks are joined to the first;'replace' - all tasks are joined (replaced) to the last (only for promises).Label of a task (the previous task with the same label will be canceled)
-Handler/s of task clearing
-Handler/s of task merging: a task should merge to another task with the same label and with "join: true" strategy
-Handler/s of muted task calling. -These handlers are invoked when occurring calling the task if it is muted.
-If true, then a task namespace is marked as promisified
-Timeout value for the native requestIdleCallback function
-Delay value in milliseconds
-Group name of a task
-Strategy to join competitive tasks (with the same labels):
-true - all tasks are joined to the first;'replace' - all tasks are joined (replaced) to the last (only for promises).Label of a task (the previous task with the same label will be canceled)
-Subscribes for mutations of the specified cache object
-mutation method to subscribe
-object whose mutations we are handling
-callback that invokes when occurring mutations
-Event emitter to produce mutation events
-Number of elements within the cache
-Returns an iterator by the cache keys
-Clears the cache by the specified filter and returns a map of removed keys
-Returns an iterator from the cache that produces pairs of keys and values
-Returns a value from the cache by the specified key
-Returns true if a value by the specified key exists in the cache
-Returns an iterator by the cache keys
-Removes a value from the cache by the specified key
-Returns an iterator by the cache values
-How to load cache items from the persistent storage:
-'onInit' - the whole stored data will be loaded during the cache initialization;'onDemand' - each stored item will be loaded from the cache only on the first touch, i.e. on-demand or lazily;'onOfflineDemand' - each stored item will be loaded from the cache only on the first touch and only if
- there is no internet connection (the strategy is useful to create net-first offline storages)Default time to expire a cache item in the persistent storage
-Event emitter to produce mutation events
-Number of elements within the cache
-Returns an iterator by the cache keys
-Clears the cache by the specified filter and returns a map of removed keys
-Returns an iterator from the cache that produces pairs of keys and values
-Returns a value from the cache by the specified key
-Returns true if a value by the specified key exists in the cache
-Returns an iterator by the cache keys
-Removes a value from the cache by the specified key
-Removes the ttl descriptor from a cache item by the specified key.
-The method returns true if the operation has been successful, otherwise false
-(the requested item hasn't been found).
Saves a value to the cache by the specified key
-Returns an iterator by the cache values
-Base interface for a cache data structure
-value type
-key type (string by default)
Number of elements within the cache
-Returns an iterator by the cache keys
-Clears the cache by the specified filter and returns a map of removed keys
-Returns an iterator from the cache that produces pairs of keys and values
-Returns a value from the cache by the specified key
-Returns true if a value by the specified key exists in the cache
-Returns an iterator by the cache keys
-Removes a value from the cache by the specified key
-Saves a value to the cache by the specified key
-Returns an iterator by the cache values
-Base interface of a data provider
-Provider alias
-Event emitter to broadcast provider events
-Full name of the provider including a namespace
-Add new data to the provider. -This method is similar for a POST request.
-Returns the base part of URL of any request
-Sets the base part of URL for any request. -This method returns a new provider object with context.
-Deletes data of the provider by a query. -This method is similar for a DELETE request.
-Drops the request cache of the current provider
-Requests the provider for data by a query. -This method is similar for a GET request.
-Returns the custom HTTP request method of any request
-Sets the custom HTTP request method for any request. -This method returns a new provider object with context.
-Returns the custom logical name of any request. -If a request has the name, then it will fire an event with the same name after successful receiving.
-Sets the custom logical name for any request. -If a request has the name, then it will fire an event with the same name after successful receiving. -This method returns a new provider object with context.
-Checks accessibility of the provider by a query. -This method is similar for a HEAD request.
-Sends custom data to the provider without any logically effect. -This method is similar for a POST request.
-Updates data of the provider by a query. -This method is similar for a PUT request.
-Returns the full URL of any request
-Sets an extra URL part for any request (it is concatenated with the base part of URL). -This method returns a new provider object with context.
-Extractor that gets details from an error of type E
Constructor function of an error
-Extracts details from the passed error
-an error, which details should be extracted
-Name of a function/method/etc. that need to use instead of the current -or an object with additional options of the alternative
-Type of warn context
-Indicates that a function/method/etc. was moved to a different file, but its interface still actual, -the value contains a source path after moving
-Additional information
-Indicates that a function/method/etc. was renamed, but its interface still actual, -the value contains a name after renaming
-Name of a function/method/etc. that need to use instead of the current -or an object with additional options of the alternative
-Type of warn context
-Indicates that a function/method/etc. was moved to a different file, but its interface still actual, -the value contains a source path after moving
-Name of an expression to wrap
-Additional information
-Indicates that a function/method/etc. was renamed, but its interface still actual, -the value contains a name after renaming
-Type of expression to wrap
-A type of parsed structure in which the picking takes place
-If true the filtration will return all matched filter results, otherwise only the first match will be returned
-API for an asynchronous storage
-Returns an async storage object by the specified namespace
-KV-storage engine
-API for a synchronous storage
-Clears the storage by the specified filter and returns a list of removed keys. -Notice, the method can take a list of additional parameters provided to the used storage' engine.
-Returns a value from the storage by the specified key.
-The returning value automatically parses by using Object.parse from a string to equivalent JS value, i.e.,
-'1' will be parsed to 1, 'true' to true, '2021-07-09T08:15:57.753Z' to Date, etc.
Notice, the method can take a list of additional parameters provided to the used storage' engine.
-Returns true if a value by the specified key exists in the storage. -Notice, the method can take a list of additional parameters provided to the used storage' engine.
-Returns a storage object by the specified namespace
-Removes a value from the storage by the specified key. -Notice, the method can take a list of additional parameters provided to the used storage' engine.
-Saves a value to the storage by the specified key.
-The value to parse automatically serializes to a string by using Object.trySerialize, i.e.,
-arrays and dictionaries will be serialized to JSON, etc.
Notice, the method can take a list of additional parameters provided to the used storage' engine.
-Clears the storage by the specified filter and returns a list of removed keys. -Notice, the method can take a list of additional parameters provided to the used storage' engine.
-Returns a value from the storage by the specified key.
-The returning value automatically parses by using Object.parse from a string to equivalent JS value, i.e.,
-'1' will be parsed to 1, 'true' to true, '2021-07-09T08:15:57.753Z' to Date, etc.
Notice, the method can take a list of additional parameters provided to the used storage' engine.
-Returns true if a value by the specified key exists in the storage. -Notice, the method can take a list of additional parameters provided to the used storage' engine.
-Removes a value from the storage by the specified key. -Notice, the method can take a list of additional parameters provided to the used storage' engine.
-Saves a value to the storage by the specified key.
-The value to parse automatically serializes to a string by using Object.trySerialize, i.e.,
-arrays and dictionaries will be serialized to JSON, etc.
Notice, the method can take a list of additional parameters provided to the used storage' engine.
-Logs a message with the error level and specified context
-log record context
-Logs a message with the error level and specified context
-log record context
-thrown error
-Logs a message with the info level and specified context
-log record context
-Returns a new logging function with the specified namespace
-Logs a message with the warning level and specified context
-log record context
-Logs a message with the warning level and specified context
-log record context
-thrown error
-Recurrent structure that represents detailed error information
-Information of a caused error
-Error's details that could be extracted from it via error details extractors
-General info about an error. -Using only for cause errors and not for the root one.
-Processes the events -(if it has data to pass to the next middleware, calls the next callback)
-How long to store a checking result in the local cache
-How often need to check the online connection (ms)
-Timeout of a connection checking request
-URL to check the online connection -(with the "browser.request" engine can be used only image URL-s)
-How often to update the last online connection time
-True, if we need to save a time of the last online connection in the local cache
-The maximum number of retries to check the online connection
-The option enables or disables collapsing of mutation events.
-When it toggles to true, all mutation events fire as if they occur on top properties of the watchable object.
const {proxy} = watch({a: {b: {c: 1}}}, {collapse: true, deep: true}, (mutations) => {
mutations.forEach(([value, oldValue, info]) => {
console.log(value, oldValue, info.path);
});
});
// {b: {c: 2}} {b: {c: 2}} ['a', 'b', 'c']
proxy.a.b.c = 2;
-
-When it toggles to false, and the watcher binds to the specified path, the callback takes a list of mutations.
-Otherwise, the callback takes only the last mutation.
const {proxy} = watch({a: {b: {c: 1}}}, 'a.b', {collapse: false}, (mutations) => {
mutations.forEach(([value, oldValue, info]) => {
console.log(value, oldValue, info.path, info.originalPath);
});
});
// 2 1 ['a', 'b'] ['a', 'b', 'c']
proxy.a.b.c = 2;
const {proxy: proxy2} = watch({a: {b: {c: 1}}}, 'a.b', (value, oldValue, info) => {
console.log(value, oldValue, info.path, info.originalPath);
});
// {c: 2} {c: 2} ['a', 'b'] ['a', 'b', 'c']
proxy2.a.b.c = 2;
-
-If true, then the callback of changing is also fired on mutations of nested properties
-When providing the specific path to watch, this parameter can contain a list of dependencies for the watching path. -This parameter can help to watch accessors.
-const obj = {
get foo() {
return this.bla * this.baz;
},
bla: 2,
baz: 3
};
const {proxy} = watch(obj, 'foo', {dependencies: ['bla', 'baz']}, (value, oldValue, info) => {
console.log(value, oldValue, info.path, info.originalPath, info.parent);
});
// This mutation will invoke our callback
proxy.bla++;
-
-When providing the specific path to watch, this parameter can contain an object or Map with lists of
-dependencies to watch.
const obj = {
foo: {
get value() {
return this.bla * this.baz;
}
},
bla: 2,
baz: 3
};
const depsAsObj = {
'foo.value': ['bla', 'baz']
};
const {proxy: proxy1} = watch(obj, {dependencies: depsAsObj}, (mutations) => {
mutations.forEach(([value, oldValue, info]) => {
console.log(value, oldValue, info.path, info.originalPath, info.parent);
});
});
// This mutation will fire an additional event for `foo.value`
proxy1.bla++;
const depsAsMap = new Map([
[
// A path to the property with dependencies
['foo', 'value'],
// Dependencies
['bla', 'baz']
]
]);
const {proxy: proxy2} = watch(obj, {dependencies: depsAsMap}, (mutations) => {
mutations.forEach(([value, oldValue, info]) => {
console.log(value, oldValue, info.path, info.originalPath, info.parent);
});
});
proxy2.baz++;
-
-Watch engine to use. -By default, will be used proxy if supported, otherwise accessors.
-A filter function for mutation events. -The function allows skipping some mutation events.
-If true, then all mutation events will be fired immediately. -Notice, with enabling this option, the callback changes its interface:
-// Before
type Cb = (mutations: [[unknown, unknown, WatchHandlerParams]]) => any;
// After
type CbWithImmediate = (newValue: unknown, oldValue: unknown, info: WatchHandlerParams) => any;
-
-A function that takes a path of the mutation event and returns a new path. -The function is used when you want to mask one mutation to another one.
-List of postfixes for paths to watch. -This parameter can help to watch accessors.
-List of prefixes for paths to watch. -This parameter can help to watch accessors.
-Link to an object that should connect with the watched object, i.e., -changing of properties of the tied object, will also emit mutation events
-If true, then the callback of changing is also fired on mutations of properties from prototypes
-Parameters of a mutation event
-True if the mutation has occurred on a prototype of the watched object
-Link to the object that is watched
-Path to a property that was changed
-Link to the root object of watching
-Link to the top property of watching -(the first level property of the root)
-Extended parameters of a mutation event
-True if the mutation has occurred on a prototype of the watched object
-Link to the object that is watched
-The original path to a property that was changed.
-Information about the parent mutation event
-Path to a property that was changed
-Link to the root object of watching
-Link to the top property of watching -(the first level property of the root)
-The option enables or disables collapsing of mutation events.
-When it toggles to true, all mutation events fire as if they occur on top properties of the watchable object.
const {proxy} = watch({a: {b: {c: 1}}}, {collapse: true, deep: true}, (mutations) => {
mutations.forEach(([value, oldValue, info]) => {
console.log(value, oldValue, info.path);
});
});
// {b: {c: 2}} {b: {c: 2}} ['a', 'b', 'c']
proxy.a.b.c = 2;
-
-When it toggles to false, and the watcher binds to the specified path, the callback takes a list of mutations.
-Otherwise, the callback takes only the last mutation.
const {proxy} = watch({a: {b: {c: 1}}}, 'a.b', {collapse: false}, (mutations) => {
mutations.forEach(([value, oldValue, info]) => {
console.log(value, oldValue, info.path, info.originalPath);
});
});
// 2 1 ['a', 'b'] ['a', 'b', 'c']
proxy.a.b.c = 2;
const {proxy: proxy2} = watch({a: {b: {c: 1}}}, 'a.b', (value, oldValue, info) => {
console.log(value, oldValue, info.path, info.originalPath);
});
// {c: 2} {c: 2} ['a', 'b'] ['a', 'b', 'c']
proxy2.a.b.c = 2;
-
-If true, then the callback of changing is also fired on mutations of nested properties
-When providing the specific path to watch, this parameter can contain a list of dependencies for the watching path. -This parameter can help to watch accessors.
-const obj = {
get foo() {
return this.bla * this.baz;
},
bla: 2,
baz: 3
};
const {proxy} = watch(obj, 'foo', {dependencies: ['bla', 'baz']}, (value, oldValue, info) => {
console.log(value, oldValue, info.path, info.originalPath, info.parent);
});
// This mutation will invoke our callback
proxy.bla++;
-
-When providing the specific path to watch, this parameter can contain an object or Map with lists of
-dependencies to watch.
const obj = {
foo: {
get value() {
return this.bla * this.baz;
}
},
bla: 2,
baz: 3
};
const depsAsObj = {
'foo.value': ['bla', 'baz']
};
const {proxy: proxy1} = watch(obj, {dependencies: depsAsObj}, (mutations) => {
mutations.forEach(([value, oldValue, info]) => {
console.log(value, oldValue, info.path, info.originalPath, info.parent);
});
});
// This mutation will fire an additional event for `foo.value`
proxy1.bla++;
const depsAsMap = new Map([
[
// A path to the property with dependencies
['foo', 'value'],
// Dependencies
['bla', 'baz']
]
]);
const {proxy: proxy2} = watch(obj, {dependencies: depsAsMap}, (mutations) => {
mutations.forEach(([value, oldValue, info]) => {
console.log(value, oldValue, info.path, info.originalPath, info.parent);
});
});
proxy2.baz++;
-
-Watch engine to use. -By default, will be used proxy if supported, otherwise accessors.
-A filter function for mutation events. -The function allows skipping some mutation events.
-If true, then all mutation events will be fired immediately. -Notice, with enabling this option, the callback changes its interface:
-// Before
type Cb = (mutations: [[unknown, unknown, WatchHandlerParams]]) => any;
// After
type CbWithImmediate = (newValue: unknown, oldValue: unknown, info: WatchHandlerParams) => any;
-
-A function that takes a path of the mutation event and returns a new path. -The function is used when you want to mask one mutation to another one.
-List of postfixes for paths to watch. -This parameter can help to watch accessors.
-List of prefixes for paths to watch. -This parameter can help to watch accessors.
-Link to an object that should connect with the watched object, i.e., -changing of properties of the tied object, will also emit mutation events
-If true, then the callback of changing is also fired on mutations of properties from prototypes
-A proxy object to watch
-Deletes a watchable value from the proxy object by the specified path.
-To restore watching for this property, use set.
Sets a new watchable value for the proxy object by the specified path
-Cancels watching for the proxy object
-True if the property to watch is taken from a prototype
-Base path to object properties
-Link to the root object of watching
-Link to the top object of watching -(the first level property of the root)
-Watch options
-True if the property to watch is taken from a prototype
-Base path to object properties
-Link to the root object of watching
-Link to the top object of watching -(the first level property of the root)
-Watch options
-Returns an instance of the scoped performance timer for a specific group
-group name, that timer should belong to. It appears at the beginning of all time marks namespaces.
-scope name, that defines the scope. It doesn't appear in any time mark namespaces.
-Returns an instance of the performance timer for a specific group
-group name, that timer should belong to. It appears at the beginning of all time marks namespaces.
-An engine to send time metrics to the target
-Returns a timestamp from the application start
-Sends metrics by the specified parameters
-metrics name
-difference between two moments of time
-Performance timer
-Finishes started measurement by its identifier.
-Works together with the start method.
id of the metrics to stop
-Measures difference between the current moment and the time origin of a corresponding timers runner
-full name of the metrics
-Returns a new instance of the performance timer but with the passed suffix
-namespace suffix
-Starts measuring for the specified name and returns an identifier of the metrics
-full name of the metrics
-A factory to create performance timers
-Returns an instance of the scoped performance timer for a specific group. -The scoped timer is a timer that measures timestamps from the moment of the first scope using. -This moment is called the time origin.
-group name, that timer should belong to. It appears at the beginning of all time marks namespaces.
-scope name, that defines the scope. It doesn't appear in any time mark namespaces.
-Returns an instance of the performance timer for a specific group
-group name, that timer should belong to. It appears at the beginning of all time marks namespaces.
-Value from the pool
-Destroys the resource instead of returning it to the pool
-Returns the resource to the pool
-extra arguments to pass to the onFree hook handler
A function to calculate a hash string for the specified arguments
-The maximum number of resources that the pool can contain
-Handler: taking some resource via borrow methods
Handler: clearing of all pool resources
-Handler: releasing of some resource
-Handler: taking some resource via take methods
A function to destroy one resource from the pool
-Number of resources to create at pull initialization
-Value from the pool
-Destroys the resource instead of returning it to the pool
-Returns the resource to the pool
-extra arguments to pass to the onFree hook handler
Returns a value from the storage by the specified key.
-The returning value automatically parses by using Object.parse from a string to equivalent JS value, i.e.,
-'1' will be parsed to 1, 'true' to true, '2021-07-09T08:15:57.753Z' to Date, etc.
Notice, the method can take a list of additional parameters provided to the used storage' engine.
-Saves a value to the storage by the specified key.
-The value to parse automatically serializes to a string by using Object.trySerialize, i.e.,
-arrays and dictionaries will be serialized to JSON, etc.
Notice, the method can take a list of additional parameters provided to the used storage' engine.
-Extra arguments to pass to the promise constructor
-Promise constructor
-Promise constructor executor
-A factory to create an internal queue to store elements
-The maximum number of concurrent workers
-Hash function for a task
-How often to update task statuses (in milliseconds)
-A factory to create the internal queue to store elements
-Meta parameters for the engine
-Options for a request
-response data type
-A map of API parameters.
-These parameters apply if the original request URL is not absolute, and they can be used to customize the
-base API URL depending on the runtime environment. If you define the base API URL via
-config#api or globalOpts.api, these parameters will be mapped on it.
Request body.
-Mind, not every HTTP method can send data in this way. For instance,
-GET or HEAD requests can send data only with URLs (@see query).
Unique cache identifier: it can be useful to create request factories with isolated cache storages
-List of request methods that support caching
-Strategy of caching for requests that support caching (by default, only GET requests can be cached):
-'forever' - caches all requests and stores their values forever within the active session or
- until the cache expires (if cacheTTL is specified);'queue' - caches all requests, but more frequent requests will push less frequent requests;'never' - never caches any requests;Value in milliseconds that indicates how long a request value should keep in the cache -(all requests are stored within the active session without expiring by default)
-Mime type of the request data (if not specified, it will be cast dynamically)
-Enables providing of credentials for cross-domain requests. -Also, you can manage to omit any credentials if the used request engine supports it.
-A function (or a sequence of functions) takes the current request response data -and returns new data to respond. If you provide a sequence of functions, -the first function will pass a result to the next function from the sequence, etc.
-A function (or a sequence of functions) takes the current request data -and returns new data to request. If you provide a sequence of functions, -the first function will pass a result in the next function from the sequence, etc.
-A request engine to use.
-The engine - is a simple function that takes request parameters and returns an abortable promise resolved with the
-core/request/response instance. Mind, some engines provide extra features. For instance, you can listen to upload
-progress events with the XHR engine. Or, you can parse responses in a stream form with the Fetch engine.
Additional HTTP request headers.
-You can provide them as a simple dictionary or an instance of the Headers class.
-Also, you can pass headers as an instance of the core/request/headers class.
A meta flag that indicates that the request is important: is usually used with middlewares to indicate that -the request needs to be executed as soon as possible
-Reviver function for JSON.parse or false to disable defaults.
-By default, it parses some strings as Date instances.
A dictionary with some extra parameters for the request: is usually used with middlewares to provide -domain-specific information
-HTTP method to create a request
-A dictionary or iterable value with middleware functions: -functions take an environment of request parameters and can modify theirs.
-Please notice that the order of middleware depends on the structure you use. -Also, if at least one of the middlewares returns a function, invoking this function -will be returned as the request result. It can be helpful to organize mocks of data and -other similar cases when you don't want to execute a real request.
-Enables support of offline caching.
-By default, a request can only be taken from a cache if there is no network.
-You can customize this logic by providing a custom cache object with the core/cache/decorators/persistent
-decorator.
Value in milliseconds that indicates how long a request value should keep in the offline cache
-A list of status codes (or a single code) that match successful operation. -Also, you can pass a range of codes.
-Request parameters that will be serialized to a string and passed via a request URL.
-To customize how to encode data to a query string, see querySerializer.
Type of the response data -(if not specified, it will be cast dynamically from the response headers):
-'text' - result is interpreted as a simple string;'json' - result is interpreted as a JSON object;'document' - result is interpreted as an XML/HTML document;'formData' - result is interpreted as a FormData object;'blob' - result is interpreted as a Blob object;'arrayBuffer' - result is interpreted as a raw array buffer;'object' - result is interpreted "as is" without any converting.Options to retry bad requests or a number of maximum request retries
-A function (or a sequence of functions) takes the current request response data chunk -and yields a new chunk to respond via an async iterator. If you provide a sequence of functions, -the first function will pass a result to the next function from the sequence, etc. -This parameter is used when you're parsing responses in a stream form.
-Value in milliseconds for a request timeout
-Returns a serialized value of the specified query object
-A map of API parameters.
-These parameters apply if the original request URL is not absolute, and they can be used to customize the
-base API URL depending on the runtime environment. If you define the base API URL via
-config#api or globalOpts.api, these parameters will be mapped on it.
Value for an API authorization part
-Value for an API domain level 2 part
-Value for an API domain level 3 part
-Value for an API domain level 4 part
-Value for an API domain level 5 part
-Value for an API domain level 6 part
-Value for an API namespace part: it follows after '/' character
-Value for an API api port
-API protocol
-The direct value of API URL. -If this parameter is defined, all other parameters will be ignored.
-Value for an API domain zone part
-Request engine
-A flag indicates that the active requests with the same request hash can be merged
-If true, then the promise was aborted
-Handler of the native promise rejection that was raised by a reason of abort
-Handler of the native promise rejection
-Handler of the native promise resolving
-Number of pending child promises
-Internal native promise instance
-Actual promise state
-Resolved promise value
-True if the current promise is pending
-Aborts the current promise (the promise will be rejected)
-Executes a function with the specified parameters
-arguments for the function
-Attaches a handler for the promise' rejected state. -The method returns a new promise that will be resolved with a value that returns from the passed handler.
-Attaches a common callback for the promise fulfilled and rejected states. -The method returns a new promise with the state and value from the current. -A value from the passed callback will be ignored unless it equals a rejected promise or exception.
-Attaches handlers for the promise fulfilled and/or rejected states. -The method returns a new promise that will be resolved with a value that returns from the passed handlers.
-Options to retry bad requests
-response data type
-Maximum number of attempts to request
-Returns a number in milliseconds (or a promise) to wait before the next attempt. -If the function returns false, it will prevent all further attempts.
-current attempt number
-error object
-A map of API parameters.
-These parameters apply if the original request URL is not absolute, and they can be used to customize the
-base API URL depending on the runtime environment. If you define the base API URL via
-config#api or globalOpts.api, these parameters will be mapped on it.
Request body.
-Mind, not every HTTP method can send data in this way. For instance,
-GET or HEAD requests can send data only with URLs (@see query).
Unique cache identifier: it can be useful to create request factories with isolated cache storages
-List of request methods that support caching
-Strategy of caching for requests that support caching (by default, only GET requests can be cached):
-'forever' - caches all requests and stores their values forever within the active session or
- until the cache expires (if cacheTTL is specified);'queue' - caches all requests, but more frequent requests will push less frequent requests;'never' - never caches any requests;Value in milliseconds that indicates how long a request value should keep in the cache -(all requests are stored within the active session without expiring by default)
-Mime type of the request data (if not specified, it will be cast dynamically)
-Enables providing of credentials for cross-domain requests. -Also, you can manage to omit any credentials if the used request engine supports it.
-A function (or a sequence of functions) takes the current request response data -and returns new data to respond. If you provide a sequence of functions, -the first function will pass a result to the next function from the sequence, etc.
-A function (or a sequence of functions) takes the current request data -and returns new data to request. If you provide a sequence of functions, -the first function will pass a result in the next function from the sequence, etc.
-A request engine to use.
-The engine - is a simple function that takes request parameters and returns an abortable promise resolved with the
-core/request/response instance. Mind, some engines provide extra features. For instance, you can listen to upload
-progress events with the XHR engine. Or, you can parse responses in a stream form with the Fetch engine.
Additional HTTP request headers.
-You can provide them as a simple dictionary or an instance of the Headers class.
-Also, you can pass headers as an instance of the core/request/headers class.
A meta flag that indicates that the request is important: is usually used with middlewares to indicate that -the request needs to be executed as soon as possible
-Reviver function for JSON.parse or false to disable defaults.
-By default, it parses some strings as Date instances.
A dictionary with some extra parameters for the request: is usually used with middlewares to provide -domain-specific information
-HTTP method to create a request
-A dictionary or iterable value with middleware functions: -functions take an environment of request parameters and can modify theirs.
-Please notice that the order of middleware depends on the structure you use. -Also, if at least one of the middlewares returns a function, invoking this function -will be returned as the request result. It can be helpful to organize mocks of data and -other similar cases when you don't want to execute a real request.
-Enables support of offline caching.
-By default, a request can only be taken from a cache if there is no network.
-You can customize this logic by providing a custom cache object with the core/cache/decorators/persistent
-decorator.
Value in milliseconds that indicates how long a request value should keep in the offline cache
-A list of status codes (or a single code) that match successful operation. -Also, you can pass a range of codes.
-Original path that was passed into the request function
-Request parameters that will be serialized to a string and passed via a request URL.
-To customize how to encode data to a query string, see querySerializer.
Type of the response data -(if not specified, it will be cast dynamically from the response headers):
-'text' - result is interpreted as a simple string;'json' - result is interpreted as a JSON object;'document' - result is interpreted as an XML/HTML document;'formData' - result is interpreted as a FormData object;'blob' - result is interpreted as a Blob object;'arrayBuffer' - result is interpreted as a raw array buffer;'object' - result is interpreted "as is" without any converting.Options to retry bad requests or a number of maximum request retries
-A function (or a sequence of functions) takes the current request response data chunk -and yields a new chunk to respond via an async iterator. If you provide a sequence of functions, -the first function will pass a result to the next function from the sequence, etc. -This parameter is used when you're parsing responses in a stream form.
-Value in milliseconds for a request timeout
-URL to make request
-Returns a serialized value of the specified query object
-If true, then nested properties will be decoded by using [] syntax
If false, then all parsed values won't be converted from a string
-If false, then the passed string won't be decoded by using decodeURIComponent
Separator for nested properties
-If true, then nested properties will be encoded by using [] syntax
If false, then the result string won't be encoded by using encodeURIComponent
Separator for nested properties
-Filters values that shouldn't be serialized. -By default, the function skip all values with null-s and empty strings.
-property key
-accumulated property path ({a: {b: 1}} => 'a_b')
This module provides extensions for a bunch of builtin objects, such as String, Number, etc. -The module is uploaded to the runtime automatically, you don't need to require it.
-Returns a new function based on the specified with adding as the first parameter the passed object
-Parameters for the internationalization function
-Overrides properties of the specified type or interface. -Don't use this helper if you simply extend one type from another, i.e. without overriding properties.
-original type
-type with the overridden properties
-any function
-Wraps the specified function to return a value as Promise
-String pluralization constants that can be used instead of numbers
-Returns a new non-abstract class from the specified abstract class where methods can have the default implementation. -The default implementations are taken from the static methods that match by names with the class's methods.
-Creates an interface based on the specified type or interface but every property can be edited
-Converts the specified unknown value to any
-Converts the specified unknown value to any
-Creates a function to internationalize strings in an application based on the given locale and keyset. -Keyset allows you to share the same keys in different contexts. -For example, the key "Next" may have a different value in different components of the application, therefore, -we can use the name of the component as a keyset value.
-the name of keyset or array with names of keysets to use. - If passed as an array, the priority of the cases will be arranged in the order of the elements, - the first one will have the highest priority.
-Creates a function to internationalize strings in an application based on the given locale and keyset. -Keyset allows you to share the same keys in different contexts. -For example, the key "Next" may have a different value in different components of the application, therefore, -we can use the name of the component as a keyset value.
-Global i18n function (can be used as a string tag or simple function)
-STDERR wrapper
-STDERR wrapper
-This module provides options to configure the application.
-Extends the config object with additional objects
-This module provides API to work with analytic services.
-Each of the analytic services should define its own engine within the core/analytics/engines folder.
Notice, there is no implementation for any analytic services. -You have to create it by yourself.
- - -Create a new file within the engines folder and expose it from the index file.
-Let's create a simple engine for Google Analytics.
core/analytics/engines/ga.ts
-export default function sendEvent(event: string, hint?: string, extra?: [...string, Dictionary?]) {
ga(event, hint, ...extra);
};
-
-core/analytics/engines
-export { default } from 'core/analytics/engines/ga';
-
-Sends the specified analytic event
-This module provides a class to control asynchronous operations.
-import Async from 'core/async';
const
watcher = new Async();
watcher.setTimeout(() => {
console.log(1);
}, 100, {group: 'foo'});
watcher.setTimeout(() => {
console.log(2);
}, 200, {group: 'foo'});
watcher.clearTimeout({group: 'foo'});
-
-This module provides the base class for the Async module.
-import Async from 'core/async';
const
watcher = new Async();
// ...
watcher.muteAll();
// ...
watcher.unmuteAll();
watcher.suspendAll();
// ..
watcher.unsuspendAll();
watcher.clearAll();
-
-Returns true if the specified value is looks like an instance of AsyncOptions
-Reason why a task can be killed (cleared)
-Reason why a task can be marked
-Context of a task
-This module provides Async wrappers for event emitters.
-import Async from 'core/async';
import { EventEmitter2 as EventEmitter } from 'eventemitter2';
const
emitter = new EventEmitter(),
watcher = new Async();
watcher.on(emitter, 'foo', (e) => {
console.log(e);
});
emitter.emit('foo', 'bar');
-
-Returns true if the specified value is looks like an event object
-This module provides Async wrappers for timer functions, like, setTimeout, setInterval and requestIdleCallback.
import Async from 'core/async';
const
watcher = new Async();
watcher.setTimeout(() => {
console.log('bla');
}, 100);
-
-This module provides a bunch of helpers to wrap some objects, like event emitters or data providers.
- - -The wrapper takes a link to the "raw" data provider and returns a new object that based on the original, -but all async methods and properties are wrapped by Async.
-Notice, the wrapped methods can take additional Async parameters, like group or label.
-import Async from 'core/async';
import Provider, { provider } from 'core/data';
@provider('api')
export default class User extends Provider {
baseURL = 'user/:id';
}
const
$a = new Async(),
wrappedProvider = $a.wrapDataProvider(new User());
wrappedProvider.get({uuid: 1}).then((res) => {
console.log(res);
});
// By default, all wrapped methods have a group name that is equal to the provider name.
// So we can use it to clear or suspend requests, etc.
$a.clearAll({group: 'api.User'})
wrappedProvider.upd({uuid: 1}, {
// All wrapped methods can take additional Async parameters as the second argument: `group`, `label` and `join`
group: 'bla',
label: 'foo',
join: true,
// Also, the second argument of the wrapped method can take the original parameters from a provider
headers: {
'X-Foo': '1'
}
}).then((res) => {
console.log(res);
});
// If we are providing a group to the method, it will be joined with the global group by using the `:` character
$a.suspendAll({group: 'api.User:bla'});
// Obviously, we can use a group as RegExp
$a.muteAll({group: /api\.User/});
// We can use any methods or properties from the original data provider
wrappedProvider.dropCache();
-
-
-
- By default, when the wrapper wraps the provider, it takes the provider name and passes it as a group to all wrapped methods. -This behavior brings a future to clear or suspend all requests from the wrapped provider by its name. -But we can provide a different global name when wrapping a provider.
-import Async from 'core/async';
import Provider, { provider } from 'core/data';
@provider('api')
export default class User extends Provider {
baseURL = 'user/:id';
}
const
$a = new Async(),
dp1 = $a.wrapDataProvider(new User(), {group: 'foo'});
dp1.get({uuid: 1}).then((res) => {
console.log(res);
});
$a.clearAll({group: 'foo'})
-
-
-
- The wrapper takes a link to the "raw" event emitter and returns a new object that based on the original, -but all async methods and properties are wrapped by Async.
-Notice, the wrapped methods can take additional Async parameters, like group or label. In addition, -the wrapper adds new methods, like "on" or "off", to make the emitter API more standard.
-import Async from 'core/async';
const
$a = new Async(),
wrappedEventEmitter = $a.wrapEventEmitter(window);
const handler = () => console.log('scroll event');
// We can safely listen to emitter events, cause all emitter methods, like `addListener` or `on` are wrapped by Async.
const id = wrappedEventEmitter.addEventListener('scroll', handler, {
// Notice, the third argument can take Async parameters in addition to the native emitter parameters
capture: true,
label: 'label'
});
// The wrapper preserves the original API of emitter methods, so we can call something like this
wrappedEventEmitter.removeEventListener('scroll', handler);
// Finally, the wrapper adds a bunch of standard methods to the emitter, like `on`, `once`, and other stuff.
// We can use their instead of the original methods to make our code more universal.
wrappedEventEmitter.once('resize', (e) => {
console.log(e);
}, {group: 'resizers'});
$a.muteAll({group: 'resizers'});
// We can use any methods or properties from the original emitter
console.log(wrappedEventEmitter.name); // window.name
-
-
-
- Unlike the wrapper of data providers, the emitter wrapper doesn't have any default global group for operations, -but you can pass it manually. -This behavior brings a future to clear or suspend all events from the wrapped provider by its name.
-import Async from 'core/async';
const
$a = new Async(),
wrappedEventEmitter = $a.wrapEventEmitter(window, {group: 'windowEvents'});
wrappedEventEmitter.once('resize', (e) => {
console.log(e);
});
$a.muteAll({group: 'windowEvents'});
wrappedEventEmitter.on('scroll', (e) => {
console.log(e);
}, {
// If we are providing a group to the method, it will be joined with the global group by using the `:` character
group: 'scrolling'
});
$a.muteAll({group: 'windowEvents:scrolling'});
-
-
-
- As you can see, the wrapper creates a new object based on the original emitter and replaces some methods with the safely Async analogs. -The overridden methods preserve the original emitter API, but some interfaces are not supported to use.
-import Async from 'core/async';
const
$a = new Async(),
wrappedEventEmitter = $a.wrapEventEmitter(window, {group: 'windowEvents'});
// The wrapper does not support this kind of attaching listeners.
// The replaced method can take the second argument only as a function.
wrappedEventEmitter.addEventListener('scroll', {
handleEvent: (e) => {
console.log(e);
}
})
-
-
-
- The wrapper takes a link to the "raw" async storage and returns a new object that based on the original, -but all async methods and properties are wrapped by Async.
-Notice, the wrapped methods can take additional Async parameters, like group or label.
-import Async from 'core/async';
import { asyncLocal } from 'core/kv-storage';
const
$a = new Async(),
wrappedStorage = $a.wrapStorage(asyncLocal);
wrappedStorage.set('someKey', 'someValue', {
// All wrapped methods can take additional Async parameters as the last argument: `group`, `label` and `join`
group: 'bla',
label: 'foo',
join: true,
}).then(async () => {
console.log(await wrappedStorage.get('someKey') === 'someValue');
});
$a.suspendAll({label: 'foo'});
-
-
-
- The storage wrapper doesn't have any default global group for operations, but you can pass it manually. -This behavior brings a feature to clear or suspend all events from the wrapped provider by its name.
-import Async from 'core/async';
import { asyncLocal } from 'core/kv-storage';
const
$a = new Async(),
wrappedStorage = $a.wrapStorage(asyncLocal, {group: 'globalGroup'});
wrappedStorage.set('someKey', 'someValue').then(() => {
console.log('yeah!');
});
$a.muteAll({group: 'globalGroup'});
wrappedStorage.get('someKey', {
// If we are providing a group to the method, it will be joined with the global group by using the `:` character
group: 'localGroup'
}).then((val) => {
console.log(val) === 'someValue';
});
$a.clearAll({group: 'globalGroup:localGroup'});
-
-
-
- By default, a custom namespace have the same global group as the global namespace
-import Async from 'core/async';
import { asyncLocal } from 'core/kv-storage';
const
$a = new Async(),
wrappedStorage = $a.wrapStorage(asyncLocal, {group: 'bar'});
// We can provide own global group to namespace, it will be joined with the parent's global group
const blaStore = wrappedStorage.namespace('[[BLA]]', {group: 'bla'});
blaStore.clear({group: 'foo'});
$a.muteAll({group: 'bar:bla:foo'});
-
-This module provides the base interface for a Cache data structure: a simple in-memory key-value storage, -which can be useful to organize cache data structures. -The submodules contain different implementations for that interface. The main module re-exports these implementations:
-AbstractCache — an alias for core/cache/interface/Cache;Cache — an alias for core/cache/simple;RestrictedCache — an alias for core/cache/restricted;NeverCache — an alias for core/cache/never.import SimpleCache from 'core/cache/simple';
const
cache = new SimpleCache();
cache.set('foo', 'bar1');
cache.set('foo2', 'bar2');
cache.set('baz', 'bar3');
console.log(cache.size); // 3
cache.clear((val, key) => /foo/.test(key));
console.log(cache.size); // 1
-
-
-
- All caches support three kinds of iterators:
-import SimpleCache from 'core/cache/simple';
cache.set('foo', 'bar1');
cache.set('foo2', 'bar2');
cache.set('baz', 'bar3');
for (const key of SimpleCache) {
// 'foo' 'foo2' 'baz'
console.log(el);
}
for (const key of SimpleCache.keys()) {
// 'foo' 'foo2' 'baz'
console.log(el);
}
-
-import SimpleCache from 'core/cache/simple';
cache.set('foo', 'bar1');
cache.set('foo2', 'bar2');
cache.set('baz', 'bar3');
for (const key of SimpleCache.values()) {
// 'bar1' 'bar2' 'bar3'
console.log(el);
}
-
-import SimpleCache from 'core/cache/simple';
cache.set('foo', 'bar1');
cache.set('foo2', 'bar2');
cache.set('baz', 'bar3');
for (const key of SimpleCache.entries()) {
// ['foo', 'bar1'] ['foo2', 'bar2'] ['baz', 'bar3']
console.log(el);
}
-
-
-
- Also, the module provides a bunch of functions to decorate cache storages, like adding the ttl feature or persisting data storing.
Provides a decorator for any cache to add a feature of cache expiring.
-import addTTL from 'core/cache/decorators/ttl';
import SimpleCache from 'core/cache/simple';
// The function `addTTL` accepts a cache object and a value for the default TTL as the second argument
const
cache = addTTL(new SimpleCache(), 1000);
// The method "add" accepts as the third optional parameter time until expiring the item to store in milliseconds
cache.add('foo', 'bar1', {ttl: 500});
// Additional method to remove the `ttl` descriptor from a cache item by the specified key
cache.removeTTLFrom('foo');
-
-
-
- Provides a decorator for any cache to add a feature of persistent data storing.
-import { asyncLocal } from 'core/kv-storage';
import addPersistent from 'core/cache/decorators/persistent';
import SimpleCache from 'core/cache/simple';
const
persistentCache = await addPersistent(new SimpleCache(), asyncLocal);
await persistentCache.set('foo', 'bar', {persistentTTL: (2).seconds()});
await persistentCache.set('foo2', 'bar2');
// Cause we use the same instance for the local data storing,
// this cache will have all values from the previous (it will be loaded from the storage during initialization)
const
copyOfCache = await addPersistent(new SimpleCache(), asyncLocal, opts);
-
-
-
- Ranges support a bunch of methods to work with them.
- - -Number of elements within the cache.
-import SimpleCache from 'core/cache/simple';
const
cache = new SimpleCache();
cache.add('foo', 'bar1');
console.log(cache.size); // 1
-
-
-
- Returns true if a value by the specified key exists in the cache.
-import SimpleCache from 'core/cache/simple';
const
cache = new SimpleCache();
cache.add('foo', 'bar1');
console.log(cache.has('foo')); // true
-
-
-
- Returns a value from the cache by the specified key.
-import SimpleCache from 'core/cache/simple';
const
cache = new SimpleCache();
cache.add('foo', 'bar1');
console.log(cache.get('foo')); // 'bar1'
-
-
-
- Saves a value to the cache by the specified key.
-import SimpleCache from 'core/cache/simple';
const
cache = new SimpleCache();
cache.set('foo', 'bar1');
console.log(cache.has('foo')); // true
-
-
-
- Removes a value from the cache by the specified key.
-import SimpleCache from 'core/cache/simple';
const
cache = new SimpleCache();
cache.set('foo', 'bar1');
console.log(cache.has('foo')); // true
cache.remove('foo');
console.log(cache.has('foo')); // false
-
-
-
- Clears the cache by the specified filter and returns a map of removed keys.
-import SimpleCache from 'core/cache/simple';
const
cache = new SimpleCache();
cache.set('foo1', 'bar1');
cache.set('foo2', 'bar2');
cache.set('foo3', 'bar2');
cache.clear((val) => val === 'bar2');
console.log(cache.has('foo1')); // true
console.log(cache.has('foo1')); // true
console.log(cache.has('foo2')); // false
cache.clear();
console.log(cache.has('foo1')); // true
-
-This module provides a helper for Cache decorators to add a feature of emitting mutation events caused by side effects.
-import addEmitter from 'core/cache/decorators/helpers/add-emitter';
import SimpleCache from 'core/cache/simple';
const
cache = new SimpleCache();
// `originalRemove` doesn't emit events
const {remove: originalRemove, subscribe} = addEmitter(cache);
// Now cache.eventEmitter emit event 'remove' with args [cache(instance what call emit), [...args]]
cache.remove('foo');
// (eventName, instanceOfListener, callback) - callback invoked only if emit was made by children of instanceOfListener;
subscribe('remove', cache, (key) => {
console.log(key);
});
-
-Adds an event emitter to the provided cache object and wraps all mutation events to emit events, i.e., -it mutates the original object. The function returns an object with the original unwrapped methods and -a method to subscribe to these events.
-This module provides a wrapper for Cache data structures to add a feature of persistent data storing.
-To describe how long should keep an item in the persistent cache, use the persistentTTL parameter.
-The value for persistentTTL should be provided in milliseconds.
import { asyncLocal } from 'core/kv-storage';
import addPersistent from 'core/cache/decorators/persistent';
import SimpleCache from 'core/cache/simple';
const
opts = {loadFromStorage: 'onInit'},
persistentCache = await addPersistent(new SimpleCache(), asyncLocal, opts);
await persistentCache.set('foo', 'bar', {persistentTTL: (2).seconds()});
await persistentCache.set('foo2', 'bar2');
// Cause we use the same instance for the local data storing,
// this cache will have all values from the previous (it will be loaded from the storage during initialization)
const
copyOfCache = await addPersistent(new SimpleCache(), asyncLocal, opts);
-
-
-
- The option specifies the default TTL to keep items within the persistent storage in milliseconds.
-This value is used when you don't provide the persistentTTL parameter when saving an item.
import { asyncLocal } from 'core/kv-storage';
import addPersistent from 'core/cache/decorators/persistent';
import SimpleCache from 'core/cache/simple';
const persistentCache = await addPersistent(new SimpleCache(), asyncLocal, {
persistentTTL: (60).seconds()
});
// If we "reload" the cache from the storage by using the browser reloading or another way,
// these saved values can be "restored" from the storage only for the next 60 seconds
await persistentCache.set('foo', 'bar');
await persistentCache.set('foo2', 'bar2');
-
-
-
- There is more than one way to initialize a cache from persistent storage. -The most obvious way to do it is to load all data from the storage to RAM during the cache's initialization. -This strategy is simple but not effective cause if we can have a huge amount of data in the storage, -so we have to load it all at the same time. This can be very expensive. We need another way. -But what if we load an item from the cache only when it is requested the first time. -In that case, we haven't to load the whole stored data on cache initialization, -but all cache methods will change API - they will become return promises instead of the raw results. -Some consumers cannot be ready for changing API, so there is no silver bullet. We have to keep both strategies.
- - -The whole stored data will be loaded during the cache initialization
-Notice, cause the loading from the storage is an asynchronous operation, addPersistent will return a promise
-if used the onInit strategy.
import { asyncLocal } from 'core/kv-storage';
import addPersistent from 'core/cache/decorators/persistent';
import SimpleCache from 'core/cache/simple';
const
opts = {loadFromStorage: 'onInit'};
persistentCache = await addPersistent(new SimpleCache(), asyncLocal, opts);
await persistentCache.set('foo', 'bar');
await persistentCache.set('foo2', 'bar2');
// All properties already in our `Simple` cache
const copyOfCache = await addPersistent(new SimpleCache(), asyncLocal, opts);
console.log(copyOfCache.get('foo') === 'bar');
-
-
-
- Each stored item will be loaded from the cache only on the first touch, i.e. on-demand or lazily. -This is the default strategy.
-import { asyncLocal } from 'core/kv-storage';
import addPersistent from 'core/cache/decorators/persistent';
import SimpleCache from 'core/cache/simple';
const persistentCache = await addPersistent(new SimpleCache(), asyncLocal);
await persistentCache.set('foo', 'bar');
await persistentCache.set('foo2', 'bar2');
const copyOfCache = await addPersistent(new SimpleCache(), asyncLocal);
console.log(await copyOfCache.get('foo') === 'bar');
-
-
-
- Each stored item will be loaded from the cache only on the first touch and only if there is no internet connection. -The strategy is useful to create net-first offline storages.
-import { isOnline } from 'core/net';
import { asyncLocal } from 'core/kv-storage';
import addPersistent from 'core/cache/decorators/persistent';
import SimpleCache from 'core/cache/simple';
const
opts = {loadFromStorage: 'onOfflineDemand'},
persistentCache = await addPersistent(new SimpleCache(), asyncLocal, opts);
await persistentCache.set('foo', 'bar');
await persistentCache.set('foo2', 'bar2');
const copyOfCache = await addPersistent(new SimpleCache(), asyncLocal, opts);
if ((await isOnline()).status) {
console.log(await copyOfCache.get('foo') !== 'bar');
} else {
console.log(await copyOfCache.get('foo') === 'bar');
}
-
-Wraps the specified cache object to add a feature of persistent data storing
-value type of the cache object
-cache object to wrap
-storage to save data
-Engine to provide the persistent feature
-Available checking state of a storage item:
-available: false; checked: false - don't need to check the storage, don't mark the item as checked;available: false; checked: true - don't need to check the storage, mark the item as checked;available: true; checked: true - check the storage, mark the item is checked.This module provides a wrapper for Cache data structures to add a feature of the cache expiring.
-To describe how long should keep an item in the cache, use the ttl parameter.
-The value for ttl should be provided in milliseconds.
import addTTL from 'core/cache/decorators/ttl';
import SimpleCache from 'core/cache/simple';
const
cache = addTTL(new SimpleCache());
cache.add('foo', 'bar1', {ttl: 500});
cache.add('foo2', 'bar2', {ttl: 1000});
cache.add('baz', 'bar3');
console.log(cache.keys().length); // 3
setTimeout(() => {
console.log(cache.keys().length); // 1
}, 2000);
-
-
-
- When you wrap a cache object with the ttl decorator, you can provide the default ttl value.
-This value is used when you don't provide the ttl parameter when saving an item.
import addTTL from 'core/cache/decorators/ttl';
import SimpleCache from 'core/cache/simple';
const
cache = addTTL(new SimpleCache(), 10000);
cache.add('foo', 'bar1', {ttl: 500}); // TTL 500 has the higher priority and will overwrite 10000s
cache.add('foo2', 'bar2'); // TTL will be 10000
-
-
-
- In case of a property collision, all old properties, including their TTL values, will be overwritten.
-import addTTL from 'core/cache/decorators/ttl';
import SimpleCache from 'core/cache/simple';
const
cache = addTTL(new SimpleCache());
cache.add('foo', 'bar1', {ttl: 500});
cache.add('foo', 'bar1'); // TTL will be overwritten
-
-Wraps the specified cache object to add a feature of the cache expiring
-value type of the cache object
-key type of the cache object
-cache object to wrap
-default ttl value in milliseconds
-This module provides a loopback class for a Cache data structure. -It can be helpful if you use the "strategy" pattern and need to prevent caching.
-import * as cache from 'core/cache';
class Foo {
constructor(cacheStrategy) {
this.cache = cache[cacheStrategy];
}
}
const withCache = new Foo('Cache');
const withoutCache = new Foo('NeverCache');
-
-
-
- See Cache.
-This module provides a class for a Cache data structure with support for limiting of values in the cache.
-The structure' constructor takes how many values can be stored in the cache (by default, it equals 20).
import RestrictedCache from 'core/cache/restricted';
const
cache = new RestrictedCache(3);
cache.set('foo1', 'bar1');
cache.set('foo2', 'bar2');
cache.set('foo3', 'bar3');
console.log(cache.size); // 3
console.log(cache.has('foo1')); // true
cache.set('foo4', 'bar4');
console.log(cache.size); // 3
console.log(cache.has('foo1')); // false
console.log(cache.has('foo4')); // true
// Modify the cache' capacity
cache.setCapacity(5);
cache.set('foo5', 'bar5');
cache.set('foo6', 'bar6');
console.log(cache.size); // 5
cache.setCapacity(3);
console.log(cache.size); // 3
console.log(cache.has('foo2')); // false
console.log(cache.has('foo3')); // false
-
-
-
- See Cache.
- - -Sets a new capacity of the cache. -The method returns a map of truncated elements that the cache can't fit anymore.
-import RestrictedCache from 'core/cache/restricted';
// The constructor takes a number of maximum values in the cache
const
cache = new RestrictedCache(3);
cache.set('foo1', 'bar1');
cache.set('foo2', 'bar2');
cache.set('foo3', 'bar3');
// Map([['foo1', 'bar1], ['foo2', 'bar2']])
console.log(cache.setCapacity(1));
console.log(cache.size); // 1
-
-This module provides a class for a simple in-memory Cache data structure.
-import SimpleCache from 'core/cache/simple';
const
cache = new SimpleCache();
cache.set('foo', 'bar1');
cache.set('foo2', 'bar2');
cache.set('baz', 'bar3');
console.log(cache.keys().length); // 3
cache.clear((val, key) => /foo/.test(key));
console.log(cache.keys().length); // 1
-
-
-
- See Cache.
-This module provides API to create an abstraction under data — a data provider. -The provider grants methods to access and modify data that is represented as one logical instance.
-For example, we need to create an API for a user in our application. Let's start with a simple REST architecture:
-GET user/:id returns an object of user fields by the specified user id:import request from 'core/request';
request('user/1');
-
-{
"id": 1,
"name": "Andrey",
"age": 30
}
-
-PUT user/:id modifies a user by the specified id with some provided data and returns new data:import request from 'core/request';
request('user/1', {method: 'PUT', body: {age: 31}});
-
-{
"id": 1,
"name": "Andrey",
"age": 31
}
-
-DELETE user/:id deletes a user by the specified id:import request from 'core/request';
request('user/1', {method: 'DELETE'});
-
-POST user creates a new user with the specified data and returns it:import request from 'core/request';
request('user', {method: 'POST', body: {name: 'Andrey', age: 30}});
-
-{
"id": 2,
"name": "Andrey",
"age": 30
}
-
-All of these handlers are associated with one data model that represents a user. Knowing this, we can create a class for this model.
-import request from 'core/request';
class User {
url = 'user/';
async get(id) {
return (await request(this.url + id)).data;
}
async upd(id, body) {
return (await request(this.url + id, {method: 'PUT', body})).data;
}
async del(id) {
return (await request(this.url + id, {method: 'DELETE'})).data;
}
async add(body) {
return (await request(this.url, {method: 'POST', body})).data;
}
}
-
-It might seem naive, but it works. Also, we need to create some API to submit the provider's events that allows notifying an application -if data was changed.
-import request from 'core/request';
import { EventEmitter2 as EventEmitter } from 'eventemitter2';
class User {
url = 'user/';
emitter = new EventEmitter();
async get(id) {
return (await request(this.url + id)).data;
}
async upd(id, body) {
const {data} = await request(this.url + id, {method: 'PUT', body});
this.emitter.emit('upd', data);
return data;
}
async del(id) {
const {data} = await request(this.url + id, {method: 'DELETE'});
this.emitter.emit('del', data);
return data;
}
async add(body) {
const {data} = await request(this.url, {method: 'POST', body});
this.emitter.emit('add', data);
return data;
}
}
-
-Still looks fine and useful, but if we want to create more classes for other data instances, we need to make some kind
-of superclass to avoid "copy-pasting" code lines. The superclass may also improve our API with added extra functionality,
-such as support for socket events, middlewares, etc. This is exactly what core/data module does.
The core/data module provides the default interface for any data providers. If your class implements that interface,
-you can use it as a data provider with any V4Fire modules. The interface is pretty similar to the example mentioned above of
-a data class but realizes more common API. Let's take a look at it.
core/data/interface
-import { EventEmitterLike } from 'core/async';
import {
CreateRequestOptions,
RequestQuery,
RequestMethod,
RequestResponse,
RequestBody
} from 'core/data';
import { ModelMethod } from 'core/data/interface';
export * from 'core/data/interface/types';
export default interface Provider {
readonly providerName: string;
readonly emitter: EventEmitterLike;
name(): CanUndef<ModelMethod>;
name(value: ModelMethod): Provider;
method(): CanUndef<RequestMethod>;
method(value: RequestMethod): Provider;
base(): string;
base(value: string): Provider;
url(): string;
url(value: string): Provider;
dropCache(): void;
get<T = unknown>(query?: RequestQuery, opts?: CreateRequestOptions<T>): RequestResponse;
peek<T = unknown>(query?: RequestQuery, opts?: CreateRequestOptions<T>): RequestResponse;
post<T = unknown>(body?: RequestBody, opts?: CreateRequestOptions<T>): RequestResponse;
add<T = unknown>(body?: RequestBody, opts?: CreateRequestOptions<T>): RequestResponse;
upd<T = unknown>(body?: RequestBody, opts?: CreateRequestOptions<T>): RequestResponse ;
del<T = unknown>(body?: RequestBody, opts?: CreateRequestOptions<T>): RequestResponse;
}
-
-Many of these methods look familiar, but we also have some new methods and properties:
-providerName — contains the full name of a provider.name — a pair of get/set methods to provide "logical" meaning for a request:// There will be fired the "init" event after successfully receiving the data
myProvider.name('init').get('foo');
-
-Mind that the default V4Fire implementation of a data provider by default sends events for upd, add, del requests.
-These events have the same name with methods that produce them.
method — a pair of get/set methods to provide a type of HTTP request:// The request uses POST to get data
myProvider.method('POST').get('foo');
-
-base — a pair of get/set methods to provide a base URL for requests:// The request is addressed for https://google.com/foo
myProvider.base('https://google.com').get('foo');
-
-url — a pair of get/set methods to provide URL for requests:// The request is addressed for https://google.com/foo
myProvider.url('https://google.com').get('foo');
// We can combine .base() and .url():
// The request is addressed for https://google.com/bla/baz
myProvider.base('https://google.com').url('bla/baz').get('foo');
-
-dropCache — a method that drops any request cache.
peek — a request that logically is similar to the checking of API accessibility. It uses HEAD by default.
post — a request that sends to a server some data without any logical representation. It uses POST by default.
In addition to the base interface of data providers, V4Fire provides an implementation that grants some extra functionality -and more flexibility.
-import Provider from 'core/data';
export default class User extends Provider {
baseURL = 'user/:id';
}
const user = new User();
user.get({id: 1}).then((data) => {
console.log(data);
})
-
-
-
- You can provide some parameters to a provider by using the constructor.
-import Provider from 'core/data';
export default class User extends Provider {
baseURL = 'user/:id';
}
const user = new User({
externalRequest: true,
socket: true
});
-
-The entire list of parameters:
-interface ProviderOptions {
/**
* List of additional data providers for the "get" method.
* It can be useful if you have some providers that you want combine to one.
*/
extraProviders?: FunctionalExtraProviders;
/**
* Provider alias: it is used with extra providers
*/
alias?: string;
/**
* @see [[CreateRequestOptions.externalRequest]]
* @default `false`
*/
externalRequest?: boolean;
/**
* If true, then the provider is connected to a socket server
* @default `false`
*/
socket?: boolean;
}
-
-
-
- You can register your data provider by a name in the global storage. For that case, you should use the special decorator provider.
import Provider, { provider, providers } from 'core/data';
@provider
export default class User extends Provider {
baseURL = 'user/:id';
}
console.log(providers['User']);
-
-The name to register is taken from the class name of the provider. Also, you can declare a namespace that is concatenated with the name.
-import Provider, { provider, providers } from 'core/data';
@provider('base')
export default class User extends Provider {
baseURL = 'user/:id';
}
console.log(providers['base.User']);
-
-It can be useful to provide data providers to components as input properties:
-<my-component dataProvider="base.User"></my-component>
-
-
-
- The default implementation of a data provider has an association between HTTP request methods and provider methods:
-{
/**
* Default HTTP request method for the "get" method
*/
getMethod: RequestMethod = 'GET';
/**
* Default HTTP request method for the "peek" method
*/
peekMethod: RequestMethod = 'HEAD';
/**
* Default HTTP request method for the "add" method
*/
addMethod: RequestMethod = 'POST';
/**
* Default HTTP request method for the "upd" method
*/
updMethod: RequestMethod = 'PUT';
/**
* Default HTTP request method for the "del" method
*/
delMethod: RequestMethod = 'DELETE';
}
-
-You allow to rewrite it in your subclass.
-import Provider, { provider } from 'core/data';
@provider
export default class User extends Provider {
baseURL = 'user/:id';
getMethod = 'POST';
}
-
-
-
- The base URL is the starting point for URLs of each request. You can provide one universal URL by using the baseURL parameter, but also,
-you can specify the base URL for each particular method.
import Provider, { provider } from 'core/data';
@provider
export default class User extends Provider {
baseURL = 'user/:id';
baseAddURL = 'user/add';
baseDeLURL = 'user/:id/del';
}
-
-
-
- You can specify dynamic values within a URL string. For this case, just add a variable with : character before the name.
-The interpolations' values are taken from a query object or request body (if it's represented as a simple JS object).
-After interpolation, all values that are used will be dropped from the source object.
Middleware is a simple function invoked before each request and can modify some request parameters, like adding/removing HTTP headers, etc. -The function takes a request environment:
-{
ctx: RequestContext<T>;
opts: CreateRequestOptions<T>;
globalOpts: GlobalOptions;
}
-
-You can specify a sequence of middlewares to the provider, but notice that middlewares' order depends on the structure that you use -(hash doesn't preserve the order, but arrays/maps do it).
-For example, we need to add some authorization header for every request of the provider.
-import Provider, { provider } from 'core/data';
@provider
export default class User extends Provider {
static middlewares = {
addSession({opts: {headers}}) {
headers['Authorization'] = 'bearer myJWTToken';
}
};
baseURL = 'user/:id';
}
-
-The result of a middleware function is ignoring, with the exceptions of promises and functions. -If some middleware returns a promise, it will be awaited. -If at least one of the middlewares returns a function, then the result of invoking the function will be returned as the request result. -It can help organize mocks of data and other similar cases when you don't want to execute a real request.
-import Provider, { provider, Response } from 'core/data';
@provider
export default class User extends Provider {
static middlewares = {
attachMocks() {
return () => new Response({id: 1, name: 'Andrey'}, {
status: 200,
responseType: 'object'
});
}
};
baseURL = 'user/:id';
}
-
-
-
- The encoder is a subtype of a middleware function, but unlike the simple middleware, the encoder must return a value and provide it -to another encoder or a request, which means that a sequence of encoders is tied with the following order. -Encoders are using to convert data to another format before submitting it. -For example, your server demands that all request data must be represented as a protobuf value.
-import Provider, { provider } from 'core/data';
@provider
export default class User extends Provider {
static encoders = {
upd: [toProtobuf]
};
baseURL = 'user/:id';
}
-
-Note that unlike the middlewares parameter, the encoders are separated between provider methods, which means
-that you should declare encoders for all your methods.
The encoder function has a signature:
-export interface Encoder<I = unknown, O = unknown> {
(data: I, params: MiddlewareParams): O;
}
-
-Where:
-data is your data;params is an environment of your request.If some encoder returns a promise, it will be awaited.
- - -The decoder is another subtype of a middleware function, which is pretty similar to encoder, but unlike the encoder,
-it converts data from a response to the provider format.
The decoder function has a signature:
-export interface Encoder<I = unknown, O = unknown> {
(data: I, params: MiddlewareParams, response: Response): O;
}
-
-The first parameters are equal to the encoder function. The last parameter contains a link to the response object.
-import Provider, { provider } from 'core/data';
@provider
export default class User extends Provider {
static decoders = {
get: [fromProtobuf]
};
baseURL = 'user/:id';
}
-
-If some encoder returns a promise, it will be awaited.
- - -To create a request, all providers use the core/request module. If you need to provide some extra parameters of the request,
-such as contentType, you can specify a factory to make these requests using an overload of the request function.
import request from 'core/request';
import Provider, { provider } from 'core/data';
@provider
export default class User extends Provider {
static request = request({
contentType: 'json',
cacheStrategy: 'forever',
cacheTTL: (10).seconds()
});
baseURL = 'user/:id';
}
-
-
-
- Headers of any request also support interpolation from request data, which is similar to baseURL.
import request from 'core/request';
import Provider, { provider } from 'core/data';
@provider
export default class User extends Provider {
static request = request({
header: {
Accept: '${accept}'
}
});
baseURL = 'user/:id';
}
-
-
-
- You can specify the base URL for your API. It can be useful if you have different URLs for development, staging, and production. -The API URL is concatenated with the base URL of a provider.
-import Provider, { provider } from 'core/data';
@provider
export default class User extends Provider {
static request = request({
api: {url: 'https://google.com'}
});
baseURL = 'user/:id';
}
-
-The value can also be declared as a function that is invoked at each request.
-import Provider, { provider } from 'core/data';
@provider
export default class User extends Provider {
static request = request({
api: {url: () => USE_PROD ? 'https://google.com' : 'https://dev.google.com'}
});
baseURL = 'user/:id';
}
-
-Finally, if you specify the default API URL within core/config/api, you can provide some chunks of an API URL
-that are applied to the base.
import Provider, { provider } from 'core/data';
@provider
export default class User extends Provider {
static request = request({
api: {
domain3: () => () => USE_PROD ? '' : 'dev',
zone: 'io'
}
});
baseURL = 'user/:id';
}
-
-
-
- You can create a composition of multiple providers that are fetching in parallel and merging to one data. -This mechanism is called "extraProviders". Mind that API work only for a get request.
-import Provider, { provider } from 'core/data';
@provider
export default class User extends Provider {
extraProviders = ({opts: {query}}) => ({
'skills': {
provider: 'Skills',
query: {id: query.id}
}
});
alias = 'user';
baseURL = 'user/:id';
}
new User().get({id: 1}).then((data) => {
// The main data from User provider is stored by an alias (if it's specified) or by a provider name
console.log(data.user);
// The extra data is stored by an alias (if it's specified) or by key name from the declaration
console.log(data.skills);
});
-
-
-
- The declaration object of an extra provider has a standard interface:
-type ExtraProviderConstructor =
string |
Provider |
{new(opts?: ProviderOptions): Provider};
interface ExtraProvider {
provider?: ExtraProviderConstructor;
providerOptions?: ProviderOptions;
query?: RequestQuery;
request?: CreateRequestOptions;
alias?: string;
}
-
-provider — full name of a provider or a link to the provider or the provider constructor;providerOptions — additional options for the provider constructor;query — query parameters for a provider get request;request — request parameters for the provider;alias — alias of data: the data is stored by a key from this value in the result object.If you don't need to provide dynamic parameters to a request, you can define a static object instead of a function.
-import Provider, { provider } from 'core/data';
@provider
export default class User extends Provider {
extraProviders = {
'skills': {
provider: 'Skills'
}
};
alias = 'user';
baseURL = 'user/:id';
}
-
-
-
- The data provider is a simple class that implements a special interface. -That's why to create a new provider that is extended parameters from another provider, you should create a simple subclass.
-import Provider, { provider } from 'core/data';
@provider
export class User extends Provider {
static request = request({
api: {url: 'https://google.com'}
});
static middlewares = {
addSession({opts: {headers}}) {
headers['Authorization'] = 'bearer myJWTToken';
}
};
baseURL = 'user/:id';
}
@provider
export class User2 extends User {
static request = User.request({
contentType: 'json'
});
static middlewares = {
...User.middlewares,
addABHeader({opts: {headers}}) {
headers['X-AB'] = 'foo';
}
};
}
-
-
-
- There is a standard middleware to organize a data mocking mechanism — attackMock middleware (it is used by default).
import Provider, { provider } from 'core/data';
@provider
export default class User extends Provider {
static mocks = {
PUT: [
{
body: {
age: 31
},
response: {
id: 1,
name: "Andrey",
age: 31
}
}
],
GET: [{
response: {
id: 1,
name: "Andrey",
age: 30
}
}]
};
baseURL = 'user/:id';
}
-
-Mind that the root keys of mocks represent HTTP methods, but not provider methods. -The values contain arrays of request objects to match: the algorithm finds the most suitable option and returns its response. -Also, the middleware supports dynamically casting responses:
-import Provider, { provider } from 'core/data';
@provider
export default class User extends Provider {
static mocks = {
GET: [{
response(params, response) {
if (!params.opts.query?.id) {
response.status = 400;
return;
}
response.status = 200;
return {
id: 1,
name: "Andrey",
age: 30
};
}
}]
};
baseURL = 'user/:id';
}
-
-Finally, you can use dynamic importing with mocks:
-import Provider, { provider } from 'core/data';
@provider
export default class User extends Provider {
static mocks = import('mocks/user.json');
baseURL = 'user/:id';
}
-
-
-
- By default, all data mocks are disabled, but you can enable them just type to a console of a browser:
-// Enables mocks for the User provider
setEnv('mock', {patterns: ['User']});
// Enables mocks for all providers
setEnv('mock', {patterns: ['.*']});
-
-The values of patterns are converted to RegExp objects and applied to provider names (including namespaces). -Config settings are stored within a local browser storage.
-Registers a data provider class to the global store with the specified namespace: -the namespace value is concatenated with a name of the provider class
-namespace string
-Registers a data provider class to the global store with the specified namespace: -the namespace value is concatenated with a name of the provider class
-Registers a data provider class to the global store by a name of the provider class
-provider class
-This module provides an interface a for simple data provider.
-This module provides a bunch of default middlewares for requests and data providers:
-attachMock — an alias for core/data/middlewares/attach-mock;attachStatus — an alias for core/data/middlewares/attach-status;wait — an alias for core/data/middlewares/wait.This module provides a middleware to attach mock data to a request.
- - -import Provider, { provider } from 'core/data';
import { attachMock } from 'core/data/middlewares';
@provider
export default class User extends Provider {
static middlewares = {
attachMock
};
static mocks = {
PUT: [
{
body: {
age: 31
},
response: {
id: 1,
name: "Andrey",
age: 31
}
}
],
GET: [{
response: {
id: 1,
name: "Andrey",
age: 30
}
}]
};
baseURL = 'user/:id';
}
-
-Mind that the root keys of mocks represent HTTP methods, but not provider methods. -The values contain arrays of request objects to match: the algorithm finds the most suitable option and returns its response. -Also, the middleware supports dynamically casting responses:
-import Provider, { provider } from 'core/data';
import { attachMock } from 'core/data/middlewares';
@provider
export default class User extends Provider {
static middlewares = {
attachMock
};
static mocks = {
GET: [{
response(params, response) {
if (!params.opts.query?.id) {
response.status = 400;
return;
}
response.status = 200;
return {
id: 1,
name: "Andrey",
age: 30
};
}
}]
};
baseURL = 'user/:id';
}
-
-Finally, you can use dynamic importing with mocks:
-import Provider, { provider } from 'core/data';
import { attachMock } from 'core/data/middlewares';
@provider
export default class User extends Provider {
static middlewares = {
attachMock
};
static mocks = import('mocks/user.json');
baseURL = 'user/:id';
}
-
-
-
- By default, all data mocks are disabled, but you can enable them just type to a console of a browser:
-// Enables mocks for the User provider
setEnv('mock', {patterns: ['User']});
// Enables mocks for all providers
setEnv('mock', {patterns: ['.*']});
-
-The values of patterns are converted to RegExp objects and applied to provider names (including namespaces). -Config settings are stored within a local browser storage.
-Middleware: attaches mock data from the mocks property
This module provides a decoder middleware to attach a response status to the response data.
-import Provider, { provider } from 'core/data';
import { attachStatus } from 'core/data/middlewares';
@provider
export default class User extends Provider {
static decoders = {
get: [attachStatus]
};
baseURL = 'user/:id';
}
(async () => {
const
user = new User(),
bob = await user.get('bob').data;
// Response status code (number)
console.log(bob.status);
// User response data
console.log(bob.data);
})();
-
-Decoder: attaches a response status to response data
-This module provides a middleware to suspend a request until will be resolved the specified value to wait.
-The middleware can be used as encoder: the value to wait will be taken from input data (.wait),
-otherwise, it will be taken from .meta.wait.
import Provider, { provider } from 'core/data';
import { wait } from 'core/data/middlewares';
@provider
export default class User extends Provider {
static encoders = {
get: [wait]
};
baseURL = 'user/:id';
}
(async () => {
const
user = new User(),
// Sleep 500 ms before do the request
bob = await user.get('bob', {meta: {wait: () => sleep(500)}}).data;
console.log(bob);
function sleep(ms) {
return new Promise((r) => setTimeout(r, ms));
}
})();
-
-Middleware: if the request has some parameter to wait, -then the middleware won't be resolved until this parameter isn't resolved.
-This middleware can be used as encoder: the value to wait will be taken from input data (.wait),
-otherwise, it will be taken from .meta.wait.
This module provides a bunch of helper decorators for functions. Mind that this module is deprecated and will be removed from the next major release of the library. You can use modules from core/functools instead of this.
-This module provides an alias for core/prelude/env.
-The module provides the base class for any errors. All classes of errors should extend this one.
- - -When TypeScript's target is < ES6, the transpiled code breaks inheritance from built-in classes. -For example:
-class MyError extends Error {}
const error = new MyError();
// false
console.log(error instanceof MyError);
// true
console.log(error instanceof Error);
-
-So instanceof won't work as expected. The same goes to a class that extends MyError: instanceof returns true
-only for the Error class.
BaseError fixes this problem. Moreover, BaseError takes care of name field and sets it correctly
-in the constructor.
import BaseError from 'core/error';
class ValidationError extends BaseError {}
-
-
-
- You can define an error message via the first argument at the BaseError constructor. Additionally, BaseError allows you
-to define a message format. It means that message can be generated based on arguments, passed to the error class
-constructor. To achieve this, you need to override the protected format method with an inheriting class.
The message field always returns the result of invoking the format method. By default, the method returns a string that is passed
-to BaseError's constructor as the first argument.
class ValidationError extends BaseError {
fieldName: string;
constructor(fieldName: string) {
super();
this.fieldName = fieldName;
}
protected format(): string {
return `Invalid field: ${this.fieldName}`;
}
}
const error = new ValidationError('FullName');
console.log(error.message); // Invalid field: FullName
-
-
-
- It's possible to pass an error as the second argument to the BaseError constructor. In this case, it's considered
-as the error that caused the new one. After this, the error caused can be accessed via the read-only cause property.
class ExternalLibError extends BaseError {
constructor(cause: Error) {
super('An external lib failed', cause);
}
}
try {
// Do some stuff
} catch (e) {
const error = new ExternalLibError(e);
// error.cause === e
throw error;
}
-
-This module provides a bunch of helper functions to handle events in more flexibly way.
- - -The function returns a promise that will be resolved after emitting of all events from the specified emitter.
-import { EventEmitter2 as EventEmitter } from 'eventemitter2';
import { resolveAfterEvents } from 'core/event';
const
emitter = new EventEmitter();
resolveAfterEvents(emitter, 'foo', 'bar')
.then(() => console.log('Bang!'));
emitter.emit('foo');
emitter.emit('bar');
-
-
-
- The function wraps a callback into a new function that never calls the target until all specified flags are resolved.
-createsAsyncSemaphore returns a new function that takes a string flag and resolves it.
-After all, flags are resolved, the last function invokes the target function.
-If you try to invoke the function after the first time resolving, ii won't be executed.
import { EventEmitter2 as EventEmitter } from 'eventemitter2';
import { createsAsyncSemaphore } from 'core/event';
const semaphore = createsAsyncSemaphore(() => {
console.log('Boom!');
}, 'foo', 'bar');
semaphore('foo');
semaphore('bar') // Boom!
-
-Creates a synchronous promise wrapper for the specified value
-Wraps a callback into a new function that never calls the target until all specified flags are resolved. -The function returns a new function that takes a string flag and resolves it. -After all, flags are resolved, the last function invokes the target function. -If you try to invoke the function after the first time resolving, ii won't be executed.
-callback function that is invoked after resolving all flags
-flags to resolve
-Wraps a callback into a new function that never calls the target until all specified flags are resolved. -The function returns a new function that takes a string flag and resolves it. -After all, flags are resolved, the last function invokes the target function. -If you try to invoke the function after the first time resolving, ii won't be executed.
-Returns a promise that will be resolved after emitting of all events from the specified emitter
-events to listen
-This module provides a bunch of functions and decorators to wrap another functions with adding some extra functionality. -Also, see submodules of this module:
-core/functools/deprecation;core/functools/implementation;core/functools/warning;core/functools/trait.Decorator for Function.prototype.once.
-Returns a new function that allows to invoke the specified function only once.
import { once, debounce } from 'core/functools';
class Foo {
@once
bar() {
return Math.random();
}
}
const foo = new Foo();
console.log(foo.bar() === foo.bar());
-
-
-
- Decorator for Function.prototype.debounce
-Returns a new function that allows to invoke a function, which it takes, only with the specified delay.
-The next invocation of the function will cancel the previous.
import { debounce } from 'core/functools';
class Foo {
@debounce(500)
bla() {
console.log('Bang!');
}
}
-
-
-
- Decorator for Function.prototype.throttle.
-Returns a new function that allows to invoke a function, which it takes, not more often than the specified delay.
-The first invoking of a function will run immediately, but all rest invokes will be merged to one and
-executes after the specified delay.
import { throttle } from 'core/functools';
class Foo {
@throttle(500)
bla() {
console.log('Bang!');
}
}
-
-This module provides a bunch of functions and decorators to mark deprecated functions with the special flag.
-import { deprecate, deprecated } from 'core/functools/deprecation';
const foo = deprecate({
name: 'foo',
renamedTo: 'bar'
}, bar);
function bar() {
}
class Baz {
@deprecated({alternative: 'newMethod'})
oldMethod() {
}
newMethod() {}
}
-
-Marks the specified function as obsolescence
-additional options
-function to wrap
-Emits an obsolescence warning with the specified parameters
-additional options
-Marks the specified function as obsolescence
-function to wrap
-Decorator for deprecate
Decorator for deprecate.
-This overload adds a feature to provide additional options.
Returns a function that always returns the specified value
-Returns the specified value
-This module provides a bunch of functions and decorators to mark unimplemented functions with the special flag.
-import { unimplement, unimplemented } from 'core/functools/implementation';
const foo = unimplement({name: 'foo', alternative: 'bar'}, () => {
});
function bar() {
}
class Baz {
@unimplemented({alternative: 'newMethod'})
oldMethod() {
}
newMethod() {}
}
-
-Marks the specified function as unimplemented
-additional options
-function to wrap
-Emits an "unimplemented" warning with the specified parameters
-additional options
-Marks the specified function as unimplemented
-function to wrap
-Decorator for unimplement
Decorator for unimplement.
-This overload adds a feature to provide additional options.
This module provides a bunch of functions to create and implement traits. -A trait is the special kind of abstract class that is used as an interface. -Why would we need that? Well, unlike Java or Kotlin, TypeScript interfaces can't have default implementations of methods. -So we need to implement each method in our classes even if the implementation doesn't change. -This is where traits come into play. How it works? Ok, let's enumerate the steps to create a trait:
-abstract class Duckable {
abstract name: string;
abstract fly(): void;
}
-
-return Object.throw().abstract class Duckable {
abstract name: string;
abstract fly(): void;
getQuack(size: number): string {
return Object.throw();
}
}
-
-AddSelf helper to produce less code.abstract class Duckable {
abstract name: string;
abstract fly(): void;
getQuack(size: number): string {
return Object.throw();
}
// The first parameter provides a method to wrap.
// The second parameter declares which type has `self`.
static getQuack: AddSelf<Duckable['getQuack'], Duckable> = (self, size) => {
if (size < 10) {
return 'quack!';
}
if (size < 20) {
return 'quack!!!';
}
return 'QUACK!!!';
};
}
-
-We have created a trait. Now we can implement it in a simple class.
-implements keyword.
-Don't implement methods, which you want to store their default implementations.class DuckLike implements Duckable {
name: string = 'Bob';
fly(): void {
// Do some logic to fly
}
}
-
-Trait type.interface DuckLike extends Trait<typeof Duckable> {}
class DuckLike implements Duckable {
name: string = 'Bob';
fly(): void {
// Do some logic to fly
}
}
-
-derive decorator from core/functools/trait with our class and provide all traits that we want to implement automatically.import { derive } from 'core/functools/trait';
interface DuckLike extends Trait<typeof Duckable> {}
@derive(Duckable)
class DuckLike implements Duckable {
name: string = 'Bob';
fly(): void {
// Do some logic to fly
}
}
-
-import { derive } from 'core/functools/trait';
interface DuckLike extends Trait<typeof Duckable> {}
@derive(Duckable)
class DuckLike implements Duckable {
name: string = 'Bob';
fly(): void {
// Do some logic to fly
}
}
/// 'QUACK!!!'
console.log(new DuckLike().getQuack(60));
-
-import { derive } from 'core/functools/trait';
interface DuckLike extends Trait<typeof Duckable>, Trait<typeof AnotherTrait> {}
@derive(Duckable, AnotherTrait)
class DuckLike implements Duckable, AnotherTrait, SimpleInterfaceWithoutDefaultMethods {
name: string = 'Bob';
fly(): void {
// Do some logic to fly
}
}
-
-Besides, regular methods, you can also define get/set accessors like this:
-abstract class Duckable {
get canFly(): boolean {
return Object.throw();
}
set canFly(value: boolean) {};
static canFly(self: Duckable): string {
if (arguments.length > 1) {
const value = arguments[1];
// Setter code
} else {
return /* Getter code */;
}
}
}
-
-Derives the provided traits to a class. -The function is used to organize multiple implementing interfaces with the support of default methods.
-This module provides a bunch of functions and decorators to mark functions with different warnings.
-import { warn, warned } from 'core/functools/warning';
const foo = warn({context: 'unimplemented', name: 'foo', alternative: 'bar'}, () => {
});
function bar() {
}
class Baz {
@warned({context: 'deprecated', alternative: 'newMethod'})
oldMethod() {
}
newMethod() {}
}
-
-Marks a function with the specified warning
-additional options
-function to wrap
-Emits a warning with the specified parameters
-additional options
-Marks a function as non-recommended to use
-function to wrap
-Decorator for warn
Decorator for warn.
-This overload adds a feature to provide additional options.
This module provides a bunch of helper functions.
- - -This module provides an alias for core/prelude/i18n.
-This module provides a bunch of helpers to create and work with iterators.
- - -Creates an iterator based on the specified object and returns it. -The function has various overloads:
-import { intoIter } from 'core/iter';
// From 0 to Infinity
intoIter(true);
// From 0 to Infinity
intoIter(false);
-
-null or undefined, the function creates an empty iterator.import { intoIter } from 'core/iter';
// []
console.log([...intoIter(null)]);
-
-import { intoIter } from 'core/iter';
// [0, 1, 2]
console.log([...intoIter(3)]);
// [0, -1, -2]
console.log([...intoIter(-3)]);
-
-import { intoIter } from 'core/iter';
// ['f', 'o', 'o']
console.log([...intoIter('foo')]);
// ['1', '😃', 'à', '🇷🇺', '👩🏽❤️💋👨']
console.log([...intoIter('1😃à🇷🇺👩🏽❤️💋👨')]);
-
-import { intoIter } from 'core/iter';
// [1, 2]
console.log([...intoIter({a: 1, b: 2})]);
-
-import { intoIter } from 'core/iter';
// [1, 2]
console.log(function* () { yield* [1, 2]; });
-
-import { intoIter } from 'core/iter';
for await (const el of async function* () { yield* [1, 2]; }) {
// 1
// 2
console.log(el);
}
-
-import { intoIter } from 'core/iter';
// [1, 2]
console.log([...intoIter([1, 2].values())]);
-
-import { intoIter } from 'core/iter';
for await (const el of (async function* () { yield* [1, 2]; })()) {
// 1
// 2
console.log(el);
}
-
-Creates an infinite iterator and returns it. -If the passed value is true, the created iterator will produce values from zero to the positive infinity. -Otherwise, from zero to the negative infinity.
-Creates an empty iterator and returns it
-Creates an iterator from zero to the passed number (non including) and returns it
-Creates an iterator over the passed string by graphical letters
-Creates an iterator over values from the specified dictionary and returns it
-Creates an iterator over values from the specified array-like object and returns it
-Creates an iterator from the passed generator function and returns it
-Creates an iterator from the passed async generator function and returns it
-Creates a new iterator based on the specified iterable structure and returns it
-Creates a new async iterator based on the specified async iterable structure and returns it
-This module provides a bunch of helpers to combine different iterable structures.
- - -Takes iterable objects and returns a new iterator that produces values from them sequentially.
-import { sequence } from 'core/iterr/combinators';
// [1, 2, 3, 4, 5, 6]
console.log([
...sequence([1, 2], new Set([3, 4], [5, 6].values()))
]);
-
-If the first passed object has an asynchronous iterator, the result iterator will also be asynchronous.
-import { intoIter } from 'core/iter';
import { sequence } from 'core/iterr/combinators';
import { from, pick, andPick, assemble, streamArray } from 'core/json/stream';
const tokens = intoIter(from(JSON.stringify({
total: 3,
data: [
{
user: 'Bob',
age: 21
},
{
user: 'Ben',
age: 24
},
{
user: 'Rob',
age: 28
}
]
})));
const seq = sequence(
assemble(pick(tokens, 'total')),
streamArray(andPick(tokens, 'data'))
);
for await (const val of seq) {
// 3
// {index: 0, value: {user: 'Bob', age: 21}}
// {index: 1, value: {user: 'Ben', age: 24}}
// {index: 2, value: {user: 'Rob', age: 28}}
console.log(val);
}
-
-Takes iterable objects and returns a new iterator that produces values from them sequentially
-Takes async iterable objects and returns a new async iterator that produces values from them sequentially
-This module provides a bunch of helper functions to serialize/parse JSON data.
- - -The core/json/stream submodule provides API to work with JSON in a stream form.
import { convertIfDate } from 'core/json';
import { from, pick, streamArrray } from 'core/json/stream';
const
parser = streamArrray(pick(from('{"data": [1, 2, 3]}'), 'data'), {reviver: convertIfDate});
for await (const val of parser) {
// {index: 0, value: 1}
// {index: 1, value: 2}
// {index: 2, value: 3}
console.log(val);
}
-
-
-
- A reviver for the JSON.parse method: converts all strings that are looks like a date to Date.
import { convertIfDate } from 'core/json';
// true
console.log(JSON.parse('"2015-10-12"', convertIfDate).is(new Date(2015, 9, 12)));
-
-Reviver for the JSON.parse method: converts all strings that are looks like a date to Date
This module provides a bunch of functions to work with JSON in a stream form. -The submodules contain different classes to parse, filter and assemble JSON in a stream form.
- - -import { convertIfDate } from 'core/json';
import { from, pick, streamArrray } from 'core/json/stream';
const
parser = streamArrray(pick(from('{"data": [1, 2, 3]}'), 'data'), {reviver: convertIfDate});
for await (const val of parser) {
// {index: 0, value: 1}
// {index: 1, value: 2}
// {index: 2, value: 3}
console.log(val);
}
-
-
-
- Parses the specified iterable object as a JSON stream and yields tokens via a Generator.
-See core/json/stream/parser for more information.
import { from } from 'core/json/stream';
const
parser = from('{"data": [1, 2, 3]}');
for await (const token of parser) {
console.log(token);
}
-
-
-
- Takes the specified iterable object of tokens and filters it via the specified filter.
-See core/json/stream/filters for more information.
import { from, filter } from 'core/json/stream';
const
parser = filter(from('{"total": 3, "data": [1, 2, 3]}'), 'data');
for await (const token of parser) {
console.log(token);
}
-
-
-
- Takes the specified iterable object of tokens and pick from it value that matches the specified selector.
-See core/json/stream/filters for more information.
import { from, pick } from 'core/json/stream';
const
parser = pick(from('{"total": 3, "data": [1, 2, 3]}'), 'data');
for await (const token of parser) {
console.log(token);
}
-
-
-
- Takes the specified iterable object of tokens that has already been pick or pickAnd applied to,
-and picks from it a value that matches the specified selector.
-Use this function when you need to combine two or more Pick-s from a one token stream.
import { intoIter } from 'core/iter';
import { sequence } from 'core/iter/combinators';
import { from, pick, andPick, assemble, streamArray } from 'core/json/stream';
const tokens = intoIter(from(JSON.stringify({
total: 3,
data: [
{user: 'Bob', age: 21},
{user: 'Ben', age: 24},
{user: 'Rob', age: 28}
]
})));
const seq = sequence(
assemble(pick(tokens, 'total')),
streamArray(andPick(tokens, 'data'))
);
for await (const val of seq) {
console.log(val);
}
-
-
-
- Takes the specified iterable object of tokens and yields an assembled item from it.
-See core/json/stream/assembler for more information.
import { from, assemble } from 'core/json/stream';
const
parser = assemble(from('{"total": 3, "data": [1, 2, 3]}'));
for await (const val of parser) {
// {total: 3, data: [1, 2, 3]}
console.log(val);
}
-
-
-
- Takes the specified iterable object of tokens representing an object and yields assembled object items.
-See core/json/stream/streamers for more information.
import { from, streamObject } from 'core/json/stream';
const
parser = streamObject(from('{"total": 3, "data": [1, 2, 3]}'));
for await (const val of parser) {
// {key: 'total', value: 3}
// {key: 'data', value: [1, 2, 3]}
console.log(val);
}
-
-
-
- Takes the specified iterable object of tokens representing an array and yields assembled array items.
-See core/json/stream/streamers for more information.
import { from, streamArray } from 'core/json/stream';
const
parser = streamArray(from('[1, 2, 3]'));
for await (const val of parser) {
// {index: 0, value: 1}
// {index: 1, value: 2]}
// {index: 2, value: 3}
console.log(val);
}
-
-Takes the specified iterable object of tokens that has already been pick or pickAnd applied to,
-and picks from it a value that matches the specified selector.
-Use this function when you need to combine two or more Pick-s from a one token stream.
Takes the specified iterable object of tokens and yields an assembled item from it
-Takes the specified iterable object of tokens and filters it via the specified filter
-Parses the specified iterable object as a JSON stream and yields tokens via a Generator
-Takes the specified iterable object of tokens and picks from it a value that matches the specified selector
-Takes the specified iterable object of tokens representing an array and yields assembled array items
-Takes the specified iterable object of tokens representing an object and yields assembled object items
-This module provides a class to assemble JS values from an iterable of tokens produced by json/stream/parser Parser.
import Parser from 'core/json/stream/parser';
import Assembler from 'core/json/stream/assembler';
const
src = ['{"total": 2, "data', '": {"a": [1', ', true, "foo", 2', '], "b": [2, 3]}}'],
parser = Parser.from(src, new Assembler());
for await (const val of parser) {
// {total: 2, data: {a: [1, true, "foo", 2], b: [2, 3]}}
console.log(val);
}
-
-
-
- The instance constructor can take an object with optional parameter.
- - -false]Should or not parse numeric values as string literals.
-import Parser from 'core/json/stream/parser';
import Assembler from 'core/json/stream/assembler';
const
parser1 = Parser.from('-13.4e-3', new Assembler({numberAsString: true}));
for await (const val of parser1) {
// '-13.4e-3'
console.log(val);
}
const
parser2 = Parser.from('-13.4e-3', new Assembler());
for await (const val of parser2) {
// -0.0134
console.log(val);
}
-
-
-
- The option defines a reviver function similar to JSON.parse.
import { convertIfDate } from 'core/json';
import Parser from 'core/json/stream/parser';
import Assembler from 'core/json/stream/assembler';
const
parser = Parser.from(JSON.stringify([new Date()]), new Assembler({reviver: convertIfDate}))
for await (const val of parser) {
// true
console.log(val[0] instanceof Date);
}
-
-
-
- A property key of the active assembling value.
- - -A value of the active assembled item. -If it is a container (object or array), all new assembled values will be added to it.
- - -Indicates that the active value is fully assembled.
- - -A depth of the assembling structure.
- - -Processes the passed JSON token and yields the assembled values
-import Parser from 'core/json/stream/parser';
import Assembler from 'core/json/stream/assembler';
const
assembler = new Assembler();
for (const token of new Parser().processChunk('["foo"]')) {
// ["foo"]
console.log(...assembler.processToken(token));
}
-
-This module provides a bunch of classes to filter tokens produced by json/stream/parser Parser.
-Also, the module provides an abstract class to create your own filters.
import Parser from 'core/json/stream/parser';
import { Filter } from 'core/json/stream/filters';
const
parser = Parser.from(['{"total": 2, "data": [1, 2]}'], new Filter('data'));
tokens = [];
for await (const token of parser) {
tokens.push(token);
}
/* [
{name: 'startObject'},
{name: 'startKey'},
{name: 'stringChunk', value: 'data'},
{name: 'endKey'},
{name: 'keyValue', value: 'data'},
{name: 'startArray'},
{name: 'startNumber'},
{name: 'numberChunk', value: '1'},
{name: 'endNumber'},
{name: 'numberValue', value: '1'},
{name: 'startNumber'},
{name: 'numberChunk', value: '2'},
{name: 'endNumber'},
{name: 'numberValue', value: '2'},
{name: 'endArray'},
{name: 'endObject'}
] */
console.log(tokens);
-
-
-
- An instance of the Filter class takes an iterable object of parsed tokens, filters values matched with the specified condition, -and yields only the filtered tokens.
- - -If a filter condition is provided as a string, the Filter instance will interpret it as a property path that should preserve.
-import Parser from 'core/json/stream/parser';
import Assembler from 'core/json/stream/assembler';
import { Filter } from 'core/json/stream/filters';
const
src = ['{"total": 2, "data": {"a": [1, 2], "b": [2, 3]}}'],
parser = Parser.from(src, new Filter('data.a'), new Assembler());
for await (const val of parser) {
// {data: {a: [1, 2]}
console.log(val);
}
-
-
-
- If a filter condition is provided as a RegExp, the Filter instance will interpret it as a pattern of property paths that should preserve.
-import Parser from 'core/json/stream/parser';
import Assembler from 'core/json/stream/assembler';
import { Filter } from 'core/json/stream/filters';
const
src = ['{"total": 2, "data": {"a": [1, 2], "b": [2, 3]}}'],
parser = Parser.from(src, new Filter(/\b[ab]\b/), new Assembler());
for await (const val of parser) {
// {data: {a: [1, 2], b: [2, 3]}}
console.log(val);
}
-
-
-
- If a filter condition is provided as a function, the Filter instance will invoke it at each token and preserve it if the function returns true. -The filter function takes a property path and token.
-import Parser from 'core/json/stream/parser';
import Assembler from 'core/json/stream/assembler';
import { Filter } from 'core/json/stream/filters';
const
src = ['{"total": 2, "data": {"a": [1, true, "foo", 2], "b": [2, 3]}}'],
filter = (path, token) => path.includes('a') && token.name === 'numberValue',
parser = Parser.from(src, new Filter(filter), new Assembler());
for await (const val of parser) {
// {data: {a: [1, 2]}}
console.log(val);
}
-
-
-
- An instance of the Pick class takes an iterable object of parsed tokens and yields only tokens by the specified selector.
- - -If a pick selector is provided as a string, the Pick instance will interpret it as a property path that should pick.
-import Parser from 'core/json/stream/parser';
import Assembler from 'core/json/stream/assembler';
import { Pick } from 'core/json/stream/filters';
const
src = ['{"total": 2, "data": {"a": [1, 2], "b": [2, 3]}}'],
parser = Parser.from(src, new Pick('data.a'), new Assembler());
for await (const val of parser) {
// [1, 2]
console.log(val);
}
-
-
-
- If a pick selector is provided as a RegExp, the Pick instance will interpret it as a pattern of property path that should pick.
-import Parser from 'core/json/stream/parser';
import Assembler from 'core/json/stream/assembler';
import { Pick } from 'core/json/stream/filters';
const
src = ['{"total": 2, "data": {"a": [1, 2], "b": [2, 3]}}'],
parser = Parser.from(src, new Pick(/\b[ab]\b/), new Assembler());
for await (const val of parser) {
// [1, 2]
console.log(val);
}
-
-
-
- When you need to pick more than one set of tokens by a selector, use the additional multiple option.
import Parser from 'core/json/stream/parser';
import Assembler from 'core/json/stream/assembler';
import { Pick } from 'core/json/stream/filters';
const
src = ['{"total": 2, "data": {"a": [1, 2], "b": [2, 3]}}'],
parser = Parser.from(src, new Pick(/\b[ab]\b/, {multiple: true}), new Assembler());
const
values = [];
for await (const val of parser) {
values.push(val);
}
// [[1, 2], [2, 3]]
console.log(values);
-
-
-
- If a pick selector is provided as a function, the Pick instance will invoke it at each token and pick it if the function returns true. -The pick function takes a property path and token.
-import Parser from 'core/json/stream/parser';
import Assembler from 'core/json/stream/assembler';
import { Pick } from 'core/json/stream/filters';
const
src = ['{"total": 2, "data": {"a": [1, true, "foo", 2], "b": [2, 3]}}'],
selector = (path, token) => path.includes('a') && token.name === 'numberValue',
parser = Parser.from(src, new Pick(selector), new Assembler());
for await (const val of parser) {
// 1
console.log(val);
}
-
-
-
- When you need to pick more than one set of tokens by a selector, use the additional multiple option.
import Parser from 'core/json/stream/parser';
import Assembler from 'core/json/stream/assembler';
import { Pick } from 'core/json/stream/filters';
const
src = ['{"total": 2, "data": {"a": [1, true, "foo", 2], "b": [2, 3]}}'],
selector = (path, token) => path.includes('a') && token.name === 'numberValue',
parser = Parser.from(src, new Pick(selector), new Assembler());
const
values = [];
for await (const val of parser) {
values.push(val);
}
// [1, 2]
console.log(values);
-
-
-
- When creating a new filter class, extend it from the AbstractFilter and implement the checkToken method.
-In addition, you can override finishTokenProcessing if needed.
import type { Token } from 'core/json/stream/parser';
import Super from 'core/json/stream/filters/abstract-filter';
import type { TokenFilter, FilterOptions } from 'core/json/stream/filters/interface';
export default class PickObject extends Super {
public constructor(filter: TokenFilter, opts?: FilterOptions) {
super(filter, opts);
}
/** @inheritDoc */
protected*checkToken(chunk: Token): Generator<boolean | Token> {
switch (chunk.name) {
case 'startObject':
case 'startArray':
if (this.filter(this.stack, chunk)) {
yield chunk;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.processToken = this.passObject;
this.depth = 1;
return true;
}
break;
default:
// Do nothing
}
return false;
}
}
-
-
-
- The instance constructor takes two parameters.
-The first one is a filter. The second one is an object with optional filter parameters.
-A filter can be defined via a string, regular expression, or function.
-By providing the optional multiple parameter, you can customize should or not to stop filter after the first successful token.
Processes the passed JSON token and yields tokens.
-import Parser from 'core/json/stream/parser';
import { Pick } from 'core/json/stream/filters';
const
pick = new Pick('0'),
tokens = [];
for (const token of new Parser().processChunk('["foo"]')) {
tokens.push(...pick.processToken(token));
}
tokens.push(...pick.finishTokenProcessing());
-
-
-
- Closes all unclosed tokens and returns a Generator of filtered tokens. -The method must be called after the end of filtration.
-This module provides a class to parse JSON from separated string chunks, i.e., stream form. -The class instance takes a JSON chunk and returns a Generator that produces parsed JSON tokens; otherwise, it throws a syntax error.
- - -import Parser from 'core/json/stream/parser';
const
parser = Parser.from(['{"key', '": 2', '}']);
tokens = [];
for await (const token of parser) {
tokens.push(token);
}
/* [
{name: 'startObject'},
{name: 'startKey'},
{name: 'stringChunk', value: 'key'},
{name: 'endKey'},
{name: 'keyValue', value: 'key'},
{name: 'startNumber'},
{name: 'numberChunk', value: '2'},
{name: 'endNumber'},
{name: 'numberValue', value: '2'},
{name: 'endObject'}
] */
console.log(tokens);
-
-
-
- The method parses the specified iterable object as a JSON stream and yields tokens via an asynchronous Generator.
-import Parser from 'core/json/stream/parser';
const
parser = Parser.from('[1]');
for await (const token of parser) {
// {name: 'startArray'},
// {name: 'startNumber'},
// {name: 'numberChunk', value: '1'},
// {name: 'endNumber'},
// {name: 'numberValue', value: '1'},
// {name: 'endArray'}
console.log(token);
}
-
-The method can also take a list of token processors to apply.
-import Parser from 'core/json/stream/parser';
import Assembler from 'core/json/stream/assembler';
import { Filter } from 'core/json/stream/filters';
const
parser = Parser.from('[{"a": 1}, {"b": 2}]', new Filter(/\d+\.a/), new Assembler());
for await (const result of parser) {
// [{a: 1}]
console.log(result);
}
-
-
-
- The method processes the passed JSON chunk and yields tokens via a Generator.
-import Parser from 'core/json/stream/parser';
const
parser = new Parser();
/* [
{name: 'startArray'},
{name: 'startNumber'},
{name: 'numberChunk', value: '1'},
{name: 'endNumber'},
{name: 'numberValue', value: '1'},
{name: 'endArray'}
] */
console.log([...parser.processChunk('[1]')]);
-
-
-
- This is the list of data objects produced by Parser in the correct order:
-// A sequence can have 0 or more items.
// A value is one of: object, array, string, number, null, true, false.
// A parser produces a sequence of values:
// Object
({name: 'startObject'});
// Sequence of object properties: key, then value
({name: 'endObject'});
// ----
// Array
({name: 'startArray'});
// Sequence of values
({name: 'endArray'});
// ----
// Key
({name: 'startKey'});
// Sequence of string chunks:
({name: 'stringChunk', value: 'string value chunk'});
({name: 'endKey'});
({name: 'keyValue', value: 'key value'});
// ----
// String
({name: 'startString'});
// Sequence of string chunks:
({name: 'stringChunk', value: 'string value chunk'});
({name: 'endString'});
({name: 'stringValue', value: 'string value'});
// ----
// Number
({name: 'startNumber'});
// Sequence of number chunks (as strings):
({name: 'numberChunk', value: 'string value chunk'});
({name: 'endNumber'});
({name: 'numberValue', value: 'string value'});
// ----
// null, true, false
({name: 'nullValue', value: null});
({name: 'trueValue', value: true});
({name: 'falseValue', value: false});
-
-All value chunks (stringChunk and numberChunk) should be concatenated in order to produce a final value. -Empty string values may have no chunks. String chunks may have empty values.
-Important: values of numberChunk and numberValue are strings, not numbers.
-It is up to a downstream code to convert it to a number using parseInt(x), parseFloat(x) or simply x => +x.
All items follow in the correct order. If something is going wrong, a parser will produce an error event. For example:
-All startXXX are balanced with endXXX.
Between startKey and endKey can be zero or more stringChunk items. No other items can be seen.
After startObject optional key-value pairs emitted in a strict pattern: a key-related item, then a value, and
-this cycle can be continued until all key-value pairs are streamed.
All endObject are balanced with the corresponding startObject.
endObject cannot close startArray.
Between startString and endString can go 0 or more stringChunk, but no other items.
endKey can be optionally followed by keyValue, then a new value will be started, but no endObject.
In short, the item sequence is always correctly formed. No need to do unnecessary checks.
-This module provides a bunch of classes to stream object or array elements. -Also, the module provides an abstract class to create your own streamers
- - -import { convertIfDate } from 'core/json';
import Parser from 'core/json/stream/parser';
import { ArrayStreamer } from 'core/json/stream/assembler';
const
parser = Parser.from('[1, {"a": true}, true, -0.234]', new ArrayStreamer({reviver: convertIfDate}));
for await (const val of parser) {
// {index: 0, value: 1}
// {index: 1, value: {a: true}}
// {index: 2, value: true}
// {index: 3, value: -0.234}
console.log(val);
}
-
-
-
- An instance of the ObjectStreamer class takes an iterable object of parsed tokens of some object and -yields assembled elements of this object.
-import Parser from 'core/json/stream/parser';
import { ObjectStreamer } from 'core/json/stream/assembler';
const
parser = Parser.from('{"a": 1, "b": true}', new ObjectStreamer());
for await (const val of parser) {
// {key: 'a', value: 1}
// {key: 'b', value: true}
console.log(val);
}
-
-
-
- An instance of ArrayStreamer ObjectStreamer class takes an iterable object of parsed tokens of some array and -yields assembled elements of this array.
-import Parser from 'core/json/stream/parser';
import { ArrayStreamer } from 'core/json/stream/assembler';
const
parser = Parser.from('[1, {"a": true}, true, -0.234]', new ArrayStreamer());
for await (const val of parser) {
// {index: 0, value: 1}
// {index: 1, value: {a: true}}
// {index: 2, value: true}
// {index: 3, value: -0.234}
console.log(val);
}
-
-
-
- When creating a new streamer class, extend it from the AbstractStreamer and implement the checkToken and push methods.
import type { Token } from 'core/json/stream/parser';
import type { AssemblerOptions } from 'core/json/stream/assembler';
import Streamer, { StreamedArray } from 'core/json/stream/streamers/interface';
export default class ArrayStreamer<T = unknown> extends Streamer<StreamedArray<T>> {
/**
* Index of the current streamed array element
*/
protected index: number = 0;
public constructor(opts?: AssemblerOptions) {
super(opts);
}
/** @inheritDoc */
protected checkToken(chunk: Token): boolean {
if (chunk.name !== 'startArray') {
throw new TypeError('The top-level object should be an array');
}
return true;
}
/** @inheritDoc */
protected*push(): Generator<StreamedArray<T>> {
const
{value} = this.assembler;
if (Object.isArray(value) && value.length > 0) {
yield {
index: this.index++,
value: Object.cast(value.pop())
};
}
}
}
-
-
-
- The instance constructor takes one optional parameter. -It is an object with parameters for a token [[Assembler]].
- - -Processes the passed JSON token and yields values.
-import Parser from 'core/json/stream/parser';
import { ArrayStreamer } from 'core/json/stream/streamers';
const
streamer = new Streamer(),
values = [];
for (const token of new Parser().processChunk('["foo"]')) {
values.push(...streamer.processToken(token));
}
// ['foo']
console.log(values);
-
-This module provides API to work with a persistent key-value storage using different runtime engines, like localStorage, -indexedDb, SQLite, etc.
- - -browser-localstoragebrowser-indexeddbnode-localstorageThe module has interfaces to work with storage in a synchronous and asynchronous way. -In the case of asynchronous API, all defined methods have the same input parameters as the synchronous API but return promises. -Notice, not each engine implements the synchronous API, so we recommend preferring to use asynchronous API in most cases.
- - -Both API exposes methods to implement simple CRUD operations.
- - -Returns true if a value by the specified key exists in the storage. -Notice, the method can take a list of additional parameters provided to the used storage' engine.
-import * as kv from 'core/kv-storage';
kv.set('bla', 1);
console.log(kv.has('bla') === true);
-
-
-
- Returns a value from the storage by the specified key.
-The returning value automatically parses by using Object.parse from a string to equivalent JS value, i.e.,
-'1' will be parsed to 1, 'true' to true, '2021-07-09T08:15:57.753Z' to Date, etc.
Notice, the method can take a list of additional parameters provided to the used storage' engine.
-import * as kv from 'core/kv-storage';
kv.set('bla', 1);
console.log(kv.get('bla') === 1);
-
-
-
- Saves a value to the storage by the specified key.
-The value to parse automatically serializes to a string by using Object.trySerialize, i.e.,
-arrays and dictionaries will be serialized to JSON, etc.
Notice, the method can take a list of additional parameters provided to the used storage' engine.
-import * as kv from 'core/kv-storage';
kv.set('bla', {a: 1});
console.log(kv.get('bla').a === 1);
-
-
-
- Removes a value from the storage by the specified key. -Notice, the method can take a list of additional parameters provided to the used storage' engine.
-import * as kv from 'core/kv-storage';
kv.set('bla', 1);
console.log(kv.has('bla') === true);
kv.remove('bla');
console.log(kv.has('bla') === false);
-
-
-
- Clears the storage by the specified filter and returns a list of removed keys. -Notice, the method can take a list of additional parameters provided to the used storage' engine.
-import * as kv from 'core/kv-storage';
kv.set('bla', 1);
kv.set('bla2', 2);
// ['bla']
kv.clear((el, key) => el === 1);
console.log(kv.has('bla') === false);
console.log(kv.has('bla2') === true);
// ['bla2']
kv.clear();
console.log(kv.has('bla2') === false);
-
-
-
- All values are stored within a local storage in the global namespace, i.e., you can override any value you have. -If you want to isolate data from other data, you can specify the custom namespace. Mind, you still can override or remove these -values from the storage by using global API.
-import * as kv from 'core/kv-storage';
kv.set('bla', 1);
const blaStore = kv.namespace('[[BLA]]');
blaStore.set('baz', true);
blaStore.clear();
console.log(kv.has('bla') === true);
blaStore.set('foo', 1);
kv.clear();
console.log(blaStore.has('foo') === false);
-
-
-
- If you need to work with an asynchronous local storage, you can use `asyncLocal. The API is pretty similar to local, but its -methods return a promise instead of a raw result.
-import { asyncLocal } from 'core/kv-storage';
asyncLocal.set('bla', 1).then(async () => {
console.log(await asyncLocal.get('bla') === 1);
});
const blaStore = asyncLocal.namespace('[[BLA]]');
blaStore.set('bla', 1).then(async () => {
console.log(await blaStore.get('bla') === 1);
});
-
-
-
- If you need to store data only during the active session, you can use session and asyncSession API-s.
import { session, asyncSession } from 'core/kv-storage';
session.set('bla', 1);
console.log(session.get('bla') === 1);
session.clear();
asyncSession.set('bla', 1).then(async () => {
console.log(await asyncSession.get('bla') === 1);
});
const blaStore = asyncSession.namespace('[[BLA]]');
blaStore.set('bla', 1).then(async () => {
console.log(await blaStore.get('bla') === 1);
});
-
-
-
- You can pass your storage API as a strategy to another function or method.
-import { local, asyncLocal, SyncStorage, AsyncStorage } from 'core/kv-storage';
function save(kv: SyncStorage): void {
kv.set('bla', 1);
console.log(kv.get('bla') === 1);
console.log(kv.has('bla') === true);
kv.set('obj', {a: 1});
console.log(kv.get('obj').a === 1);
kv.remove('bla');
kv.clear((el, key) => el.a === 1);
}
save(local);
function asyncSave(kv: AsyncStorage): void {
asyncLocal.set('bla', 1).then(async () => {
console.log(await asyncLocal.get('bla') === 1);
});
}
save(asyncLocal);
-
-
-
- By default, in a browser, the module uses native window.localStorage and window.sessionStorage API-s.
-Also, there is a storage based on IndexedDb. Use the factory method to specify an engine to store.
import { factory } from 'core/kv-storage';
import * as idb from 'core/kv-storage/engines/browser-indexeddb';
const asyncStorage = factory(idb.asyncLocalStorage, true);
asyncStorage.set('bla', 1).then(async () => {
console.log(await asyncLocal.get('bla') === 1);
});
const asyncSessionStorage = factory(idb.asyncSessionStorage, true);
-
-
-
- You can specify your engine by using the factory method.
import { factory } from 'core/kv-storage';
const syncStorage = factory(YourSyncStorage);
const asyncStorage = factory(YourAsyncStorage, true);
-
-The wrapped engine need to have CRUD methods from the interface:
-interface StorageEngine {
get?(key: unknown): unknown;
getItem?(key: unknown): unknown;
set?(key: unknown, value: unknown): unknown;
setItem?(key: unknown, value: unknown): unknown;
remove?(key: unknown): unknown;
removeItem?(key: unknown): unknown;
delete?(key: unknown): unknown;
exist?(key: unknown): unknown;
exists?(key: unknown): unknown;
includes?(key: unknown): unknown;
has?(key: unknown): unknown;
keys?(): Iterable<unknown>;
clear?(): unknown;
clearAll?(): unknown;
truncate?(): unknown;
}
-
-API for asynchronous local storage
-API for asynchronous session storage
-Alias for a clear method of the synchronous local storage API
-Alias for a get method of the synchronous local storage API
-Alias for a has method of the synchronous local storage API
-API for synchronous local storage
-Alias for a namespace method of the synchronous local storage API
-Alias for a remove method of the synchronous local storage API
-API for synchronous session storage
-Alias for a set method of the synchronous local storage API
-Creates a new kv-storage API with the specified engine
-if true, then the storage is implemented async interface
-This module provides a function to create a lazy structure based on the provided function or class. -The created structure is a function with the pre-defined methods and properties from the passed scheme and/or class prototype. -All property or method actions will be intercepted and accumulated in a queue. After invoking the result function, -all accumulated actions will be executed.
- - -import makeLazy from 'core/lazy';
function createUser(name, age) {
return {
name,
age,
showInfo() {
console.log(`Name: ${this.name}; Age: ${this.age}`);
}
};
}
const lazyUser = makeLazy(
createUser,
// Declaring a scheme with the result of the original function invoking
{
// A string property with the default value
name: '',
// A number property with the default value
age: 0,
// A method
showInfo: Function
}
);
// Nothing happens at all
lazyUser.age = 45;
lazyUser.showInfo();
// Invoking the lazy function and passing necessary arguments.
// After invoking we can see in a console the result of calling `showInfo`:
// `Name: Bob; Age: 45`
const user = lazyUser('Bob', 10);
-
-
-
- import makeLazy from 'core/lazy';
class User {
constructor(name, age) {
this.name = name;
this.age = age;
this.config = {
errorHandler() {
console.log('Boom!');
}
};
}
showInfo() {
console.log(`Name: ${this.name}; Age: ${this.age}`);
}
}
const LazyUser = makeLazy(
User,
// Declaring only properties.
// All methods are taken automatically from the class prototype.
{
config: {
attr: {},
errorHandler: Function
}
}
);
// Nothing happens at all
LazyUser.showInfo();
LazyUser.config.attr = 'value';
LazyUser.config.errorHandler();
// Creating an instance of the lazy class and passing necessary arguments to its constructor.
// After invoking we can see in a console the results of calling `showInfo` and `config.errorHandler()`:
// `Name: Bob; Age: 23`
// `Boom!`
const user = new LazyUser('Bob', 23);
// Because of `LazyUser.config.attr = 'value'`
console.log(user.config.attr === 'value');
// After invoking we can see in a console the results of `showInfo` and `config.errorHandler()`:
// `Name: Fred; Age: 56`
// `Boom!`
const user2 = new LazyUser('Fred', 56);
-
-
-
- There is possibility to provide hook handlers on of some structure actions,
-like getting or setting a property value or method invoking. These handlers take an array of the already created Lazy instances.
-Other arguments depend on the hook type.
import makeLazy from 'core/lazy';
class RenderEngine {
component(name, opts) {
if (opts == null) {
return /* Component declaration */;
}
return /* Create a component */;
}
}
const LazyRenderEngine = makeLazy(
RenderEngine,
{
config: {
attr: {},
errorHandler: Function
}
},
{
get: {
'config.attrs'(contexts) {
return contexts.at(-1).config.attrs;
}
},
set: {
'config.attrs'(contexts, value) {
contexts.forEach((ctx) => {
ctx.config.attrs = value;
});
}
},
call: {
component(contexts, ...args) {
if (args.length > 1) {
contexts.forEach((ctx) => {
ctx.component(...args);
});
return;
}
return contexts.at(-1).component(...args);
}
}
}
);
const
engine1 = new LazyRenderEngine(),
engine2 = new LazyRenderEngine();
// These actions will be provided to the already created instances,
// because we specify hook handlers with this logic
// Will invoke a handler `set.config.attrs`
LazyRenderEngine.config.attrs = 'value';
// Will invoke a handler `get.config.attrs`
console.log(LazyRenderEngine.config.attrs);
// Will invoke a handler `call.component`
LazyRenderEngine.component('newAwesomeComponent', {
props: { /* ... */ },
render: () => { /* ... */ }
});
-
-Creates a new function based on the passed function or class and returns it. -The new function accumulates all method and properties actions into a queue. -The queue will drain after invoking the created function.
-This module provides a class to organize a double-ended two-way linked list. -For convenience, the list API is similar to the regular JS Array API.
-import LinkedList from 'core/linked-list';
const
list = new LinkedList();
list.push(10, 11);
// 2
console.log(list.length);
// 11
console.log(list.pop());
-
-
-
- The LinkedList constructor can take any Iterable object whose elements will be used to populate the list.
-import LinkedList from 'core/linked-list';
const
list = new LinkedList([1, 2, 3]);
// 3
console.log(list.length);
-
-
-
- Data of the first node in the list.
-import LinkedList from 'core/linked-list';
const
list = new LinkedList([1, 2, 3]);
// 1
console.log(list.first);
-
-
-
- Data of the last node in the list.
-import LinkedList from 'core/linked-list';
const
list = new LinkedList([1, 2, 3]);
// 3
console.log(list.last);
-
-
-
- Clears all nodes from the list.
-import LinkedList from 'core/linked-list';
const
list = new LinkedList([1, 2, 3]);
list.clear();
console.log(list.first); // undefined
console.log(list.last); // undefined
console.log(list.length); // 0
-
-
-
- Returns an iterator over the data in the list. -The traversal will proceed from the last node to the first.
-import LinkedList from 'core/linked-list';
const
list = new LinkedList([1, 2, 3]);
// 3, 2, 1
console.log(...list.reverse());
-
-
-
- For convenience, the LinkedList API is similar to the regular JS Array API:
-Adding and removing is done through the push/pop/shift/unshift methods.
import LinkedList from 'core/linked-list';
const
list = new LinkedList();
list.push(10, 11);
list.unshift(9);
// 11
console.log(list.pop());
// 9
console.log(list.shift());
-
-Checking if a node is in the list with a given value is done using includes.
import LinkedList from 'core/linked-list';
const
list = new LinkedList([-0, 1, NaN, 2]);
console.log(list.includes(0)); // true
console.log(list.includes(1)); // true
console.log(list.includes(NaN)); // true
console.log(list.includes(12)); // false
-
-Use the length getter to get the number of nodes in the list. The push/unshift methods also return the length of the list.
import LinkedList from 'core/linked-list';
const
list = new LinkedList();
list.push(10, 11); // 2
list.unshift(9); // 3
// 3
console.log(list.length);
-
-To create a new list based on another, use slice.
import LinkedList from 'core/linked-list';
const
list = new LinkedList([1, 2, 3]);
// [3]
console.log([...list.slice(-1)]);
// [1, 2]
console.log([...list.slice(0, -1)]);
-
-There are 2 iterators to traverse the list: values (used by default) and reverse.
-Note that unlike arrays, here reverse returns an iterator, not a new linked list.
-However, you can pass this iterator to the constructor when creating a new list.
import LinkedList from 'core/linked-list';
const
list = new LinkedList([1, 2, 3]);
// [1, 2, 3]
console.log([...list]);
// [3, 2, 1]
console.log([...list.reverse()]);
const
reversedList = new LinkedList([...list.reverse()]);
// [3, 2, 1]
console.log([...reversedList]);
-
-This module provides API to log different system/application events.
-import log from 'core/log';
log.info('Info message');
log.warn('Some warning');
log.error('Some error', new Error('Boom!'));
log.namespace('net').error('Some error with the context');
-
-API for logging
-Mixes two objects
-Creates a pipeline by using the config -(returns undefined if there are not enough data to create one)
-Creates an object of styles where each log level property merged with the default property of a log styles config
-Sends data to every logging pipeline
-Returns a function that creates an engine of the specified class
-Returns a function that creates an engine of the specified class
-constructor or just a class
-Returns a function that creates an engine of the specified class
-Returns a function that creates a middleware of the specified class
-Returns a function that creates a middleware of the specified class
-Returns a function that creates a middleware of the specified class
-Returns a function that creates a middleware of the specified class
-constructor or just a class
-Returns a function that creates a middleware of the specified class
-This module provides a middleware to extract information from an error log event and store
-it within the additionals dictionary of the event.
A constructor of the extractor middleware takes a list of objects that implement the ErrorDetailsExtractor interface.
-These objects are used to match an error and extract details.
-If the error doesn't match with any ErrorDetailsExtractor, the middleware gets only enumerable properties from the error.
new ExtractorMiddleware(
{
target: RequestError,
extract: (err) => { /* Return details */ }
},
{
target: URLError,
extract: (err) => { /* Return details */ }
}
);
-
-Also, the middleware is capable of processing the hierarchy of nested errors. If an error from some log event has the cause
-property with another error inside, the middleware processes that error in the same way as the log event's error.
-If the cause error has another cause error inside then, the middleware goes further by the hierarchy, i.e., it works recursively.
The result of the error processing is following:
-{
error: {
// An object of enumerable properties from the error or details returned by the error extractor
details: {...},
cause: {
error: {
// A name of the caused error
name: '...',
// A message of the caused error
message: '...'
},
// Details of the caused error
details: {...},
cause: {
...
}
}
}
}
-
-
-
- The middleware should be set up via config in config/index. It should be added to the middleware array property of a
-pipeline.
To install it without the custom detail extractors, just pass a string:
-{
log: {
pipelines: [{
middlewares: ['extractor']
// ...
}]
}
}
-
-To install the middleware with the custom detail extractors, use the following form:
-{
log: {
pipelines: [{
middlewares: [['extractor', [new RequestErrorDetailsExtractor()]]]
// ...
}]
}
}
-
-The first opened bracket here is an array of middlewares. The second one is a tuple of the middleware name and its parameters.
-This module provides a middleware to extract information from an error log event and store
-it within the additionals dictionary of the event.
A constructor of the extractor middleware takes a list of objects that implement the ErrorDetailsExtractor interface.
-These objects are used to match an error and extract details.
-If the error doesn't match with any ErrorDetailsExtractor, the middleware gets only enumerable properties from the error.
new ExtractorMiddleware(
{
target: RequestError,
extract: (err) => { /* Return details */ }
},
{
target: URLError,
extract: (err) => { /* Return details */ }
}
);
-
-Also, the middleware is capable of processing the hierarchy of nested errors. If an error from some log event has the cause
-property with another error inside, the middleware processes that error in the same way as the log event's error.
-If the cause error has another cause error inside then, the middleware goes further by the hierarchy, i.e., it works recursively.
The result of the error processing is following:
-{
error: {
// An object of enumerable properties from the error or details returned by the error extractor
details: {...},
cause: {
error: {
// A name of the caused error
name: '...',
// A message of the caused error
message: '...'
},
// Details of the caused error
details: {...},
cause: {
...
}
}
}
}
-
-
-
- The middleware should be set up via config in config/index. It should be added to the middleware array property of a
-pipeline.
To install it without the custom detail extractors, just pass a string:
-{
log: {
pipelines: [{
middlewares: ['extractor']
// ...
}]
}
}
-
-To install the middleware with the custom detail extractors, use the following form:
-{
log: {
pipelines: [{
middlewares: [['extractor', [new RequestErrorDetailsExtractor()]]]
// ...
}]
}
}
-
-The first opened bracket here is an array of middlewares. The second one is a tuple of the middleware name and its parameters.
-This module provides API to extract data types from mime-type/DATA:URI strings.
- - -Returns a type of data from the specified mime type string.
-import { getDataType } from 'core/mine-type';
console.log(getDataType('application/json')); // json
-
-
-
- Returns a type of data from the specified DATA:URI string.
-import { getDataTypeFromURI } from 'core/mine-type';
console.log(getDataTypeFromURI('data:application/javascript;...')); // text
-
-Returns a type of data from the specified mime type string
-This module provides API to work with a network, such as testing of the network connection, etc.
-import * as net from 'core/net';
(async () => {
console.log(await net.isOnline());
})();
-
-
-
- To enable online checking you need to add a configuration within your runtime config module (src/config).
config
-import { extend } from '@v4fire/core/config';
extend({
online: {
// URL to check the online connection
// (with the "browser.request" engine can be used only image URL-s)
checkURL: 'https://google.com/favicon.ico',
// Default options:
// How often need to check the online connection (ms)
checkInterval: (30).seconds(),
// Timeout of a connection checking request
checkTimeout: (2).seconds(),
// The maximum number of retries to check the online connection
retryCount: 3,
// How often to update the last online connection time
lastDateSyncInterval: (1).minute(),
// True, if we need to save a time of the last online connection in the local cache
persistence: true,
// How long to store a checking result in the local cache
cacheTTL: (1).second()
}
});
-
-
-
- | EventName | -Description | -Payload description | -Payload | -
|---|---|---|---|
online |
-The network connection has appeared | -- | -- | -
offline |
-The network connection has lost | -When was the last connection | -Date |
-
status |
-The network connection status has been changed | -Connection status | -NetStatus |
-
import * as net from 'core/net';
net.emitter.emitter.on('online', () => {
console.log("I'm online!");
});
net.emitter.emitter.on('offline', (lastOnlineDate) => {
console.log(`I have been online at ${lastOnlineDate}`);
});
net.emitter.emitter.on('status', (e) => {
console.log(`Connection is ${e.status ? 'online' : 'offline'}`);
if (!e.status) {
console.log(`I have been online at ${e.lastOnline}`);
}
});
-
-
-
- The module supports different implementations to check the online connection.
-The implementations are placed within core/net/engines. By default, it uses a strategy by requesting
-some recourses from the internet, like a Google favicon. But you can manually provide an engine to use.
import * as net from 'core/net';
(async () => {
// Loopback. Always online.
console.log(await net.isOnline(async () => true));
})();
-
-Synchronizes the online status with a local storage
-Updates the online status
-This module provides a bunch of helper functions to work with an object.
-The module returns a function to create clones of the passed objects. -This function creates a Proxy object based on the given to create a clone. -It means that this operation is lazily and very effective but depends on the native support of proxy objects.
-import proxyClone from 'core/object/proxy-clone';
const original = {
user: {
name: 'Bob',
age: 56,
skills: ['singing', 'dancing', 'programming']
}
};
const
clone = proxyClone(original);
clone.user.name = 'Jack';
clone.user.skills.push('boxing');
console.log(clone.user.name !== original.user.name);
// ['singing', 'dancing', 'programming', 'boxing']
console.log(clone.user.skills);
// ['singing', 'dancing', 'programming']
console.log(original.user.skills);
-
-
-
- Because the process of cloning uses native Proxy objects, there are a few limitations:
-Object.preventExtension at a clone object because it should be applied to the original object.Object.isExtensible always returns a value from the original object.configurable: false attribute in the original object.The module also exports a common implementation to clone objects. If the runtime supports Proxy API, it will be used.
-import { clone } from 'core/object/proxy-clone';
const original = {
user: {
name: 'Bob',
age: 56,
skills: ['singing', 'dancing', 'programming']
}
};
const
clone = clone(original);
clone.user.name = 'Jack';
clone.user.skills.push('boxing');
console.log(clone.user.name !== original.user.name);
// ['singing', 'dancing', 'programming', 'boxing']
console.log(clone.user.skills);
// ['singing', 'dancing', 'programming']
console.log(original.user.skills);
-
-Returns a clone of the specified object. -If the runtime supports Proxy, it will be used to clone.
-Returns a clone of the specified object. -The function uses a Proxy object to create a clone. The process of cloning is a lazy operation.
-Returns a raw value by a key from the specified store
-Resolves the specified target by a value from the store and returns it
-The module returns a function to create read-only views of the passed objects. -This function creates a Proxy object based on the given to create a view. -It means that this operation is lazily and very effective but depends on the native support of proxy objects.
-import proxyReadonly from 'core/object/proxy-readonly';
const original = {
user: {
name: 'Bob',
age: 56,
skills: ['singing', 'dancing', 'programming']
}
};
const
readonly = proxyReadonly(original);
try {
readonly.user.name = 'Jack';
} catch (err) {
console.log(err);
}
try {
readonly.user.skills.push('boxing');
} catch (err) {
console.log(err);
}
console.log(readonly.user.name === original.user.name);
// ['singing', 'dancing', 'programming']
console.log(readonly.user.skills);
// ['singing', 'dancing', 'programming']
console.log(original.user.skills);
-
-
-
- Because the process of cloning uses native Proxy objects, there are a few limitations:
-Object.preventExtension at a clone object because it should be applied to the original object.The module also exports a common implementation to make objects read-only. If the runtime supports Proxy API, it will be used.
-import { readonly } from 'core/object/proxy-readonly';
const original = {
a: 1
};
const
readonly = proxyReadonly(original);
try {
readonly.a++;
} catch (err) {
console.log(err);
}
// 1
console.log(readonly.a);
-
-Returns a read-only view of the specified object. -The function uses a Proxy object to create a view.
-Returns a read-only view of the specified object. -If the runtime supports Proxy, it will be used to create a view.
-This module provides a function to find an element from an object by the specified parameters. -The function is useful for declarative searching from data without functions, i.e., we can take parameters to search from JSON -or other stuff.
- - -When the search function takes a plain object and some where condition, it returns the object itself if it matches the condition.
-Otherwise, it returns undefined.
import select from 'core/object/select';
// {foo: 1, bar: 2}
select({foo: 1, bar: 2}, {where: {foo: 1}});
// undefined
select({foo: 1, bar: 2}, {where: {foo: 1, bar: 3}});
-
-The matching process is recursive, i.e., it checks the nested structure of the condition and object.
-import select from 'core/object/select';
// {foo: {b: [1, 2, 3]}}
select({foo: {b: [1, 2, 3]}}, {where: {foo: {b: [1, 2, 3]}}});
// undefined
select({foo: {b: [1, 2, 3]}}, {where: {foo: {b: [1]}}});
-
-If the object to search doesn't have some property from where, the property will be ignored if other conditions are matched.
import select from 'core/object/select';
// {foo: 1, bar: 2}
select({foo: 1, bar: 2}, {where: {baz: 78, foo: 1}});
// undefined
select({foo: 1, bar: 2}, {where: {baz: 78}});
-
-
-
- When the search function takes an iterable object and some where condition, it returns the first element from the object
-that matches the condition. If there are no elements that match the condition, the function returns undefined.
import select from 'core/object/select';
// {foo: 1, bar: 2}
select([{bla: 12}, {foo: 1, bar: 2}], {where: {foo: 1}});
// undefined
select(new Set([{bla: 12}, {foo: 1, bar: 2}]), {where: {foo: 1, bar: 3}});
-
-
-
- When where contains an array, it will be represented as the OR condition.
import select from 'core/object/select';
// {test: 2}
select({test: 2}, {where: [{test: 1}, {test: 2}]});
-
-
-
- By using the from option, you can define a start point to search.
import select from 'core/object/select';
// {foo: 1, bar: 2}
select({my: {data: {foo: 1, bar: 2}}}, {where: {foo: 1}, from: 'my.data'});
// undefined
select(new Map([[0, {data: {foo: 1, bar: 2}}]]), {where: {foo: 21}, from: [0, 'data']});
-
-If there is no provided where condition but specified from, the function returns a value by the path.
import select from 'core/object/select';
// {foo: 1, bar: 2}
select({my: {data: {foo: 1, bar: 2}}}, {from: 'my.data'});
// {foo: 1, bar: 2}
select(new Map([[0, {data: {foo: 1, bar: 2}}]]), {from: [0, 'data']});
-
-Finds an element from an object by the specified parameters
-object to search
-The module provides API to watch changes of JS objects, like, maps, arrays, etc. -The watching supports different strategies:
-By default, if runtime supports Proxy objects, then will be used an approach based on these objects. -Otherwise, will be used a strategy based on accessors. Also, you can manually define a strategy to use for each watcher.
-import watch from 'core/object/watch';
const obj = {
a: 1,
b: [],
c: new Map(),
d: {}
};
const {proxy, unwatch} = watch(obj, {deep: true, immediate: true}, (value, oldValue, info) => {
console.log(value, oldValue, info.path);
});
proxy.a++;
proxy.b.push(1);
proxy.c.set(1, 2);
proxy.d.foo = 'bar';
unwatch();
-
-
-
- The assessors' based engine doesn't watch array indices. To add or remove new elements to an array, use array methods.
-Or, you can use set/unset methods from a watcher to add or remove elements by a path.
The assessors' based engine doesn't watch newly added elements.
-To add watching for these properties, use set/unset methods from a watcher to add or remove elements by a path.
To watch invoking of mutating methods, like add or delete, the watcher wraps the original methods of the passed object.
The module provides a function to watch changes. It takes an object to watch, optionally some watching options, -and a callback function that accumulates mutations and invokes on the next tick after the first mutation. -After this, the function returns API to watch changes. The API has an interface below.
-export interface Watcher<T extends object = object> {
/**
* A proxy object to watch
*/
proxy: T;
/**
* Sets a new watchable value for the proxy object by the specified path
*
* @param path
* @param value
*/
set(path: WatchPath, value: unknown): void;
/**
* Deletes a watchable value from the proxy object by the specified path
* @param path
*/
delete(path: WatchPath): void;
/**
* Cancels watching for the proxy object
*/
unwatch(): void;
}
-
-The function to watch supports: objects, arrays, Map-s, Set-s.
-import watch from 'core/object/watch';
const user = new Map([
['name', 'Kobezzza'],
['age', 31]
]);
const {proxy} = watch(user, (mutations) => {
mutations.forEach(([value, oldValue, info]) => {
console.log(value, oldValue, info.path);
});
});
// This mutation will invoke our callback
proxy.set('name', 'Andrey');
-
-Notice, the function creates a new object that wraps the original and adds the watching functionality. -The new object is connected to the original, and if you change the value of some property of the proxy object, -it will affect the original object. The connection works with the reverted direction too, when you change the original object, -but in this case, you can't watch these mutations.
-import watch from 'core/object/watch';
const user = {
name: 'Kobezzza',
age: 31
};
const {proxy} = watch(user, (mutations) => {
mutations.forEach(([value, oldValue, info]) => {
console.log(value, oldValue, info.path);
});
});
// This mutation will invoke our callback
proxy.name = 'Andrey';
// This mutation won't invoke our callback
user.age++;
-
-Also, the API provides a function to remove watching from the proxy object.
-import watch from 'core/object/watch';
const user = {
name: 'Kobezzza',
age: 31
};
const {proxy, unwatch} = watch(user, (mutations) => {
mutations.forEach(([value, oldValue, info]) => {
console.log(value, oldValue, info.path);
});
});
// This mutation will invoke our callback
proxy.name = 'Andrey';
unwatch();
// This mutation won't invoke our callback
proxy.age++;
-
-The rest two methods of the API allow adding or removing properties to the proxy object.
-If your environment supports Proxy objects, you can add new properties without invoking set,
-but the invoking is necessary for a strategy based on accessors.
import watch from 'core/object/watch';
import * as proxyEngine from 'core/object/watch/engines/proxy';
import * as accEngine from 'core/object/watch/engines/accessors';
const user = {
name: 'Kobezzza',
age: 31
};
const proxyWatcher = watch(user, {engine: proxyEngine}, (mutations) => {
mutations.forEach(([value, oldValue, info]) => {
console.log(value, oldValue, info.path);
});
});
// This mutation will invoke our callback
proxyWatcher.proxy.skills = ['programming', 'JS'];
const accWatcher = watch(user, {engine: accEngine}, (mutations) => {
mutations.forEach(([value, oldValue, info]) => {
console.log(value, oldValue, info.path);
});
});
// If we add a new property, we have to register a new accessor to watch.
// This mutation will invoke our callback.
accWatcher.set('skills', ['programming', 'JS']);
// Now we can change it without any doubt
accWatcher.skills = ['programming', 'JS', 'music'];
-
-To delete a property from the proxy object, we can set it to undefined, or use the delete operator,
-or invoke the delete method of the watcher. All of these methods have different semantic and work the same with any engine.
-Let's watch these in action.
import watch from 'core/object/watch';
const user = {
name: 'Kobezzza',
age: 31
};
const watcher = watch(user, (mutations) => {
mutations.forEach(([value, oldValue, info]) => {
console.log(value, oldValue, info.path);
});
});
/* ***************** */
/* The first variant */
/* ***************** */
// This mutation will invoke our callback
watcher.proxy.age = undefined;
// true
console.log('age' in watcher.proxy);
// This mutation will invoke our callback
watcher.proxy.age = 32;
/* ****************** */
/* The second variant */
/* ****************** */
// This mutation won't invoke our callback
delete watcher.proxy.age;
// false
console.log('age' in watcher.proxy);
// This mutation won't invoke our callback
watcher.proxy.age = 32;
// Invoke set to register a property to watch.
// This mutation will invoke our callback.
watcher.set('age', 31)
// This mutation will invoke our callback
watcher.proxy.age = 32;
/* ***************** */
/* The third variant */
/* ***************** */
// This mutation will invoke our callback
watcher.delete('age');
// false
console.log('age' in watcher.proxy);
// This mutation won't invoke our callback
watcher.proxy.age = 32;
// Invoke set to register a property to watch.
// This mutation will invoke our callback.
watcher.set('age', 31)
// This mutation will invoke our callback
watcher.proxy.age = 32;
-
-
-
- A function that handles mutations can take a list of mutations or a single mutation. -The list of mutations contains sub-arrays, where the first two parameters refer to new and old values of the mutated property. -The third parameter refers to an object that contains some information about a particular mutation, like, where the mutation has occurred. -In case when the function takes a single mutation, the function takes tree arguments instead of one.
-interface WatchHandlerParams {
/**
* Link to an object that is watched
*/
obj: object;
/**
* Link to the root object of watching
*/
root: object;
/**
* Link to the top property of watching
* (the first level property of the root)
*/
top?: object;
/**
* Information about a parent mutation event
*/
parent?: WatchHandlerParentParams;
/**
* True if a mutation has occurred on a prototype of the watched object
*/
fromProto: boolean;
/**
* Path to a property that was changed
*/
path: unknown[];
/**
* The original path to a property that was changed
*/
originalPath: unknown[];
}
interface WatchHandlerParentParams {
value: unknown;
oldValue: unknown;
info: WatchHandlerParams;
}
-
-
-
- We can set watching not to the whole object properties, but only the property by the specified path. -To do it, just provide a path as the second parameter of the watching function.
-import watch from 'core/object/watch';
const user = {
name: 'Kobezzza',
skills: {
programming: {
js: 80,
rust: 30
},
singing: 10
}
};
const {proxy} = watch(user, 'skills.programming', (value, oldValue, info) => {
console.log(value, oldValue, info.path, info.originalPath);
});
// This mutation won't invoke our callback
proxy.name = 'Andrey';
// This mutation will invoke our callback
// {js: 81, rust: 30} {js: 81, rust: 30} ['skills', 'programming'] ['skills', 'programming', 'js']
proxy.skills.programming.js++;
// Also, we can provide a path in the array form, like, ['skills', 'programming'].
// It helps provide a path with non-string keys.
const key = {};
const data = {
map: new Map([[key, 1]])
};
const {proxy: proxy2} = watch(data, ['map', key], (value, oldValue, info) => {
console.log(value, oldValue, info.originalPath);
});
proxy2.map.set(key, proxy2.map.get(key) + 1);
-
-There are some nuances of using this approach:
-Because we watch the specific path, the callback function will take not a list of mutations, but just a single mutation.
-import watch from 'core/object/watch';
const user = {
name: 'Kobezzza',
skills: {
programming: {
js: 80,
rust: 30
},
singing: 10
}
};
const {proxy} = watch(user, (mutations) => {
mutations.forEach(([value, oldValue, info]) => {
console.log(value, oldValue, info.path);
})
});
const {proxy: proxyByPath} = watch(user, 'skills.programming', (value, oldValue, info) => {
console.log(value, oldValue, info.path);
});
-
-Mutations of nested properties that match the path also invoke the callback.
-To get a path of the mutated property, use info.originalPath, because info.path always refers to the path that we watched.
import watch from 'core/object/watch';
const user = {
name: 'Kobezzza',
skills: {
programming: {
js: 80,
rust: 30
},
singing: 10
}
};
const {proxy: proxyByPath} = watch(user, 'skills.programming', (value, oldValue, info) => {
console.log(value, oldValue, info.originalPath);
});
// This mutation will invoke our callback
// info.path: ['skills', 'programming']
// info.originalPath: ['skills', 'programming', 'js']
proxyByPath.skills.programming.js++;
// This mutation will invoke our callback
// info.path: ['skills', 'programming']
// info.originalPath: ['skills', 'programming']
proxyByPath.skills.programming = {js: 80, rust: 30, python: 30};
// This mutation will invoke our callback
// info.path: ['skills', 'programming']
// info.originalPath: ['skills']
proxyByPath.skills = {programming: {js: 80, rust: 30, python: 30, haskell: 20}};
-
-By default, all mutations that occur on the same tick are accumulated within a mutation list.
-The provided handler function is invoked on the next tick and takes the last value from this list as an argument, i.e., it works lazily.
-To force a watcher to invoke its handler immediately after the occurred mutation, provide the immediate option.
-To watch the whole list of mutations, provide the collapse option to false.
import watch from 'core/object/watch';
const user = {
name: 'Kobezzza',
skills: {
programming: {
js: 80,
rust: 30
},
singing: 10
}
};
const {proxy: collapsedProxy} = watch(user, 'skills.programming', (value, oldValue, info) => {
console.log(value, oldValue, info.originalPath);
});
collapsedProxy.skills.programming.js++;
// This mutation overwrites the previous
// {js: 80, rust: 30, python: 30} {js: 81, rust: 30} ['skills', 'programming']
collapsedProxy.skills.programming = {js: 80, rust: 30, python: 30};
const {proxy} = watch(user, (mutations) => {
mutations.forEach(([value, oldValue, info]) => {
console.log(value, oldValue, info.originalPath);
})
});
// 81, 80, ['skills', 'programming', 'js']
proxy.skills.programming.js++;
// {js: 80, rust: 30} {js: 81, rust: 30, python: 30} ['skills']
proxy.skills = {programming: {js: 80, rust: 30}};
-
-The provided handler function takes new and old values of a property by the provided path.
-Notice, if a mutation of some nested property occurs, the new and old values will be equal because they refer to the same object.
-To get values of changed nested properties, provide the collapse option to false.
import watch from 'core/object/watch';
const user = {
name: 'Kobezzza',
skills: {
programming: {
js: 80,
rust: 30
},
singing: 10
}
};
const {proxy: collapsedProxy} = watch(user, 'skills.programming', (value, oldValue, info) => {
console.log(value, oldValue, info.originalPath);
});
// {js: 81, python: 30} {js: 81, rust: 30} ['skills', 'programming', 'js']
collapsedProxy.skills.programming.js++;
const {proxy} = watch(user, (mutations) => {
mutations.forEach(([value, oldValue, info]) => {
console.log(value, oldValue, info.originalPath);
})
});
// 82, 81, ['skills', 'programming', 'js']
proxy.skills.programming.js++;
-
-The important point is that the watch function doesn't mutate the passed object but creates a new object based on the original and returns it. -Only mutation of this new object will create events of modifications, and when we make another one watcher based on the original object, -they can't watch mutations of each other.
-import watch from 'core/object/watch';
const user = {
name: 'Kobezzza',
age: 31
};
const {proxy: proxy1} = watch(user, (mutations) => {
mutations.forEach(([value, oldValue, info]) => {
console.log(value, oldValue, info.path);
});
});
const {proxy: proxy2} = watch(user, (mutations) => {
mutations.forEach(([value, oldValue, info]) => {
console.log(value, oldValue, info.path);
});
});
// proxy2 won't handle this mutation
proxy1.name = 'Andrey';
// proxy1 won't handle this mutation
proxy2.age++;
-
-If we want to share mutations between different watchers, we should invoke the watch function by providing the previous proxy object instead of the original.
-import watch from 'core/object/watch';
const user = {
name: 'Kobezzza',
age: 31
};
const {proxy: proxy1} = watch(user, (mutations) => {
mutations.forEach(([value, oldValue, info]) => {
console.log(value, oldValue, info.path);
});
});
const {proxy: proxy2} = watch(proxy1, (mutations) => {
mutations.forEach(([value, oldValue, info]) => {
console.log(value, oldValue, info.path);
});
});
// proxy2 will handle this mutation
proxy1.name = 'Andrey';
// proxy1 will handle this mutation
proxy2.age++;
-
-
-
- By default, are watched only mutations from the top object properties, i.e., all nested mutations, are ignored.
-To enable watching of nested properties, provide the deep option.
import watch from 'core/object/watch';
const user = {
name: 'Kobezzza',
skills: {
programming: 80,
singing: 10
}
};
const {proxy} = watch(user, {deep: true}, (mutations) => {
mutations.forEach(([value, oldValue, info]) => {
console.log(value, oldValue, info.path);
});
});
// This mutation will invoke our callback
// 11 10 ['skills', 'singing']
proxy.skills.singing++;
-
-
-
- By default, all mutations of properties from a prototype of the proxy object are ignored.
-To enable watching of prototype properties, provide the withProto option.
import watch from 'core/object/watch';
const user = {
name: 'Kobezzza',
__proto__: {
age: 31
}
};
const {proxy} = watch(user, {withProto: true}, (mutations) => {
mutations.forEach(([value, oldValue, info]) => {
console.log(value, oldValue, info.path, info.fromProto);
});
});
// This mutation will invoke our callback
// 32 31 ['age'] true
proxy.age++;
-
-
-
- By default, all mutations that occur on the same tick are accumulated within a mutation list.
-The provided handler function is invoked on the next tick and takes the list of mutations as an argument, i.e., it works lazily.
-To force a watcher to invoke its handler immediately after the occurred mutation, provide the immediate option.
-In this case, the callback function doesn't take a list of mutations but parameters of the single mutation.
import watch from 'core/object/watch';
const user = {
name: 'Kobezzza',
age: 31
};
const {proxy} = watch(user, {immediate: true}, (value, oldValue, info) => {
console.log(value, oldValue, info.path);
});
// This mutation will invoke our callback
// 32 31 ['age']
proxy.age++;
-
-
-
- The option enables or disables collapsing of mutation events.
-When it toggles to true, all mutation events fire as if they occur on top properties of the watchable object.
import watch from 'core/object/watch';
const user = {
name: 'Kobezzza',
skills: {
programming: 80,
singing: 10
}
};
const {proxy} = watch(user, {collapse: true, deep: true}, (mutations) => {
mutations.forEach(([value, oldValue, info]) => {
console.log(value, oldValue, info.path, info.obj === info.top);
});
});
// {programming: 81, singing: 10} {programming: 81, singing: 10} ['skills', 'programming'] true
proxy.skills.programming++;
-
-When it toggles to false, and the watcher binds to the specified path, the callback takes a list of mutations.
-Otherwise, the callback takes only the last mutation.
import watch from 'core/object/watch';
const user = {
name: 'Kobezzza',
skills: {
programming: {
js: 80,
rust: 30
},
singing: 10
}
};
const {proxy} = watch(user, 'skills.programming', {collapse: false}, (mutations) => {
mutations.forEach(([value, oldValue, info]) => {
console.log(value, oldValue, info.top, info.path, info.originalPath);
});
});
// 81 80 {programming: {js: 81, rust: 30}, singing: 10} ['skills', 'programming'] ['skills', 'programming', 'js']
proxy.skills.programming.js++;
const {proxy: collapsedProxy} = watch({a: {b: {c: 1}}}, 'skills.programming', (value, oldValue, info) => {
console.log(value, oldValue);
});
// {programming: {js: 82, rust: 30}, singing: 10} {programming: {js: 82, rust: 30}, singing: 10}
collapsedProxy.skills.programming.js++;
-
-
-
- A function that takes a path of the mutation event and returns a new path. -The function is used when you want to mask one mutation to another one.
-import watch from 'core/object/watch';
function pathModifier(path) {
return path.map((chunk) => chunk.replace(/^_/, ''));
}
const {proxy} = watch({a: 1, b: 2, _a: 1}, 'a', {pathModifier}, (mutations) => {
mutations.forEach(([value, oldValue, info]) => {
console.log(value, oldValue, info.path, info.originalPath);
});
});
// 2 1 ['a'], ['_a']
proxy._a = 2;
-
-
-
- A filter function for mutation events. -The function allows skipping some mutation events.
-import watch from 'core/object/watch';
function eventFilter(value, oldValue, info) {
return info.path[0] !== '_a';
}
const {proxy} = watch({a: 1, b: 2, _a: 1}, {eventFilter}, (mutations) => {
mutations.forEach(([value, oldValue, info]) => {
console.log(value, oldValue, info.path, info.originalPath);
});
});
// This mutation won't invoke our callback
proxy._a = 2;
-
-
-
- A link to an object that should connect with the watched object, i.e., changing of properties of the tied object, will also emit mutation events.
-import watch from 'core/object/watch';
const data = {
foo: 2
};
class Bla {
data = data;
constructor() {
watch(this.data, {tiedWith: this}, (val) => {
console.log(val);
});
}
}
const bla = new Bla();
bla.foo = 3;
-
-
-
- A list of prefixes for paths to watch. This parameter can help to watch accessors.
-import watch from 'core/object/watch';
const obj = {
get foo() {
return this._foo * 2;
},
_foo: 2
};
const {proxy} = watch(obj, 'foo', {prefixes: ['_']}, (value, oldValue, info) => {
console.log(value, oldValue, info.path, info.originalPath, info.parent);
});
// This mutation will invoke our callback
proxy._foo++;
-
-
-
- A list of postfixes for paths to watch. This parameter can help to watch accessors.
-import watch from 'core/object/watch';
const obj = {
get foo() {
return this.fooStore * 2;
},
fooStore: 2
};
const {proxy} = watch(obj, 'foo', {postfixes: ['Store']}, (value, oldValue, info) => {
console.log(value, oldValue, info.path, info.originalPath, info.parent);
});
// This mutation will invoke our callback
proxy.fooStore++;
-
-
-
- When providing the specific path to watch, this parameter can contain a list of dependencies for the watching path. -This parameter can help to watch accessors.
-const obj = {
get foo() {
return this.bla * this.baz;
},
bla: 2,
baz: 3
};
const {proxy} = watch(obj, 'foo', {dependencies: ['bla', 'baz']}, (value, oldValue, info) => {
console.log(value, oldValue, info.path, info.originalPath, info.parent);
});
// This mutation will invoke our callback
proxy.bla++;
-
-When providing the specific path to watch, this parameter can contain an object or Map with lists of
-dependencies to watch.
const obj = {
foo: {
get value() {
return this.bla * this.baz;
}
},
bla: 2,
baz: 3
};
const depsAsObj = {
'foo.value': ['bla', 'baz']
};
const {proxy: proxy1} = watch(obj, {dependencies: depsAsObj}, (mutations) => {
mutations.forEach(([value, oldValue, info]) => {
console.log(value, oldValue, info.path, info.originalPath, info.parent);
});
});
// This mutation will fire an additional event for `foo.value`
proxy1.bla++;
const depsAsMap = new Map([
[
// A path to the property with dependencies
['foo', 'value'],
// Dependencies
['bla', 'baz']
]
]);
const {proxy: proxy2} = watch(obj, {dependencies: depsAsMap}, (mutations) => {
mutations.forEach(([value, oldValue, info]) => {
console.log(value, oldValue, info.path, info.originalPath, info.parent);
});
});
proxy2.baz++;
-
-
-
- A watch engine to use. -By default, will be used proxy if supported, otherwise accessors.
-import watch from 'core/object/watch';
import * as proxyEngine from 'core/object/watch/engines/proxy';
import * as accEngine from 'core/object/watch/engines/accessors';
const user = {
name: 'Kobezzza',
age: 31
};
const proxyWatcher = watch(user, {engine: proxyEngine}, (mutations) => {
mutations.forEach(([value, oldValue, info]) => {
console.log(value, oldValue, info.path);
});
});
const accWatcher = watch(user, {engine: accEngine}, (mutations) => {
mutations.forEach(([value, oldValue, info]) => {
console.log(value, oldValue, info.path);
});
});
-
-
-
- The module provides a bunch of additional helper functions.
- - -The function temporarily mutes all mutation events for the specified proxy object.
-import watch, { mute } from 'core/object/watch';
const user = {
name: 'Kobezzza',
skills: {
programming: 80,
singing: 10
}
};
const {proxy} = watch(user, {immediate: true, deep: true}, (value, oldValue, info) => {
console.log(value, oldValue, info.path);
});
// 81 80 ['skills', 'programming']
proxy.skills.programming++;
mute(proxy);
// This mutation won't invoke our callback
proxy.skills.programming++;
-
-
-
- Wraps the specified object with unwatchable proxy, i.e. any mutations of this proxy can’t be watched.
-const obj = {
a: 1,
b: unwatchable({c: 2})
};
const {proxy} = watch(obj, {immediate: true}, (value, oldValue) => {
console.log(value, oldValue);
});
// This mutation will be ignored by the watcher
proxy.b.c = 3;
// 1 2
proxy.a = 2;
-
-
-
- The function unmutes all mutation events for the specified proxy object.
-import watch, { mute, unmute } from 'core/object/watch';
const user = {
name: 'Kobezzza',
skills: {
programming: 80,
singing: 10
}
};
const {proxy} = watch(user, {immediate: true, deep: true}, (value, oldValue, info) => {
console.log(value, oldValue, info.path);
});
// 81 80 ['skills', 'programming']
proxy.skills.programming++;
mute(proxy);
// This mutation won't invoke our callback
proxy.skills.programming++;
unmute(proxy);
// 83 82 ['skills', 'programming']
proxy.skills.programming++;
-
-
-
- The function sets a new watchable value for a proxy object by the specified path. -It is actual when using an engine based on accessors to add new properties to the watchable object. -Or when you want to restore watching for a property after deleting it.
-import watch, { set } from 'core/object/watch';
const user = {
name: 'Kobezzza',
skills: {
programming: 80,
singing: 10
}
};
const {proxy} = watch(user, {immediate: true, deep: true}, (value, oldValue, info) => {
console.log(value, oldValue, info.path);
});
// This mutation will invoke our callback
set(proxy, 'bla.foo', 1);
-
-
-
- The function deletes a watchable value from a proxy object by the specified path.
-To restore watching for this property, use set.
import watch, { set, unset } from 'core/object/watch';
const user = {
name: 'Kobezzza',
skills: {
programming: 80,
singing: 10
}
};
const {proxy} = watch(user, {immediate: true, deep: true}, (value, oldValue, info) => {
console.log(value, oldValue, info.path);
});
// This mutation will invoke our callback
unset(proxy, 'skills.programming');
console.log('programming' in proxy.skills === false);
// This mutation won't invoke our callback
proxy.skills.programming = 80;
// Invoke set to register a property to watch.
// This mutation will invoke our callback.
set(proxy, 'skills.programming', 80)
// This mutation will invoke our callback
proxy.skills.programming++;
-
-Watches for changes of the specified object
-Watches for changes of the specified object
-additional options
-Watches for changes of the specified object
-additional options
-Watches for changes of the specified object
-path to a property to watch
-Watches for changes of the specified object
-path to a property to watch
-additional options
-Watches for changes of the specified object
-path to a property to watch
-additional options
-The function temporarily mutes all mutation events for the specified proxy object
-Sets a new watchable value for a proxy object by the specified path. -The function is actual when using an engine based on accessors to add new properties to the watchable object. -Or when you want to restore watching for a property after deleting it.
-Sets a new watchable value for a proxy object by the specified path. -The function is actual when using an engine based on accessors to add new properties to the watchable object. -Or when you want to restore watching for a property after deleting it.
-The function unmutes all mutation events for the specified proxy object
-Deletes a watchable value from a proxy object by the specified path
-Deletes a watchable value from a proxy object by the specified path.
-To restore watching for this property, use set.
Wraps the specified object with unwatchable proxy, i.e. any mutations of this proxy can’t be watched
-Sets a new watchable value for an object by the specified path
-set of registered handlers
-Sets a pair of accessors to watch the specified property and returns a proxy object
-object to watch
-property key to watch
-path to the object to watch from the root object
-set of registered handlers
-link to the root object of watching
-Unsets a watchable value for an object by the specified path
-set of registered handlers
-Watches for changes of the specified object by using accessors
-base path to object properties: it is provided to a watch handler with parameters
-callback that is invoked on every mutation hook
-set of registered handlers
-Watches for changes of the specified object by using accessors
-base path to object properties: it is provided to a watch handler with parameters
-callback that is invoked on every mutation hook
-set of registered handlers
-additional options
-link to the root object of watching
-link to the top object of watching
-Returns a value from an object by the specified label and handlers
-Returns a value from an object by the specified label and handlers
-default value (can be declared as a function that will be invoked)
-Returns a type of data to watch or false
-Returns a value to the proxy from the specified raw value
-property key for a value
-base path to object properties: it is provided to a watch handler with parameters
-set of registered handlers
-link to the root object of watching
-Returns true if the specified value is a watch proxy
-Unwraps the specified value to watch and returns the raw object
-Sets a new watchable value for an object by the specified path
-set of registered handlers
-Deletes a watchable value for an object by the specified path
-set of registered handlers
-Watches for changes of the specified object by using Proxy objects
-base path to object properties: it is provided to a watch handler with parameters
-callback that is invoked on every mutation hook
-set of registered handlers
-Watches for changes of the specified object by using Proxy objects
-base path to object properties: it is provided to a watch handler with parameters
-callback that is invoked on every mutation hook
-set of registered handlers
-additional options
-link to the root object of watching
-link to the top object of watching
-Wraps mutation methods of the specified object that they be able to emit events about mutations
-additional options
-set of callbacks that are invoked on every mutation hooks
-Wraps mutation methods of the specified object that they be able to emit events about mutations
-set of callbacks that are invoked on every mutation hooks
-This module provides API to send performance metrics.
- - -import perf from 'core/perf';
const timer = perf.getTimer('network').namespace('auth');
// Duration of the `loginUser` request
const
timerId = timer.start('login'),
user = await loginUser(credential);
timer.finish(timerId, {email: user.email});
// A reference point in time for the following measurements
const scopedTimer = perf.getScopedTimer('component').namespace('index-page');
// A component was created
scopedTimer.markTimestamp('created');
// A component was mounted
scopedTimer.markTimestamp('mounted');
-
-
-
- There are two ways to use this module: with a custom configuration or default one.
- - -The default module export refers to a performance metrics factory configured using the runtime config from src/config.
-To configure it, define a perf property within your config file.
config
-import { extend } from '@v4fire/core/config';
extend({
perf: {
timer: {
engine: 'console',
filters: {
network: ['login'],
localDB: {
include: ['load', 'unload']
},
components: {
exclude: ['mount']
}
}
}
}
})
-
-some-file.ts
-import perf from 'core/perf';
const
timer = perf.getTimer('network').namespace('auth'),
timerId = timer.start('login');
// ..
timer.finish(timerId);
-
-
-
- /**
* General config for performance metrics
*/
export interface PerfConfig {
/**
* Performance timers config
*/
timer: PerfTimerConfig;
}
/**
* Performance timers config
*/
export interface PerfTimerConfig {
/**
* Name of the used engine
*/
engine: PerfTimerEngineName;
/**
* Settings to filter perf events by groups
*/
filters?: PerfGroupFilters;
}
/**
* Settings to filter perf events by groups
*/
export type PerfGroupFilters = {
[K in PerfGroup]?: PerfIncludeFilter | string[] | boolean;
};
/**
* Include/exclude patterns for perf filters
*/
export interface PerfIncludeFilter {
/**
* Include only specific events
*/
include?: string[];
/**
* Exclude only specific events.
* If `include` and `exclude` are both presented, will be used only include.
*/
exclude?: string[];
}
-
-
-
- There is a possibility to create a performance metrics factory with a custom configuration. It allows having several -differently configured performance metrics factories at the same time.
-This is achieved using the perf method, which acquires a new config as the first argument.
import { perf as factory } from 'core/perf';
const perf = factory({
timer: {
engine: 'console',
filters: {
network: {
include: ['login']
}
}
}
});
const
timer = perf.getTimer('network').namespace('auth'),
timerId = timer.start('login');
// ..
timer.finish(timerId);
-
-
-
- Currently, the module supports only the time metrics core/perf/timer.
-Returns a configured instance of the Perf class
This module provides a bunch of helpers to configure the core/perf module.
/**
* General config for performance metrics
*/
export interface PerfConfig {
/**
* Performance timers config
*/
timer: PerfTimerConfig;
}
/**
* Performance timers config
*/
export interface PerfTimerConfig {
/**
* Name of the used engine
*/
engine: PerfTimerEngineName;
/**
* Settings to filter perf events by groups
*/
filters?: PerfGroupFilters;
}
/**
* Settings to filter perf events by groups
*/
export type PerfGroupFilters = {
[K in PerfGroup]?: PerfIncludeFilter | string[] | boolean;
};
/**
* Include/exclude patterns for perf filters
*/
export interface PerfIncludeFilter {
/**
* Include only specific events
*/
include?: string[];
/**
* Exclude only specific events.
* If `include` and `exclude` are both presented, will be used only include.
*/
exclude?: string[];
}
-
-Creates filter predicates for every group
-filters from the performance config
-Returns an instance of the timer engine that defined in the performance config
-performance config
-Combines the passed configs together
-base config, that has all required fields
-additional configs, that override fields of the base one
-This module provides an implementation of the performance timer API. -It allows calculating and sending time metrics.
- - -The module consists of several abstractions:
-The timers' factory is created using getTimerFactory function. The function acquires timers' config as the first
-argument. It means that there could be several timers' factories with different configurations simultaneously.
import { getTimerFactory } from 'core/perf/timer';
const someFactory = getTimerFactory(generalConfig);
const anotherFactory = getTimerFactory(specificConfig);
-
-
-
- Each factory has the following methods: getTimer, getScopedTimer. These methods are entry points to work with timers.
-Each of them uses runners inside to create a timer and return it. Also, the methods create a runner for passed arguments
-only once and then use the same runner for the next call with the same arguments.
These methods are called from the main perf object, so there is no need to create the timers' factory directly.
-The following examples imply that a factory has already created and use it only for educational purpose.
const timer = factory.getTimer('manual');
-
-This method returns a regular timer that starts time measurement from -the time origin.
-Duration measurement
-const timer = perf.getTimer('network').namespace('auth');
// Duration of the `loginUser` request
const loginTimerId = timer.start('login');
const user = await loginUser(credential);
timer.finish(loginTimerId);
// Duration of the `logoutUser` request
const logoutTimerId = timer.start('logout');
await logoutUser(user);
// It's possible to send additional data when finishing measurement
timer.finish(logoutTimerId, {email: user.email});
-
-Time marks from the time origin
-const timer = perf.getTimer('components').namespace('index-page');
// A page was created
scopedTimer.markTimestamp('created');
// A page was mounted
// It's possible to send additional data with timestamp
scopedTimer.markTimestamp('mounted', {id: data.id});
-
-Using the same factory in different files and calling getTimer method with the same arguments guarantees that inside
-it will be used the same instance of the timers' runner. But the method returns different instances of the performance
-timer itself.
file1.ts
-const timer = factory.getTimer('components');
-
-file2.ts
-// A different timer from the same runner
const timer = factory.getTimer('components');
-
-
-
- const timer = factory.getScopedTimer('network', 'old-api');
-
-This method returns a scoped timer that starts time measurement from the moment its runner was created.
-Timers from getTimer and getScopedTimer have the same interfaces.
Since the next call of the method with the same arguments uses the already created runner, then the time origin -for the new timer will be the same as for the previously created one.
-file1.ts
-// A time origin for the internal runner is exact this moment — m0
const timer = factory.getScopedTimer('tools', 'page-helpers');
-
-file2.ts
-// A different timer but its time origin is m0 as well
const timer = factory.getScopedTimer('tools', 'page-helpers');
-
-Returns a timers' factory for the passed config
-config, that the new factory will use
-This module contains the engines that send time metrics to a target destination.
- - -Each engine has to implement the PerfTimerEngine interface. It means that an engine should have the following methods:
sendDelta - to send metrics datagetTimestampFromTimeOrigin - returns a timestamp from the application start. In the simple example, it could be
-performance.now(), but the engine can define the precision and the moment the application starts.This module contains a runner implementation for performance timers.
- - -The runner is the actual thing that measures the difference between time moments. -It can create performance timers that are just proxies that execute measurement methods of the runner they created. -The main responsibility of timers is to store the whole namespace of current metrics to make them easy to use.
- - -The PerfTimersRunner class has several parameters in its constructor:
engine - the most important argument is PerfTimerEngine instance. It is required.filter - predicate to filter metrics. If it returns false, the metrics won't be sent anywhere.keepTImeOffset - the runner becomes a scoped one. All new timestamps measure from the moment the runner was created.A simple runner:
-import { PerfTimersRunner } from 'core/perf/timer/impl'
import engines from 'core/perf/timer/engines';
const runner = new PerfTimersRunner(engines.console);
-
-A scoped runner:
-import { PerfTimersRunner } from 'core/perf/timer/impl'
import engines from 'core/perf/timer/engines';
const scopedRunner = new PerfTimersRunner(engines.console, {withCurrentTimeOrigin: true});
-
-A runner with filtering:
-import { PerfTimersRunner } from 'core/perf/timer/impl'
import engines from 'core/perf/timer/engines';
const filterPredicate = (ns: string) => ns.startsWith('network');
// Only metrics which namespace starts with 'network' will be printed in the console
const runner = new PerfTimersRunner(engines.console, {filter: filterPredicate});
-
-
-
- The class has only one public method createTimer that returns an instance of performance timer.
import { PerfTimersRunner } from 'core/perf/timer/impl'
import engines from 'core/perf/timer/engines';
const runner = new PerfTimersRunner(engines.console);
const timer = runner.createTimer('network');
-
-Some protected methods are used by performance timer instances.
- - -A performance timer is used to make time measurements.
-After its creation, the timer has only a group name. The timer stores the whole namespace inside. -When new metrics are created, the timer's namespace prepends to metrics name, forming the full name of the metrics.
-import { PerfTimersRunner } from 'core/perf/timer/impl'
import engines from 'core/perf/timer/engines';
const runner = new PerfTimersRunner(engines.console);
// Timer's namespace at this point is "network"
const timer = runner.createTimer('network');
// Here time metrics are created, and its full name is "network.auth"
const timerId = timer.start('auth');
-
-
-
- The performance timer has several methods to measure and one method to define a namespace.
- - -Returns a new performance timer instance with the updated namespace.
-import { PerfTimersRunner } from 'core/perf/timer/impl'
import engines from 'core/perf/timer/engines';
const
runner = new PerfTimersRunner(engines.console),
timer = runner.createTimer('network');
// The timer namespace is "network.auth"
const timerNs = timer.namespace('auth');
// The full metrics name is "network.auth.login"
const timerId = timerNs.start('login');
-
-
-
- Two methods start and finish are designed for local measurements.
-Method start marks the beginning of measurement and returns a timer identifier to finish the measurement.
The advantage of this approach is that there could be a number of concurrent measurements with the same name, -and none of them will affect each other since every timer identifier is unique.
-import { PerfTimersRunner } from 'core/perf/timer/impl'
import engines from 'core/perf/timer/engines';
const
runner = new PerfTimersRunner(engines.console),
timer = runner.createTimer('network').namespace('auth');
const timerId = timer.start('login');
await login(credentials);
timer.finish(timerId);
-
-The finish method also acquires some additional information for the metrics as a second parameter.
-This kind of measurement is not affected by the runner's time origin because it measures the time difference between two moments.
Also, there is a possibility to measure time from the runner's time origin with markTimestamp method.
import { PerfTimersRunner } from 'core/perf/timer/impl'
import engines from 'core/perf/timer/engines';
const
runner = new PerfTimersRunner(engines.console),
timer = runner.createTimer('components').namespace('button');
// Some code
timer.markTimestamp('created');
// Another code
timer.markTimestamp('mounted');
-
-This method measures time from the runner's time origin to the moment the method was called. -It is possible to pass additional data as the second argument to the method.
-This module provides a class to create an object pool structure. The pool supports a classical API when you take and -release some resources from the pool, and the API with support of sharing resources between different consumers. -In addition, the pool supports segmentation of resources via a provided hash function.
- - -import Pool from 'core/pool';
const
pool = new Pool(createDBConnection, {size: 5});
// Number of resources in the pool (5)
console.log(pool.size);
// Number of available resources in the pool (5)
console.log(pool.available);
// If the pool is empty, `value` will be nullish
const {value, free, destroy} = pool.take();
// 5
console.log(pool.size);
// 4
console.log(pool.available);
// Releasing a resource and returning it to the pool
free();
// 5
console.log(pool.available);
// Creating a new resource if the pool is empty
const anotherResource = pool.takeOrCreate();
// Destroying a resource instead of returning it to the pool
// (if you provide a resource destructor when creating a pull instance, it will be used there)
anotherResource.destroy();
// Returning a promise that resolves with a resource from the pool
pool.takeOrWait().then(({value, free, destroy}) => {});
-
-
-
- Using API of borrowing you can share resources between different consumers without taking their from the pool.
-If you borrow a resource, you can't take it till all borrow consumers release it.
import Pool from 'core/pool';
const
pool = new Pool(createDOMObserver, {size: 1});
// Number of resources in the pool (5)
console.log(pool.size);
// Number of available resources in the pool (5)
console.log(pool.available);
// If the pool is empty, `value` will be nullish
const resource1 = pool.borrow();
console.log(resource1.value);
// 5
console.log(pool.size);
// 5
console.log(pool.available);
// You can't take a resource if it already borrowed
console.log(pool.take().value === null);
// But, you can borrow it
const resource2 = pool.borrow();
console.log(resource2.value);
// Releasing resources and returning their to the pool
resource1.free();
resource2.free();
// Now you can take it
console.log(pool.take().value);
// Creating a new resource if the pool is empty
const anotherResource = pool.borrowOrCreate();
// Destroying a resource instead of releasing it
// (if you provide a resource destructor when creating a pull instance, it will be used there)
anotherResource.destroy();
// Returning a promise that resolves with a borrowed resource from the pool
pool.borrowOrWait().then(({value, free, destroy}) => {});
-
-
-
- There is a possibility to provide arguments into a resource constructor. -Just pass them as the second argument into the pool constructor.
-import Pool from 'core/pool';
// The pull contains two arrays: [1, 2, 3], [1, 2, 3]
const pool = new Pool((...values) => [...values], [1, 2, 3], {
size: 2
});
-
-Also, you can pass arguments as a function. -This function will be invoked with a resource index and should return arguments to pass.
-import Pool from 'core/pool';
// The pull contains two arrays: [0], [1]
const pool = new Pool((...values) => [...values], (i) => [i], {
size: 2
});
-
-In addition, you can provide arguments to create a resource to takeOrCreate and borrowOrCreate methods.
import Pool from 'core/pool';
const
pool = new Pool((...values) => [...values]);
// [1]
console.log(pool.takeOrCreate(1).value);
// [1, 2, 3]
console.log(pool.borrowOrCreate(1, 2, 3).value);
-
-
-
- You can add a function to calculate a hash of the created resource. -Using this hash, you will be able to take or borrow a resource that matches to the specified hash.
-import Pool from 'core/pool';
// The pull contains five arrays: [0], [1], [2], [3], [4]
const pool = new Pool((...values) => [...values], (i) => [i], {
size: 5,
hashFn: (...args) => Object.fastHash(args)
});
// All arguments that are passed to the pool methods are using to calculate a hash
// [1]
console.log(pool.take(1).value)
// The pool doesn’t have any resources matched with the passed hash
console.log(pool.take(2, 3).value === null)
// [2]
console.log(pool.borrow(2).value);
-
-
-
- By passing a maxSize property you can define how many elements can be contained in the pool.
-Mind, if you also pass a size property larger than maxSize, there will be generated an exception.
import Pool from 'core/pool';
const pool = new Pool((...values) => [...values], {
maxSize: 2
});
// 2
console.log(pool.maxSize);
// [1]
console.log(pool.takeOrCreate(1).value);
// [2]
console.log(pool.takeOrCreate(2).value);
try {
// [3]
console.log(pool.takeOrCreate(2).value);
} catch (err) {
// The pool contains too many resources
console.log(err.message);
}
-
-
-
- You can clear a pool and destroys all created resources via invoking the clear method.
-If you provide a resource destructor when creating a pull instance, it will be with this method.
import Pool from 'core/pool';
const pool = new Pool(createDbConnection, {
size: 10,
resourceDestructor: (resource) => resource.disconnect()
});
// 10
console.log(pool.size);
// This resource will be destroyed too
pool.take();
pool.clear();
// 0
console.log(pool.size);
-
-
-
- You can pass callback functions to handle take, borrow, free, clear pool hooks.
-Besides regular arguments, these handlers take arguments that are passed to the associated methods.
import Pool from 'core/pool';
const pool = new Pool((...values) => [...values], {
size: 5,
onTake(resource, pool, ...args) {
console.log(resource, pool, ...args);
},
onBorrow(resource, pool, ...args) {
console.log(resource, pool, ...args);
},
onFree(resource, pool, ...args) {
console.log(resource, pool, ...args);
},
onClear(pool, ...args) {
console.log(pool, ...args);
}
});
pool.take(1, 2, 3);
pool.takeOrCreate(7, 2).free(10);
pool.takeOrWait({foo: 'bla'});
pool.borrow(6, 3);
pool.borrowOrCreate(7, 2).free(10);
pool.borrowOrWait({foo: 'bla'});
pool.clear();
-
-
-
- The structure constructor can take an object with optional parameters.
-export interface PoolOptions<T = unknown> {
/**
* Number of resources to create at pull initialization
* @default `0`
*/
size?: number;
/**
* The maximum number of resources that the pool can contain
* @default `Infinity`
*/
maxSize?: number;
/**
* A function to destroy one resource from the pool
*/
resourceDestructor?: ResourceDestructor<T>;
/**
* A function to calculate a hash string for the specified arguments
*/
hashFn?: HashFn;
/**
* Handler: taking some resource via `take` methods
*/
onTake?: ResourceHook<T>;
/**
* Handler: taking some resource via `borrow` methods
*/
onBorrow?: ResourceHook<T>;
/**
* Handler: releasing of some resource
*/
onFree?: ResourceHook<T>;
/**
* Handler: clearing of all pool resources
*/
onClear?: PoolHook<T>;
}
-
-
-
- The maximum number of resources that the pool can contain.
-import Pool from 'core/pool';
const pool = new Pool((...values) => [...values], {
maxSize: 2
});
// 2
console.log(pool.maxSize);
-
-
-
- Number of resources that are stored in the pool.
-import Pool from 'core/pool';
const
pool = new Pool(createDBConnection, {size: 5});
// 5
console.log(pool.size);
pool.take();
// 5
console.log(pool.size);
-
-
-
- Number of available resources that are stored in the pool.
-import Pool from 'core/pool';
const
pool = new Pool(createDBConnection, {size: 5});
// 5
console.log(pool.available);
pool.take();
// 4
console.log(pool.available);
pool.borrow();
// 4
console.log(pool.available);
-
-
-
- Returns an available resource from the pool. -The passed arguments will be used to calculate a resource hash. Also, they will be provided to hook handlers.
-The returned result is wrapped with a structure that contains methods to release or drop this resource. -If the pool is empty, the structure value field will be nullish.
-import Pool from 'core/pool';
const
pool = new Pool(() => [], {size: 5});
// []
console.log(pool.take().value);
-
-
-
- Returns an available resource from the pool. -The passed arguments will be used to calculate a resource hash. Also, they will be provided to hook handlers.
-The returned result is wrapped with a structure that contains methods to release or drop this resource. -If the pool is empty, it creates a new resource and returns it.
-import Pool from 'core/pool';
const
pool = new Pool((...values) => [...values]);
// [1, 2, 3]
console.log(pool.takeOrCreate(1, 2, 3).value);
-
-
-
- Returns a promise with an available resource from the pull. -The passed arguments will be used to calculate a resource hash. Also, they will be provided to hook handlers.
-The returned result is wrapped with a structure that contains methods to release or drop this resource. -If the pool is empty, the promise will wait till it release.
-import Pool from 'core/pool';
const
pool = new Pool((...values) => [...values]);
pool.takeOrWait().then(({value}) => {
// [1, 2, 3]
console.log(value);
});
pool.takeOrCreate(1, 2, 3).free();
-
-
-
- Borrows an available resource from the pool. -The passed arguments will be used to calculate a resource hash. Also, they will be provided to hook handlers.
-When a resource is borrowed, it won’t be dropped from the pool. I.e. you can share it with other consumers. -Mind, you can’t take this resource from the pool when it’s borrowed.
-The returned result is wrapped with a structure that contains methods to release or drop this resource. -If the pool is empty, the structure value field will be nullish.
-import Pool from 'core/pool';
const
pool = new Pool(() => [], {size: 1});
// []
console.log(pool.borrow().value);
// []
console.log(pool.borrow().value);
// []
console.log(pool.borrow().value);
-
-
-
- Borrows an available resource from the pool. -The passed arguments will be used to calculate a resource hash. Also, they will be provided to hook handlers.
-When a resource is borrowed, it won’t be dropped from the pool. I.e. you can share it with other consumers. -Mind, you can’t take this resource from the pool when it’s borrowed.
-The returned result is wrapped with a structure that contains methods to release or drop this resource. -If the pool is empty, it creates a new resource and returns it.
-import Pool from 'core/pool';
const
pool = new Pool((...values) => [...values]);
// [1, 2, 3]
console.log(pool.borrowOrCreate(1, 2, 3).value);
// [1, 2, 3]
console.log(pool.borrow().value);
-
-
-
- Returns a promise with a borrowed resource from the pull. -The passed arguments will be used to calculate a resource hash. Also, they will be provided to hook handlers.
-When a resource is borrowed, it won’t be dropped from the pool. I.e. you can share it with other consumers. -Mind, you can’t take this resource from the pool when it’s borrowed.
-The returned result is wrapped with a structure that contains methods to release or drop this resource. -If the pool is empty, the promise will wait till it release.
-import Pool from 'core/pool';
const
pool = new Pool((...values) => [...values]);
pool.takeOrWait().then(({value}) => {
// [1, 2, 3]
console.log(value);
});
pool.takeOrCreate(1, 2, 3).free();
-
-
-
- Clears the pool, i.e. drops all created resource. -The method takes arguments that will be provided to hook handlers.
-import Pool from 'core/pool';
const pool = new Pool(createDbConnection, {
size: 10,
resourceDestructor: (resource) => resource.disconnect()
});
// 10
console.log(pool.size);
pool.clear();
// 0
console.log(pool.size);
-
-Factory to create functions to modify date values
-Factory to create static functions to compare date values
-Factory to create static functions to format date values
-Factory to create static functions to modify date values
-Returns a relative value of the date for another date
-Returns settings from the application environment by the specified key
-Removes settings from the application environment by the specified key
-Added settings to the application environment by the specified key
-This module provides an API for internationalizing an application.
-Keep in mind, this module provides functions, but the language packs themselves for internationalization are specified in the lang module.
// Getting a language translation for a key
i18n('my-keyset-name')('my key');
// Resolve variables in text
i18n('my-keyset-name')('My name is {name}', {name: 'John'}); // My name is John
// Pluralize text
i18n('my-keyset-name')('I have {count} toy', {count: 10}); // I have 10 toys
// Using of several keysets, to implement inheritance or reuse shared translations
i18n(['my-keyset-name', 'dates'])('February')
// Using translations other than the app default language
i18n('my-keyset-name', 'ru')('I have {count} toy', {count: 10}); // У меня 10 игрушек
-
-
-
- To reduce syntactic noise, it is allowed to use the internationalization function as a regular string tag. -Please note that in this option we cannot forward additional parameters (for example, for pluralization).
-const t = i18n('my-keyset-name');
console.log(t`my key`);
-
-
-
- The structure of the language map consists of several levels:
-The symbolic name of the language or locale for which translations are provided.
-export default {
'ru': { /* ... */ },
'en-gb': { /* ... */ },
'en-us': { /* ... */ }
};
-
-Namespace for language keys (hereinafter "keyset"). Keyset allows you to share the same keys in different contexts. -For example, the key "Next" may have a different value in different components of the application, therefore, -we can use the name of the component as a keyset value.
-export default {
ru: {
'b-reg-form': {
Next: 'Далее'
},
'b-queue': {
Next: 'Следующий'
}
}
};
-
-Keys and translations. The key can be any symbolic sequence. The key values will be replaced with the corresponding translation. -If there is no translation for the given locale or keyset, then the key itself will be displayed.
-Some translations may include special constructions in their text, which will be replaced by other meanings during translation.
-To use such variables, it is enough to place them inside the {variableName} construct, and pass the values for
-translation as an additional parameter to the i18n function.
export default {
en: {
"my-component": {
"my name is {name}": "my name is {name}",
"apple": "apple"
}
}
};
-
-i18n('my-component')('My name is {name}', {name: 'John'});
-
-
-
- Some keys may have multiple translations depending on some numeric value. For example, "1 apple" or "5 apples".
-To specify such translations, a special macro {count} is used, and translations are specified as a tuple [one, some, many, none].
export default {
ru: {
"my-component": {
"time": "время",
"{count} product": [
"{count} продукт",
"{count} продукта",
"{count} продуктов",
"{count} продуктов"
]
}
},
en: {
"my-component": {
"{count} product": [
"{count} product",
"{count} products",
"{count} products",
"{count} products"
]
}
}
};
-
-i18n('my-component', 'ru')('{count} product', {count: 10});
-
-
-
- The event emitter to broadcast localization events.
- - -The default application language.
-interface Locale {
/**
* The locale value
*/
value: CanUndef<Language>;
/**
* True if the locale is already defined
*/
isDefined: boolean;
/**
* The locale initialization promise
*/
isInitialized: Promise<void>;
}
-
-
-
- Sets a new application language.
-import { setLocale } from 'core/prelide/i18n';
// Set Russian as default language
setLocale('ru', true);
-
-
-
- Creates a function to internationalize strings in an application based on the given locale and keyset. -Keyset allows you to share the same keys in different contexts. For example, the key "Next" may have a different value -in different components of the application, therefore, we can use the name of the component as a keyset value.
-Keep in mind that this function is global, i.e. it does not need to be explicitly imported.
-i18n('my-component')('My name is {name}', {name: 'John'});
-
-Creates a function to internationalize strings in an application based on the given locale and keyset. -Keyset allows you to share the same keys in different contexts. -For example, the key "Next" may have a different value in different components of the application, therefore, -we can use the name of the component as a keyset value.
-the name of keyset or array with names of keysets to use. - If passed as an array, the priority of the cases will be arranged in the order of the elements, - the first one will have the highest priority.
-Creates a function to internationalize strings in an application based on the given locale and keyset. -Keyset allows you to share the same keys in different contexts. -For example, the key "Next" may have a different value in different components of the application, therefore, -we can use the name of the component as a keyset value.
-Returns the correct plural form to translate based on the given count
-list of translation variants
-the value on the basis of which the form of pluralization will be selected
-Returns the form for plural sentences and resolves variables from the passed template
-a string for the default case, or an array of strings for the plural case
-a dictionary with parameters for internationalization
-Factory for functions that converts milliseconds by the specified offset
-Factory to create rounding methods
-Factory for static functions that converts milliseconds by the specified offset
-Factory to create static rounding methods
-Returns a descriptor for a getter that returns a string with attaching the specified type
-Repeats a string with the specified number of repetitions and returns a new string
-Returns a function to serialize object values into strings
-first object to serialize
-second object to serialize
-map to store functions
-Factory to create Object.select/reject functions
-Returns true if the specified value has a prototype that can be extended
-Returns a new instance of the specified value or null
-Returns a type of the specified value
-Returns true if the specified value is a container structure
-Converts the specified string to a string that logically split by a separator
-Factory to create static string transform methods
-Returns true, if the specified character is declared in upper case
-Creates a promise that can be resolved from the "outside"
-promise constructor
-additional options
-Creates a promise that can be resolved from the "outside"
-type of the resolved promise value
-Returns true if the specified promise implements the interface of ControllablePromise
Returns true if the specified object implements the interface of ControllablePromise
This module provides a class wraps promise-like objects and adds to them some extra functionality, such as possibility of cancellation, etc.
-import AbortablePromise from 'core/promise/abortable';
const promise = new AbortablePromise((resolve, reject, onAbort) => {
setTimeout(resolve, 100);
onAbort((reason) => {
console.error(`The promise was aborted by a reason of ${reason}`);
});
}).catch((err) => console.error(err)); // timeout
// Invoking of `abort` rejects the promise.
// Additionally, you can specify a reason to abort.
promise.abort('timeout');
-
-
-
- You can tie one promise with another. Tying is mean that when your abort one promise, another one will be aborted too.
-To tie a promise, provide a parent promise as the second argument of the constructor or static methods, like all or race.
import AbortablePromise from 'core/promise/abortable';
// catch: timeout
const parent = new AbortablePromise((resolve) => setTimeout(resolve, 100)).catch((err) => console.error(err));
// catch: timeout
const childPromise = new AbortablePromise((resolve) => setTimeout(resolve, 200)).catch((err) => console.error(err), parent);
parent.abort('timeout');
-
-
-
- The module re-use native Promise API with adding some extra getters, etc., you free to use such methods like then, catch, or finally.
True if the current promise is pending.
-import AbortablePromise from 'core/promise/abortable';
const promise = new AbortablePromise((resolve) => {
setTimeout(() => {
resolve();
// false
console.log(promise.isPending);
}, 100);
});
// true
console.log(promise.isPending);
-
-
-
- The module provides a bunch of static helper methods and getters.
- - -The method wraps the specified abort reason to ignore with tied promises, -i.e., this reason won't reject all child promises.
- - -The method creates a new resolved promise for the specified value. -If the resolved value is a function, it will be invoked. -The result of the invoking will be provided as a value of the promise.
-import AbortablePromise from 'core/promise/abortable';
AbortablePromise.resolveAndCall(Promise.resolve(() => 1)).then((res) => {
// 1
console.log(res);
});
-
-This module provides a class is similar to the native promise class but works synchronously.
-import SyncPromise from 'core/promise/sync';
// 1
// 2
SyncPromise.resolve().then(() => console.log(1));
console.log(2);
-
-
-
- True if the current promise is pending.
-import SyncPromise from 'core/prelude/structures/sync-promise';
const sleep = new SyncPromise((r) => setTimeout(r, 100));
console.log(sleep.isPending === true);
setTimeout(() => {
console.log(sleep.isPending === false);
}, 200);
-
-
-
- Returns the promise' value if it is fulfilled, otherwise throws an exception.
-import SyncPromise from 'core/prelude/structures/sync-promise';
const sleep = new SyncPromise((r) => setTimeout(() => r(10), 100));
try {
sleep.unwrap();
} catch (err) {
console.error(err);
}
setTimeout(() => {
console.log(sleep.unwrap() === 10);
}, 200);
-
-
-
- The module provides a bunch of helpers to memoize promises.
- - -Memorizes the specified promise and converts it to a synchronous promise. -It means that after the first resolution, the promised result will be cached, -and the method returns the synchronous version of a promise.
-import { memoize } from 'core/promise/memoize';
// Will fire:
// 2
// 1
// 3
// 4
memoize('core/url/concat', () => import('core/url/concat')).then(() => {
console.log(1);
memoize('core/url/concat', () => import('core/url/concat')).then(() => {
console.log(3);
});
console.log(4);
});
console.log(2);
-
-Memorizes the specified promise and converts it to a synchronous promise. -It means that after the first resolution, -the promised result will be cached, and the method returns the synchronous version of a promise.
-promise or a promise factory to cache, or a key to cache the promise
-promise or a promise factory to cache (if the first argument is a key)
-This module provides an abstract class for any Queue data structure. -For convenience, the underlying queue API is fairly close to the regular JS array API.
-The submodules contain different classes and interfaces that extends or implements that class. -The main module re-exports these implementations:
-AbstractQueue — an alias for core/queue/interface/Queue;AbstractWorkerQueue — an alias for core/queue/worker/interface/WorkerQueue;Queue — an alias for core/queue/simple;OrderedQueue — an alias for core/queue/order;MergeQueue — an alias for core/queue/merge.AbstractWorkerQueue — an alias for core/queue/worker.WorkerQueue — an alias for core/queue/worker/simple.MergeWorkerQueue — an alias for core/queue/worker/merge.The first element in the queue.
-import Queue from 'core/queue/simple';
const
queue = new Queue();
queue.push(1);
queue.push(5);
console.log(queue.head); // 1
-
-
-
- Creates a new queue based on the current one and returns it.
-import Queue from 'core/queue/simple';
const
queue1 = new Queue();
queue1.push(1);
queue1.push(5);
const
queue2 = queue1.clone();
console.log(queue2.head); // 1
console.log(queue1 !== queue2); // true
-
-
-
- Clears the queue.
-import Queue from 'core/queue/simple';
const
queue = new Queue();
queue.push(1);
queue.push(5);
console.log(queue.head); // 1
queue.clear();
console.log(queue.head); // undefined
console.log(queue.length); // 0
-
-
-
- For convenience, the underlying queue API is fairly close to the regular JS array API.
-That is, you have methods for adding and removing elements: push/unshift and pop/shift.
-Notice, the shift and unshift methods just aliases for pop and push.
import Queue from 'core/queue/simple';
const
queue = new Queue();
queue.push(1);
queue.unshift(5);
console.log(queue.pop()); // 1
console.log(queue.shift()); // 5
-
-You can also find out the number of elements in the queue using the length getter.
import Queue from 'core/queue/simple';
const
queue = new Queue();
queue.push(1);
queue.push(5);
console.log(queue.length); // 2
-
-Like arrays, any queue can be traversed using an iterator.
-import Queue from 'core/queue/simple';
const
queue = new Queue();
queue.push(1);
queue.push(5);
// [1, 5]
console.log([...queue]);
// [1, 5]
console.log([...queue.values()]);
-
-In addition, the API declares head to get the first element from the queue and clear to clear the queue.
import Queue from 'core/queue/simple';
const
queue = new Queue();
queue.push(1);
queue.push(5);
console.log(queue.head); // 1
queue.clear();
console.log(queue.head); // undefined
console.log(queue.length); // 0
-
-
-
- import { AbstractQueue } from 'core/queue';
export default class Queue extends AbstractQueue {
internalQueue = [];
get head() {
return this.internalQueue[0];
}
get length() {
return this.internalQueue.length;
}
push(el) {
return this.internalQueue.push(el);
}
pop() {
return this.internalQueue.shift();
}
clone() {
const queue = new Queue();
queue.internalQueue = this.internalQueue.slice();
return queue;
}
clear() {
this.internalQueue = [];
}
}
-
-This module provides a class to organize a Queue data structure with support of task merging by a specified hash function.
-It means that the same tasks aren't duplicated. See core/queue for more information.
import MergeQueue from 'core/queue/merge';
const queue = new MergeQueue((task) => JSON.stringify(task));
queue.push({a: 1});
queue.push({a: 1});
console.log(queue.length); // 1
queue.push({a: 2});
console.log(queue.head); // {a: 1}
console.log(queue.length); // 2
queue.clear();
console.log(queue.length); // 0
-
-
-
- To provide a function to calculate task hashes, use the structure constructor.
-By default, all hashes are calculated via Object.fastHash.
import MergeQueue from 'core/queue/merge';
const queue = new MergeQueue((task) => JSON.stringify(task));
queue.push({a: 1});
queue.push({a: 1});
-
-This module provides a class to organize an ordered Queue data structure.
-See core/queue for more information.
import OrderedQueue from 'core/queue/order';
const
queue = new OrderedQueue<number>((a, b) => a - b);
queue.push(1);
queue.push(5);
queue.push(2);
queue.push(-1);
queue.push(5);
queue.push(2);
queue.push(-1);
queue.push(5);
console.log(queue.length); // 8
console.log(queue.head); // 5
console.log(queue.pop()); // 5
console.log(queue.head); // 5
console.log(queue.pop()); // 5
console.log(queue.pop()); // 5
console.log(queue.pop()); // 2
console.log(queue.pop()); // 2
queue.clear();
console.log(queue.length); // 0
-
-
-
- To compare different elements from the queue, a special comparator function is used, which has the same API as
-the native comparator Array.prototype.sort. To provide a comparator, use the structure constructor.
import OrderedQueue from 'core/queue/order';
const
queue = new OrderedQueue<number>((a, b) => a - b);
queue.push(1);
queue.push(5);
-
-This module provides a class to organize a simple Queue data structure.
-See core/queue for more information.
import Queue from 'core/queue/simple';
const
queue = new Queue();
queue.push(1);
queue.push(5);
queue.push(2);
queue.push(-1);
queue.push(5);
queue.push(2);
queue.push(-1);
queue.push(5);
console.log(queue.length); // 8
console.log(queue.head); // 1
console.log(queue.pop()); // 1
console.log(queue.head); // 5
console.log(queue.pop()); // 5
console.log(queue.pop()); // 2
console.log(queue.pop()); // -1
console.log(queue.pop()); // 5
console.log([...queue]); // [2, -1, 5]
const
clonedQueue = queue.clone();
queue.clear();
console.log(queue.length); // 0
console.log(clonedQueue.length); // 3
-
-This module provides an abstract class for a [[WorkerQueue]] data structure.
-The submodules contain different implementations of that class. See core/queue for more information.
The structure constructor expects a function that will be invoked on each processed task. -The function can return a promise (it will be awaited).
-import WorkerQueue from 'core/queue/worker/simple';
const queue = new WorkerQueue((task) => {
console.log(task);
});
queue.push({a: 1});
queue.push({a: 2});
-
-
-
- 1]The maximum number of concurrent workers.
-import WorkerQueue from 'core/queue/worker/simple';
const queue = new WorkerQueue((task) => {
console.log(task);
}, {concurrency: 2});
queue.push({a: 1});
console.log(queue.length); // 0
queue.push({a: 2});
console.log(queue.length); // 0
queue.push({a: 3});
console.log(queue.length); // 1
queue.push({a: 4});
console.log(queue.length); // 2
-
-
-
- How often to update task statuses, i.e. the next batch of tasks will be executed at the specified interval -(by default on the next tick of the process).
- - -The maximum number of concurrent workers.
- - -How often to update task statuses, i.e. the next batch of tasks will be executed at the specified interval -(by default on the next tick of the process).
- - -Number of active workers.
-This module provides a class to organize a [[WorkerQueue]] data structure with support of task merging by a specified hash function.
-It means that the same tasks aren't duplicated. See core/queue/worker and
-core/queue for more information.
import MergeQueue from 'core/queue/worker/merge';
const queue = new MergeQueue((task) => {
console.log(task);
}, {
concurrency: 2,
refreshInterval: 50,
hashFn: (task) => JSON.stringify(task)
});
queue.push({a: 1});
queue.push({a: 1});
console.log(queue.length); // 0
queue.push({a: 2});
console.log(queue.length); // 0
queue.push({a: 3});
console.log(queue.length); // 1
queue.push({a: 4});
console.log(queue.length); // 2
queue.clear();
console.log(queue.length); // 0
-
-
-
- To provide a function to calculate task hashes, use the structure constructor hashFn option.
-By default, all hashes are calculated via Object.fastHash.
import MergeQueue from 'core/queue/worker/merge';
const queue = new MergeQueue((task) => {
console.log(task);
}, {
hashFn: (task) => JSON.stringify(task)
});
queue.push({a: 1});
queue.push({a: 1});
-
-This module provides a class to organize a [[WorkerQueue]] data structure.
-See core/queue/worker and core/queue for more information.
import WorkerQueue from 'core/queue/worker/simple';
const queue = new WorkerQueue((task) => {
console.log(task);
}, {concurrency: 2});
queue.push({a: 1});
console.log(queue.length); // 0
queue.push({a: 2});
console.log(queue.length); // 0
queue.push({a: 3});
console.log(queue.length); // 1
queue.push({a: 4});
console.log(queue.length); // 2
queue.clear();
console.log(queue.length); // 0
-
-This module provides a class to create a range structure.
- - -The ranges can be different: numbers, characters, dates.
- - -import Range from 'core/range';
const
range = new Range(0, 10);
// true
console.log(range.contains(5));
// 6..10
console.log(range.intersect(new Range(6, 15)).toString());
console.log(range.type === 'number');
-
-
-
- import Range from 'core/range';
const
range = new Range('a', 'd');
// true
console.log(range.contains('b'));
// a..c
console.log(range.intersect(new Range('c', 'z')).toString());
// You can define one border as a code point
console.log(new Range('a', 'd'.codePointAt() + 2));
console.log(new Range('a'.codePointAt() + 1), 'd');
console.log(range.type === 'string');
-
-
-
- const
range = new Range(new Date(2019, 5), new Date(2020, 5));
// true
console.log(range.contains(new Date(2019, 8)));
// Sat Jun 01 2019 00:00:00 GMT+0300..Tue Oct 01 2019 00:00:00 GMT+0300
console.log(
range.intersect(
new Range(new Date(2017, 9),
new Date(2019, 9))
).toString()
);
console.log(range.type === 'date');
-
-
-
- By default, all ranges include their bounds, but you free to change this behavior. Just wrap bounds by an array.
-import Range from 'core/range';
// [0, 1, 2, 3]
console.log(new Range(0, 3).toArray());
// [1, 2, 3]
console.log(new Range([0], 3).toArray());
// [0, 1, 2]
console.log(new Range(0, [3]).toArray());
// [1, 2]
console.log(new Range([0], [3]).toArray());
-
-
-
- If the start bound of a range more than the end bound, the created range will enumerate elements by descending order. -This behavior works well with any range.
-import Range from 'core/range';
// [3, 2, 1]
console.log(new Range(3, 1).toArray());
// [3, 2]
console.log(new Range(3, [1]).toArray());
// ['c', 'b', 'a']
console.log(new Range('c', 'a').toArray());
-
-
-
- It's possible to create an infinite range. Just skip one or both bound the creating the range.
-import Range from 'core/range';
// Range from 0 to Infinity
// 0..
console.log(new Range(0).toString());
// Range from -Infinity to a
// ..a
console.log(new Range(null, 'a').toString());
// Range from -Infinity to Infinity
// ..
console.log(new Range().toArray());
-
-Mind, you can't transform infinite ranges to arrays by invoking toArray, but you free to use iterators.
-Physically, the number and date ranges start from Number.MIN_SAFE_INTEGER to Number.Max_SAFE_INTEGER.
-The string rages start from \0 to the last Unicode code point.
import Range from 'core/range';
// Range from 0 to Infinity
// 0..
console.log(new Range(0).toString());
const
arr = [];
for (const el of new Range(0)) {
arr.push(el);
if (el > 1e3) {
break;
}
}
-
-
-
- All ranges support three kinds of iterators. -Each kind of iterators can take a step value to iterate elements (for date ranges it means milliseconds to shift).
-import Range from 'core/range';
for (const el of new Range('a', 'c')) {
// 'a' 'b' 'c'
console.log(el);
}
for (const el of new Range(0, 3).values()) {
// 0 1 2 3
console.log(el);
}
for (const el of new Range(0, 3).values(2)) {
// 0 2
console.log(el);
}
-
-import Range from 'core/range';
for (const el of new Range(3, 1).indices()) {
// 0 1 2
console.log(el);
}
for (const el of new Range(0, 3).indices(2)) {
// 0 1
console.log(el);
}
-
-import Range from 'core/range';
for (const el of new Range('c', 'a').entries()) {
// [0, 'c'] [1, 'b'] [2 'a']
console.log(el);
}
for (const el of new Range('c', 'a').entries(2)) {
// [0, 'c'] [1, 'a']
console.log(el);
}
-
-
-
- Ranges support a bunch of methods to work with them.
- - -The method returns true if an element is contained inside the range -(the element can be a simple value or another range).
-import Range from 'core/range';
// true
console.log(new Range(0, 10).contains(4));
// false
console.log(new Range(0, [10]).contains(10));
// false
console.log(new Range(0, 10).contains(12));
// false
console.log(new Range(0, 10).contains('a'));
// true
console.log(new Range(0, 10).contains(Range(3, 6)));
// false
console.log(new Range(0, 10).contains(Range(3, 16)));
// false
console.log(new Range(0, 10).contains(Range('a', 'b')));
-
-
-
- The method returns a new range with the latest starting point as its start, and the earliest ending point as its end. -If the two ranges do not intersect, this will effectively produce an empty range.
-The method preserves element ordering of the first range. -The intersection of ranges with different types will always produce an empty range.
-import Range from 'core/range';
// 8..10
console.log(new Range(0, 10).intersect(new Range([7], 14)).toString());
// 10..7
console.log(new Range(10, 0).intersect(new Range(7, 14)).toString());
// 7..10
console.log(new Range(0, 10).intersect(new Range(7)).toString());
// 7..
console.log(new Range(0).intersect(new Range(7)).toString());
// ''
console.log(new Range(0, 10).intersect(new Range(11, 14)).toString());
// ''
console.log(new Range(0, 10).intersect(new Range('a', 'z')).toString());
-
-
-
- The method returns a new range with the earliest starting point as its start, and the latest ending point as its end. -If the two ranges do not intersect, this will effectively remove the "gap" between them.
-The method preserves element ordering of the first range. -The union of ranges with different types will always produce an empty range.
-import Range from 'core/range';
// 0..13
console.log(new Range(0, 10).union(new Range(7, [14])).toString());
// 14..0
console.log(new Range(10, 0).union(new Range(7, 14)).toString());
// 0..
console.log(new Range(0, 10).union(new Range(7)).toString());
// ..
console.log(new Range().union(new Range(7)).toString());
// ''
console.log(new Range(0, 10).union(new Range('a', 'z')).toString());
-
-
-
- The method clones the range and returns a cloned one.
- - -The method clones the range with reversing of element ordering and returns a new one.
-import Range from 'core/range';
// [3, 2, 1, 0]
console.log(new Range(0, 3).reverse().toArray());
-
-
-
- The method clamps an element to be within the range if it falls outside.
-If the range is invalid or empty, the method always returns null.
import Range from 'core/range';
// 3
console.log(new Range(0, 10).clamp(3));
// 'd'
console.log(new Range('a', 'd').clamp('z'));
// null
console.log(new Range(0, [0]).clamp(10));
-
-
-
- The method returns a span of the range. -The span includes both the start and the end.
-If the range is a date range, the value is in milliseconds.
-If the range is invalid or empty, the method always returns 0.
import Range from 'core/range';
// 4
console.log(new Range(7, 10).span());
// 0
console.log(new Range(0, [0]).span());
-
-
-
- The method creates an array from the range and returns it. -Also, it can take a step to iterate elements (for date ranges, it means milliseconds to shift). -Mind, you can't transform infinite ranges to arrays, but you free to use iterators.
-import Range from 'core/range';
// [0, 3, 6, 9]
console.log(new Range(0, 10).toArray(3));
// ['a', 'b']
console.log(new Range('a', ['c']).toArray());
// []
console.log(new Range(0, [0]).toArray());
-
-
-
- The method creates a string from the range and returns it. -If the range invalid or empty, the method always returns an empty string.
-import Range from 'core/range';
// 0..10
console.log(new Range(0, 10).toString());
// 0..9
console.log(new Range(0, [10]).toString());
// 0..
console.log(new Range(0).toString());
// ..z
console.log(new Range(null, 'z').toString());
// ''
console.log(new Range(0, [0]).toString());
-
-This module provides API to request/submit data using different runtime engines, like XHR, Fetch, etc. -The submodules contain different classes to work with HTTP headers, server responses and errors.
-import request from 'core/request';
request('https://foo.com', {
method: 'POST',
body: {
bla: 'bar'
}
}).then(async ({response}) => {
console.log(await response.decode(), response.status);
});
-
-
-
- xhrfetchbrowser (the engine uses fetch when it's possible, otherwise xhr)node (the engine uses Got as a request library)provider (the engine based on core/data providers)The function has three overloads of usage.
- - -The first one creates a request based on the specified parameters. -As the first argument, the function takes a URL to request. The second argument is optional and declares additional request options.
-import request from 'core/request';
request('https://foo.com/users').then(async ({data, response}) => {
console.log(await data, response.status);
});
request('https://foo.com/create-user', {method: 'POST', body: {name: 'Bob'}}).then(async ({data, response}) => {
console.log(await data, response.status);
});
-
-
-
- There are two variants of request URL-s:
-absolute
-import request from 'core/request';
request('https://foo.com/users').data.then(console.log);
-
-relative
-import request from 'core/request';
request('/users').data.then(console.log);
-
-In the case of a relative URL, the full request URL is based on the application location.
import request from 'core/request';
// location.origin === 'https://foo.com';
// URL: https://foo.com/users
request('/users').data.then(console.log);
// location.origin.href === 'https://foo.com/bla';
// URL: https://foo.com/bla/users
request('users').data.then(console.log);
-
-But also, you can define the base API URL within your application config. This URL will be used for any relative requests.
-config
-import { extend } from '@v4fire/client/config';
export default extend({
api: 'https://api.foo.com'
});
-
-foo.ts
-import request from 'core/request';
// URL: https://api.foo.com/users
request('/users').data.then(console.log);
-
-In addition, you can read or write the api property from core/request#globalOpts or
-through globalOpts.api property within your encoders/decoders/middlewares.
import request, { globalOpts } from 'core/request';
console.log(globalOpts.api);
request('/users', {
middlewares: {
api: ({globalOpts}) => {
if (globalOpts.api == null) {
globalOpts.api = 'https://api.foo.com';
}
}
}
}).data.then(console.log);
-
-
-
- This overload is useful to create a wrapped request function. -It takes an object with request options and returns a new request function. -This function will use the passed options by default, but you can override them. -Finally, the result function can take another object with options and returns a new wrapped function recursively. -Parameters from the first and second invoke will be deeply merged.
-import request from 'core/request';
const post = request({method: 'POST'});
const postWithoutCredentials = request({method: 'POST', credentials: false});
postWithoutCredentials('https://foo.com/create-user', {body: {name: 'Bob'}}).then(async ({data, response}) => {
console.log(await data, response.status);
});
-
-
-
- The third overload helps to create a factory of requests. -It takes a URL to request, additional options (optional), and the special resolve function. -Then, it returns a new function to create requests with the passed options.
-import request from 'core/request';
const createUser = request(
'https://foo.com/user',
(url, {opts, globalOpts, ctx}, name, data) => {
opts.body = data;
// If the resolver function returns a string, it will be concatenated with the original request URL
return name;
},
{
method: 'POST'
}
);
// POST: https://foo.com/user/bob
// BODY: {age: 37}
createUser('bob', {age: 37}).then(async ({data, response}) => {
console.log(await data, response.status);
});
const wrappedRequest = request(
'https://foo.com/user',
(url, {opts, globalOpts, ctx}, ...args) => {
opts.body = args.at(-1);
// If the resolver function returns an array of string, it will replace the original request URL
return ['https://bla.com', ...args.slice(0, -1)];
}
);
// GET: https://bla.com/bla/baz
wrappedRequest('bla', 'baz', {age: 37})
-
-
-
- After creating a request, the function returns an instance of core/promise/abortable.
-The promise resolves with a special response object.
interface RequestResponseObject<D = unknown> {
// @see core/request/modules/context
ctx: Readonly<RequestContext<D>>;
// @see core/request/response
response: Response<D>;
// A promise with the response data
data: Promise<Nullable<D>>;
// An asynchronous iterable object to parse the response in a stream form
stream: AsyncIterableIterator<unknown>;
// An emitter to listen to raw request engine events
emitter: EventEmitter;
// An iterator to parse data in a stream form
[Symbol.asyncIterator](): AsyncIterable<RequestResponseChunk>;
// A type of the used cache if the data has been taken from it
cache?: CacheType;
// A method to drop cache of the request
dropCache(): void;
}
-
-import request from 'core/request';
request('https://foo.com/users').then(async ({data, response}) => {
console.log(await data, response.status);
});
-
-Also, you can get data, emitter or Symbol.asyncIterator from a request promise.
import request from 'core/request';
import xhr from 'core/request/engines/xhr';
request('https://foo.com/users').data.then((data) => {
console.log(data);
});
request('https://foo.com/users', {engine: xhr}).emitter.on('readystatechange', (e) => {
console.log(e);
});
-
-
-
- If the used request engine supports streaming, you can use it via an async iterator. -Notice, you won't switch to another form when you read response as a whole data or in a stream form.
-import request from 'core/request';
(async () => {
for await (const {loaded, total, data} of request('https://foo.com/users')) {
console.log(loaded, total, data);
}
})();
request('https://foo.com/users').then(async (response) => {
for await (const {loaded, total, data} of response) {
console.log(loaded, total, data);
}
});
request('https://foo.com/users').then(async ({response}) => {
for await (const {loaded, total, data} of response) {
console.log(loaded, total, data);
}
});
-
-If you want to process only stream data without total and loaded fields, use the stream getter.
import request from 'core/request';
(async () => {
for await (const data of request('https://foo.com/users').stream) {
console.log(data);
}
})();
request('https://foo.com/users').then(async (response) => {
for await (const data of response.stream) {
console.log(data);
}
});
request('https://foo.com/users').then(async ({response}) => {
for await (const data of response.decodeStream()) {
console.log(data);
}
});
-
-Mind, the XHR engine partially supports streaming based on its progress event.
If the used request engine emits some events, you can listen there via the emitter property.
-Mind, not every engine dispatch events.
import request from 'core/request';
import xhr from 'core/request/engines/xhr';
const
req = request('https://foo.com/users', {engine: xhr});
req.emitter.on('progress', (e) => {
console.log(e);
});
req.emitter.on('upload.progress', (e) => {
console.log(e);
});
-
-
-
- The request function can accept a bunch of optional parameters to make a request.
- - -HTTP method to create a request. -See more.
-import request from 'core/request';
request('//create-user', {
method: 'POST',
body: {name: 'Bob'}
}).data.then(console.log);
-
-
-
- Additional HTTP request headers. You can provide them as a simple dictionary or an instance of the Headers class.
-Also, you can pass headers as an instance of the core/request/headers class.
-See more.
import request from 'core/request';
request('//users', {
headers: {
Authorization: myJWT
}
}).data.then(console.log);
-
-
-
- Enables providing of credentials for cross-domain requests. -Also, you can manage to omit any credentials if the used request engine supports it.
-import request from 'core/request';
import fetchEngine from 'core/request/engines/fetch';
request('//users', {
credentials: false
}).data.then(console.log);
request('//users', {
engine: fetchEngine,
credentials: 'omit'
}).data.then(console.log);
-
-
-
- Request parameters that will be serialized to a string and passed via a request URL.
-To customize how to encode data to a query string, see querySerializer.
import request from 'core/request';
request('//user', {
query: {id: 125}
}).data.then(console.log);
-
-
-
- Returns a serialized value of the specified query object.
-import request from 'core/request';
import { toQueryString } from 'core/url';
request('//user', {
query: {ids: [125, 35, 454]},
querySerializer: (data) => toQueryString(data, {arraySyntax: true})
}).data.then(console.log);
-
-
-
- A request body. Mind, not every HTTP method can send data in this way.
-For instance, GET or HEAD requests can send data only with URLs (@see query).
import request from 'core/request';
request('//create-user', {
method: 'POST',
body: {name: 'Bob'}
}).data.then(console.log);
const form = new FormData();
form.set('name', 'Garry');
form.set('age', '36');
request('//send-form', {
method: 'POST',
body: form
}).data.then(console.log);
-
-
-
- A mime type of the request data (if not specified, it will be cast dynamically).
-import request from 'core/request';
request('//create-user', {
method: 'POST',
body: {name: 'Bob'},
contentType: 'application/x-msgpack',
encoder: toMessagePack
}).data.then(console.log);
-
-
-
- A type of the response data (if not specified, it will be cast dynamically from the response headers):
-'text' - the result is interpreted as a simple string;'json' - the result is interpreted as a JSON string;'document' - the result is interpreted as an XML/HTML document;'formData' - result is interpreted as a FormData object;'blob' - the result is interpreted as a Blob object;'arrayBuffer' - the result is interpreted as an array buffer;'object' - the result is interpreted "as is" without any converting.import request from 'core/request';
request('//users', {
responseType: 'arrayBuffer',
decoder: fromMessagePack
}).data.then(console.log);
-
-
-
- new Range(200, 299)]A list of status codes (or a single code) that match successful operation. -Also, you can pass a range of codes.
-import request from 'core/request';
import Range from 'core/range';
request('//users', {
okStatuses: [200, 201]
}).data.then(console.log);
request('//users', {
okStatuses: new Range(200, 210)
}).data.then(console.log);
-
-
-
- A value in milliseconds for a request timeout.
-import request from 'core/request';
request('//users', {
timeout: (10).seconds()
}).data.then(console.log);
-
-
-
- Options to retry bad requests or a number of maximum request retries.
-import request from 'core/request';
request('//users', {
timeout: (10).seconds(),
retry: 3
}).data.then(console.log);
request('//users', {
timeout: (10).seconds(),
retry: {
attempts: 3,
delay: (attempt) => attempt * (3).seconds()
}
}).data.then(console.log);
-
-/**
* @typeparam D - response data type
*/
export interface RetryOptions<D = unknown> {
/**
* Maximum number of attempts to request
*/
attempts?: number;
/**
* Returns a number in milliseconds (or a promise) to wait before the next attempt.
* If the function returns false, it will prevent all further attempts.
*
* @param attempt - current attempt number
* @param error - error object
*/
delay?(attempt: number, error: RequestError<D>): number | Promise<void> | false;
}
-
-
-
- A map of API parameters.
-These parameters apply if the original request URL is not absolute, and they can be used to customize the
-base API URL depending on the runtime environment. If you define the base API URL via
-config#api or globalOpts.api, these parameters will be mapped on it.
import request from 'core/request';
// URL (IS_PROD === true): https://foo.com/users
// URL (IS_PROD === false): https://foo.com/foo-stage
request('/users', {
api: {
protocol: 'https',
domain2: () => IS_PROD ? 'foo' : 'foo-stage',
zone: 'com'
}
}).data.then(console.log);
// URL (globalOpts.api === 'https://api.foo.com' && IS_PROD === true): https://api.foo.com/users
// URL (globalOpts.api === 'https://api.foo.com' && IS_PROD === false): https://api.foo-stage.com/users
request('/users', {
api: {
domain2: () => IS_PROD ? 'foo' : 'foo-stage',
}
}).data.then(console.log);
-
-export interface RequestAPI {
/**
* The direct value of API URL.
* If this parameter is defined, all other parameters will be ignored.
*
* @example
* `'https://google.com'`
*/
url?: RequestAPIValue;
/**
* API protocol
*
* @example
* `'http'`
* `'https'`
*/
protocol?: RequestAPIValue;
/**
* Value for an API authorization part
*
* @example
* `'login:password'`
*/
auth?: RequestAPIValue;
/**
* Value for an API domain level 6 part
*/
domain6?: RequestAPIValue;
/**
* Value for an API domain level 5 part
*/
domain5?: RequestAPIValue;
/**
* Value for an API domain level 4 part
*/
domain4?: RequestAPIValue;
/**
* Value for an API domain level 3 part
*/
domain3?: RequestAPIValue;
/**
* Value for an API domain level 2 part
*/
domain2?: RequestAPIValue;
/**
* Value for an API domain zone part
*/
zone?: RequestAPIValue;
/**
* Value for an API api port
*/
port?: RequestAPIValue<string | number>;
/**
* Value for an API namespace part: it follows after '/' character
*/
namespace?: RequestAPIValue;
}
-
-
-
- A strategy of caching for requests that support caching (by default, only GET requests can be cached):
-'forever' - caches all requests and stores their values forever within the active session or
-until the cache expires (if cacheTTL is specified);'queue' - caches all requests, but more frequent requests will push less frequent requests;'never' - never caches any requests;import request from 'core/request';
import RestrictedCache from 'core/cache/restricted';
request('/users', {
cacheStrategy: 'forever'
}).data.then(console.log);
request('/users', {
cacheStrategy: new RestrictedCache(50)
}).data.then(console.log);
-
-If you set a strategy using string identifiers, all requests will be stored within the global cache objects.
-import request, { cache } from 'core/request';
request('/users', {
cacheStrategy: 'forever'
}).data.then(console.log);
cache.forever.clear();
-
-
-
- A value in milliseconds that indicates how long a request value should keep in the cache -(all requests are stored within the active session without expiring by default).
-import request from 'core/request';
import RestrictedCache from 'core/cache/restricted';
request('/users', {
cacheStrategy: 'forever',
cacheTTL: (10).minutes()
}).data.then(console.log);
request('/users', {
cacheStrategy: new RestrictedCache(50),
cacheTTL: (10).minutes()
}).data.then(console.log);
-
-
-
- This option enables support of offline caching.
-By default, a request can only be taken from a cache if there is no network.
-You can customize this logic by providing a custom cache object with the core/cache/decorators/persistent decorator.
import request from 'core/request';
import { asyncLocal } from 'core/kv-storage';
import addPersistent from 'core/cache/decorators/persistent';
import SimpleCache from 'core/cache/simple';
request('/users', {
cacheStrategy: 'forever',
offlineCache: true
});
const
opts = {loadFromStorage: 'onInit'},
persistentCache = await addPersistent(new SimpleCache(), asyncLocal, opts);
request('/users', {
cacheStrategy: persistentCache
});
-
-
-
- A value in milliseconds that indicates how long a request value should keep in the offline cache.
-import request from 'core/request';
import RestrictedCache from 'core/cache/restricted';
request('/users', {
cacheStrategy: 'forever',
offlineCache: true,
offlineCacheTTL: (1).day()
});
request('/users', {
cacheStrategy: new RestrictedCache(50),
offlineCache: true,
offlineCacheTTL: (1).day()
}).data.then(console.log);
-
-
-
- ['GET']]A list of request methods that support caching.
-import request from 'core/request';
request('/users', {
cacheStrategy: 'forever',
cacheMethods: ['GET', 'POST']
}).data.then(console.log);
-
-
-
- A unique cache identifier: it can be useful to create request factories with isolated cache storages.
-import request from 'core/request';
const createUser = request(
'https://foo.com/user',
(url, {opts, globalOpts, ctx}, name, data) => {
opts.body = data;
return name;
},
{
method: 'POST',
cacheId: 'users'
}
);
createUser('bob', {age: 37}).then(async ({data, response}) => {
console.log(await data, response.status);
});
-
-
-
- A dictionary or iterable value with middleware functions: functions take an environment of request parameters and can modify theirs. -Please notice that the order of middleware depends on the structure you use. -Also, if at least one of the middlewares returns a function, invoking this function will be returned as the request result. -It can be helpful to organize mocks of data and other similar cases when you don't want to execute a real request.
-import request from 'core/request';
request('/users', {
middlewares: {
addAPI({globalOpts}) {
if (globalOpts.api == null) {
globalOpts.api = 'https://api.foo.com';
}
},
addSession({opts}) {
opts.headers.set('Authorization', myJWT);
}
}
}).data.then(console.log);
// Mocking response data
request('/users', {
middlewares: [
({ctx}) => () => ctx.wrapAsResponse([
{name: 'Bob'},
{name: 'Robert'}
])
]
});
-
-
-
- A function (or a sequence of functions) takes the current request data and returns new data to request. -If you provide a sequence of functions, the first function will pass a result in the next function from the sequence, etc.
-import request from 'core/request';
request('//create-user', {
method: 'POST',
body: {name: 'Bob'},
contentType: 'application/x-msgpack',
encoder: [normalize, toMessagePack]
}).data.then(console.log);
-
-
-
- A function (or a sequence of functions) takes the current request response data and returns new data to respond. -If you provide a sequence of functions, the first function will pass a result to the next function from the sequence, etc.
-import request from 'core/request';
request('//users', {
responseType: 'arrayBuffer',
decoder: fromMessagePack
}).data.then(console.log);
-
-
-
- A function (or a sequence of functions) takes the current request response data chunk and yields a new chunk to respond via an async iterator. -If you provide a sequence of functions, the first function will pass a result to the next function from the sequence, etc. -This parameter is used when you're parsing responses in a stream form.
-import request from 'core/request';
import { sequence } from 'core/iter/combinators';
import { pick, andPick, assemble, streamArray } from 'core/json/stream';
/*
{
"total": 3,
"data": [
{"name": "Bob", "age": 21},
{"name": "Rob", "age": 24},
{"name": "Jack", "age": 50}
]
}
*/
const {stream} = request('//users', {
responseType: 'json',
streamDecoder: (data) => sequence(
assemble(pick(data, 'total')),
streamArray(andPick(data, 'data'))
)
});
(async () => {
for await (const chunk of stream) {
// 3
// {"name": "Bob", "age": 21}
// {"name": "Rob", "age": 24}
// {"name": "Jack", "age": 50}
console.log(chunk);
}
})();
-
-
-
- convertIfDate]A reviver function for JSON.parse or false to disable defaults.
-By default, it parses some strings as Date instances.
A dictionary with some extra parameters for the request: is usually used with middlewares to provide domain-specific information.
-import request from 'core/request';
request('/users', {
meta: {addSession: true},
middlewares: {
addSession({opts}) {
if (opts.meta.addSession) {
opts.headers.set('Authorization', myJWT);
}
}
}
}).data.then(console.log);
-
-
-
- A meta flag that indicates that the request is important: is usually used with middlewares to indicate that -the request needs to be executed as soon as possible.
-import request from 'core/request';
request('/users', {
important: true,
middlewares: {
doSomeWork({ctx}) {
if (ctx.important) {
// Do some work...
}
}
}
}).data.then(console.log);
-
-
-
- This parameter defined a request engine to use.
-The engine - is a simple function that takes request parameters and returns an abortable promise resolved with the core/request/response instance.
-Mind, some engines provide extra features. For instance, you can listen to upload progress events with the XHR engine.
-Or, you can parse responses in a stream form with the Fetch engine.
import AbortablePromise from 'core/promise/abortable';
import request from 'core/request';
import Response from 'core/request/response';
import fetchEngine from 'core/request/engines/fetch';
import xhrEngine from 'core/request/engines/xhr';
request('//users', {
engine: fetchEngine,
credentials: 'omit'
}).data.then(console.log);
request('//users', {
engine: xhrEngine
}).data.then(console.log);
request('//users', {
engine: (params) => new AbortablePromise((resolve) => {
const res = new Response({
message: 'Hello world'
}, {responseType: 'object'});
resolve(res);
}, params.parent)
}).data.then(console.log);
-
-Creates a querystring from the specified data and returns it
-Creates a querystring from the specified data and returns it
-additional options
-This module provides a function that creates a request engine based on the Fetch API. -Mind, this API is developed to work in a browser — node.js support only for tests.
- - -AbortController.import fetchEngine from 'core/request/engines/fetch';
req('/search', {engine: fetchEngine}).then(({response}) => {
console.log(response.decode());
});
-
-Creates request by using the fetch API with the specified parameters and returns a promise
-Converts the specified data to send via request engines. -The function returns a tuple, where on the first position is converted data and its new content type on -the second position.
-This module provides a function that creates a request engine for node.js scripts.
- - -import nodeEngine from 'core/request/engines/node';
req('/search', {engine: nodeEngine}).then(({response}) => {
console.log(response.decode());
});
-
-Creates request by using node.js with the specified parameters and returns a promise
-This module provides a function that creates a request engine based on the passed data provider.
-You can use this kind of provider for simple requests by using core/request.
import Provider, { provider } from 'core/data';
import createProviderEngine from 'core/request/engines/provider';
@provider
class DataProvider extends Provider {
}
const
// Also, you can pass a name of the provider or link to the instance
req = request({engine: createProviderEngine(DataProvider)});
req('/search')
.then(({response}) => {
console.log(response.decode());
});
// You can specify which provider method should be invoked based on the request method
// (by default will be used mapping from the provider properties, like `addMethod` or `updMethod`)
const req2 = request('/search', {
engine: createProviderEngine(DataProvider, {
PATCH: 'upd'
})
});
-
-Or you can use it with other data providers.
-import Provider, { provider } from 'core/data';
import createProviderEngine from 'core/request/engines/provider';
@provider
class BaseProvider extends Provider {
baseUrl = '/api'
}
@provider
class DataProvider extends Provider {
static request = BaseProvider.request({
engine: createProviderEngine(BaseProvider)
});
}
@provider
class DataProvider2 extends Provider {
static request = BaseProvider.request({
engine: createProviderEngine(BaseProvider, {
// Invoking of `DataProvider2.upd` will call `DataProvider2.add`
upd: 'add'
})
});
}
-
-
-
- To resolve an issue, when we have the one server API and two variants of providers, -and we want to cache the response of the "parent" provider. The problem roots are based on the fact that every provider -stores its cache within the separated storage. It's necessary because different providers can have different -decoders (provider stores data in the cache after applying decoders). We can trap in a situation of data collision -while saving the cache: the decoders are not used to generate a hash of the request, so it's possible to meet more than -one set of data with the same hash.
-@provider
class BaseProvider extends Provider {
static request = Provider.request({cacheStrategy: 'forever'});
baseUrl = '/api'
}
@provider
class DataProvider extends BaseProvider {
static decoders = DataProviderDecoders;
}
@provider
class DataProvider2 extends BaseProvider {
static decoders = DataProvider2Decoders;
}
// Will use different cache storages, i.e., the cache doesn't share between instances.
// It happens because every data provider instance has the separated cache storage.
new DataProvider().get();
new DataProvider2().get();
-
-If we start to use the parent provider as an engine instead of inheritance, it resolves cache sharing.
-@provider
class BaseProvider extends Provider {
static request = Provider.request({cacheStrategy: 'forever'});
baseUrl = '/api'
}
@provider
class DataProvider extends Provider {
static request = BaseProvider.request({
engine: createProviderEngine(BaseProvider)
});
}
@provider
class DataProvider2 extends Provider {
static request = BaseProvider.request({
engine: createProviderEngine(BaseProvider)
});
}
// Every data provider stores its cache within the separated cache storage, but also,
// it will be cached by the parent provider.
new DataProvider().get();
new DataProvider2().get();
-
-
-
- When we create a request, we can also specify many encoders, decoders, and other middlewares to apply. -When we are using another provider as an engine, it can also have its middlewares. How do they work together?
-Providers properties during request execution are combined in an obvious way:
-/$engineProvider/$currentRequest.@provider
class DataProvider extends Provider {
static decoders = {
get: [parseFromProtobuf]
}
baseUrl = '/api'
}
// url = /api/search
const req = request('/api/search', {
engine: createProviderEngine(DataProvider),
decoder: normalizeParsedData
});
-
-Creates a request engine from the specified data provider
-provider constructor, an instance, or the global name
-This module provides a function that creates a request engine based on the XMLHttpRequest API. -Mind, this API is developed to work in a browser — node.js support only for tests.
- - -AbortController.total/loaded fields without data).import xhrEngine from 'core/request/engines/xhr';
const req = req('/search', {engine: xhrEngine}).then(({response}) => {
console.log(response.decode());
});
req.emitter.on('progress', () => {
// ..
});
req.emitter.on('upload.progress', () => {
// ..
});
-
-Creates request by using XMLHttpRequest with the specified parameters and returns a promise
-This module provides a class for any request error and its details' extractor.
- - -A constructor of the class accepts two parameters: required type and optional details.
throw new RequestError(RequestError.InvalidStatus, details);
-
-Now we support the following types of RequestError:
RequestError.InvalidStatus - a server has responded with a non-ok status;RequestError.Abort - a request was aborted;RequestError.Timeout - a request was aborted because of a timeout;RequestError.Offline - a request was failed because there is no connection to a network;RequestError.Engine - a request was failed because of an internal request engine' error.The second parameter could contain request and response objects and an error object that is caused the problem.
The extractor gets details from RequestError. A constructor of the class accepts one optional parameter with extra options.
-These options allow filtering headers from request and response objects of the error's details object. It helps to hide
-sensitive information.
The options itself look like this:
-const opts = {
headers: {
include: [/*...*/],
exclude: [/*...*/]
}
};
const extractor = new RequestErrorDetailsExtractor(opts);
-
-If include is defined, the extractor gets only headers from this array.
-If exclude is defined, the extractor gets all available headers except the specified ones.
-If both options are defined, then only inlcude option will be used.
This module provides a class to create a set of HTTP headers. -The class' API is pretty similar to native the Headers class -but has some extra functionality and doesn't implement the Guard conceptions.
- - -Because, the core/request module can use different engines, but not only fetch or XMLHttpRequest.
-These engines can have different peculiarities, so we need to create a new abstraction.
There is a possibility to provide initial headers while creating a new Headers instance. -These headers can be provided using a simple dictionary when keys are header names and values are header values. -The value can be defined as a string or list of strings - all values will be joined into one string with a comma separator.
-import Headers from 'core/request/headers';
const headers = new Headers({
'Content-Language': ['en', 'ru'],
'Cache-Control': 'no-cache'
});
console.log(headers.get('Content-Language')); // 'en, ru'
-
-Also, initial headers can be provided via another Headers instance or native browser Headers instance.
-import Headers from 'core/request/headers';
const headers = new Headers({
'Content-Language': ['en', 'ru'],
'Cache-Control': 'no-cache'
});
const headers2 = new Headers(headers);
console.log(headers2.get('Content-Language')); // 'en, ru'
-
-Or, you can pass a string with raw HTTP headers.
-import Headers from 'core/request/headers';
const headers = new Headers(`
Content-Language: en, ru
Cache-control: no-cache
`);
console.log(headers.get('Content-Language')); // 'en, ru'
-
-
-
- The class supports a feature when headers' keys or values link to extra values from request data. -To do this, place within header key or value one or more template directives. Let's see the example below.
-import Headers from 'core/request/headers';
const query = {
type: 'platform',
typeValue: 'android'
};
const headers = new Headers(
{
'X-${type}': '${typeValue} scheme'
},
query
);
console.log(headers.get('X-${type}')); // 'android scheme'
console.log(headers.get('x-platform')); // 'android scheme'
// Notice, after applying values to templates, all used values are marked as non-enumerable
console.log(query.propertyIsEnumerable('type')); // false
console.log(query.propertyIsEnumerable('typeValue')); // false
-
-
-
- For backward compatibility with previous versions of V4Fire, the instance of the Headers class can be used as a simple dictionary.
-import Headers from 'core/request/headers';
const headers = new Headers({
'Content-Language': ['en', 'ru'],
'Cache-Control': 'no-cache'
});
console.log(headers['content-language']); // 'en, ru'
console.log(Object.keys(headers)); // ['content-language', 'cache-control']
-
-To make headers read-only, use Object.freeze.
import Headers from 'core/request/headers';
const headers = Object.freeze(new Headers({
'Content-Language': ['en', 'ru'],
'Cache-Control': 'no-cache'
}));
try {
headers.set('Cache-Control', 'no-store');
} catch (err) {
console.log(err);
}
console.log(headers['cache-control']); // 'no-cache'
-
-This module provides a bunch of helper functions to work with a request and its submodules.
-Truncates all static cache storage-s
-Generates a string cache key for the specified parameters and returns it
-request url
-Applies a query object for the specified string -(used keys are removed from the query)
-This module provides a class to create an iterable stream structure with a feature of buffering input values, -i.e. every added value is placed within an internal buffer till they are read.
-const
streamBuffer = new StreamBuffer(),
source = ['value1', 'value2', 'value3'];
setTimeout(function cb() {
// While the stream is open it's possible to add new values
streamBuffer.add(source.shift());
if (source.length > 0) {
setTimeout(cb, 15);
} else {
// Closing a stream interrupt the async loop and prevent adding new items
streamBuffer.close();
}
}, 15);
// Use for await...of statement to go through the stream
for await (const val of streamBuffer) {
// value1, value2, value3
console.log(val);
}
-
-It's possible to iterate through already added items synchronously.
-// The stream constructor can take an iterable object with initial values
const streamBuffer = new StreamBuffer(['value1', 'value2', 'value3']);
for (const item of streamBuffer) {
// value1, value2, value3
console.log(item);
}
-
-To destroy a stream and stop all iterators, use the destroy method.
const
streamBuffer = new StreamBuffer();
setTimeout(function cb() {
// Also, you can pass a reason to destroy
streamBuffer.destroy('The stream has been destroyed');
});
try {
for await (const _ of streamBuffer) {
console.log('Unreachable code');
}
} catch (err) {
// The stream has been destroyed
console.log(err);
}
// The stream is destroyed, and this value is never added
streamBuffer.add('item');
-
-This module provides a class to work with server response data. -The class' API is pretty similar to native the Response class -but has some extra functionality. The class doesn't implement native Response static methods.
- - -Because, the core/request module can use different engines, but not only fetch or XMLHttpRequest.
-These engines can have different peculiarities, so we need to create a new abstraction.
There are a few differences between these classes:
-body property is not a stream object. Instead, it contains raw response data used to initialize an instance.Response instance is an async iterable object. So you can use this feature to process the response as a stream.
-Notice, not every request engine can stream response.import request from 'core/request';
import fetchEngine from 'core/request/engines/fetch';
for await (const chunk of request('//movie', {engine: fetchEngine})) {
console.log(chunk.data, chunk.total, chunk.loaded);
}
-
-
-
- | EventName | -Description | -Payload description | -Payload | -
|---|---|---|---|
bodyUsed |
-The response body has been read via decode |
-- | -- | -
streamUsed |
-The response body has been read via an async iterator | -- | -- | -
With creation of a Response instance you can pass a bunch of options.
-export interface ResponseOptions {
url?: string;
redirected?: boolean;
type?: ResponseModeType;
/**
* Parent operation promise
*/
parent?: AbortablePromise;
/**
* A meta flag that indicates that the request is important: is usually used with decoders to indicate that
* the request needs to be executed as soon as possible
*/
important?: boolean;
status?: StatusCodes;
statusText?: string;
/**
* A list of status codes (or a single code) that match successful operation.
* Also, you can pass a range of codes.
*/
okStatuses?: OkStatuses;
/**
* Type of the response data
*/
responseType?: ResponseType;
/**
* Set of response headers
*/
headers?: RawHeaders;
/**
* A function or sequence of functions to decode a response body
*/
decoder?: WrappedDecoder | WrappedDecoders;
/**
* A function or sequence of functions to decode a response chunk when you are parsing the response in a stream form
*/
streamDecoder?: WrappedStreamDecoder | WrappedStreamDecoders;
/**
* Reviver function for `JSON.parse`
* @default `convertIfDate`
*/
jsonReviver?: JSONCb | false;
}
-
-
-
- True, if the response body is already read as a stream.
- - -A list of status codes (or a single code) that match successful operation. -Also, you can pass a range of codes.
- - -A list of response decoders.
- - -A list of response decoders to apply for chunks when you are parsing response in a stream form.
- - -A reviver function for JSON.parse.
Event emitter to broadcast response events.
-import request from 'core/request';
request('//foo.jpg')
.then(({response}) => {
response.emitter.once('bodyUsed', () => {
console.log('Body has been read');
});
return response.decode();
});
-
-
-
- Parses the response body and returns a promise with the result. -The operation result is memoized, and you can't parse the response as a stream after invoking this method.
-A way to parse data is based on the response Content-Type header or a passed responseType constructor option.
-Also, a sequence of decoders is applied to the parsed result if they are passed with a decodersconstructor option.
import request from 'core/request';
request('//foo.jpg')
.then(({response}) => response.decode())
.then((img) => console.log(img instanceof Blob));
request('//users', {decoders: [parseProtobuf, normalizeUsers], responseType: 'arrayBuffer'})
.then(({response}) => response.decode())
.then((users) => console.log(users));
-
-
-
- Parses the response body as a stream and yields chunks via an async iterator. -You can't parse the response as a whole data after invoking this method.
-A way to parse data chunks is based on the response Content-Type header or a passed responseTypeconstructor option.
-Also, a sequence of stream decoders is applied to the parsed chunk if they are passed with a streamDecoders constructor option.
import request from 'core/request';
import { streamArray } from 'core/json/stream';
request('//foo.jpg')
.then(async ({response}) => {
for await (const chunk of response.decodeStream()) {
console.log(chunk instanceof ArrayBuffer);
}
});
request('//users', {streamDecoders: [streamArray], responseType: 'json'})
.then(async ({response}) => {
for await (const user of response.decodeStream()) {
console.log(user);
}
});
-
-
-
- Parses the response data stream as a JSON tokens and yields them via an async iterator.
-import request from 'core/request';
import { streamArray } from 'core/json/stream';
request('//users', {streamDecoders: [streamArray]})
.then(async ({response}) => {
for await (const user of response.jsonStream()) {
console.log(user);
}
});
-
-
-
- Parses the response data stream as a text chunks and yields them via an async iterator.
-import request from 'core/request';
request('//users')
.then(async ({response}) => {
for await (const textFragment of response.textStream()) {
console.log(textFragment);
}
});
-
-
-
- Parses the response data stream as an ArrayBuffer chunks and yields them via an async iterator.
-import request from 'core/request';
request('//users')
.then(async ({response}) => {
for await (const chunkBuffer of response.stream()) {
console.log(chunkBuffer);
}
});
-
-
-
- Returns an iterator by the response body.
-Mind, when you parse response via iterator, you won't be able to use other parse methods, like json or text.
import request from 'core/request';
request('//users')
.then(async ({response}) => {
for await (const {loaded, total, data} of response) {
console.log(loaded, total, data);
}
});
-
-Status codes that cannot contain any content according to the HTTP standard
-This module provides a function to compare string versions by using semver strategy.
-import check from 'core/semver';
console.log(check('1.4.1', '1.5.2', '>')); // false
console.log(check('1', '1.5.2', '==')); // true
console.log(check('2.4.1', '2.4', '<=')); // true
console.log(check('2.4', '2.4.2', '^=')); // true
-
-
-
- --Note: -The module currently supports only a numeric comparison with x-ranges. Without
-beta,alphaorrcpostfixes.
== equal^= caret range~= tilda range> greater than< less than>= greater than or equal to<= less than or equal toCompares two strings with number versions (a
operation type
-This module provides a map of HTTP status codes.
-import StatusCodes from 'core/status-codes';
// 301
console.log(StatusCodes.MOVED_PERMANENTLY);
// 404
console.log(StatusCodes.NOT_FOUND);
-
-
-
- enum StatusCodes {
CONTINUE = 100,
SWITCHING_PROTOCOLS = 101,
OK = 200,
CREATED = 201,
ACCEPTED = 202,
NON_AUTHORITATIVE_INFORMATION = 203,
NO_CONTENT = 204,
RESET_CONTENT = 205,
PARTIAL_CONTENT = 206,
MULTI_STATUS = 207,
ALREADY_REPORTED = 208,
IM_USED = 226,
MULTIPLE_CHOICES = 300,
MOVED_PERMANENTLY = 301,
FOUND = 302,
SEE_OTHER = 303,
NOT_MODIFIED = 304,
USE_PROXY = 305,
SWITCH_PROXY = 306,
TEMPORARY_REDIRECT = 307,
PERMANENT_REDIRECT = 308,
BAD_REQUEST = 400,
UNAUTHORIZED = 401,
PAYMENT_REQUIRED = 402,
FORBIDDEN = 403,
NOT_FOUND = 404,
METHOD_NOT_ALLOWED = 405,
NOT_ACCEPTABLE = 406,
PROXY_AUTHENTICATION_REQUIRED = 407,
REQUEST_TIMEOUT = 408,
CONFLICT = 409,
GONE = 410,
LENGTH_REQUIRED = 411,
PRECONDITION_FAILED = 412,
REQUEST_ENTITY_TOO_LARGE = 413,
REQUEST_URI_TOO_LONG = 414,
UNSUPPORTED_MEDIA_TYPE = 415,
REQUESTED_RANGE_NOT_SATISFIABLE = 416,
EXPECTATION_FAILED = 417,
IM_A_TEAPOT = 418,
MISDIRECTED_REQUEST = 421,
UNPROCESSABLE_ENTITY = 422,
UPGRADE_REQUIRED = 426,
PRECONDITION_REQUIRED = 428,
LOCKED = 423,
FAILED_DEPENDENCY = 424,
TOO_MANY_REQUESTS = 429,
REQUEST_HEADER_FIELDS_TOO_LARGE = 431,
UNAVAILABLE_FOR_LEGAL_REASONS = 451,
INTERNAL_SERVER_ERROR = 500,
NOT_IMPLEMENTED = 501,
BAD_GATEWAY = 502,
SERVICE_UNAVAILABLE = 503,
GATEWAY_TIMEOUT = 504,
HTTP_VERSION_NOT_SUPPORTED = 505,
VARIANT_ALSO_NEGOTIATES = 506,
INSUFFICIENT_STORAGE = 507,
LOOP_DETECTED = 508,
NOT_EXTENDED = 510,
NETWORK_AUTHENTICATION_REQUIRED = 511
}
-
-Enum-like structure of status codes
-This module provides a function to create unique symbols in a more flexible way.
-import symbolGenerator from 'core/symbol';
// All symbols that produce from this constant will be automatically generated by the first touch.
// This mechanism is based on the JS Proxy API.
const
$$ = symbolGenerator();
// This code is similar to
// const hi = Symbol('hi');
// console.log(hi);
console.log($$.hi);
-
-Returns a factory for flexible creation of unique symbols by the first touch
-list of predefined fields (it can be useful to shim the Proxy API)
-This module provides a class wraps promise-like objects and adds to them some extra functionality, such as possibility of cancellation, etc.
-Mind that this module is deprecated and will be removed from the next major release of the library. You can use modules from core/promise/abortable instead of this.
-This module provides a bunch of functions to work with URL strings, such as parsing/serializing, concatenating groups of URLs to one, etc.
- - -Concatenates the specified parts of URL-s with correctly arranging of slashes and returns a new string.
-import { concatURLs } from 'core/url';
concatURLs('foo/baz', '/bar', 'bla') === 'foo/baz/bar/bla';
-
-
-
- import { fromQueryString, toQueryString } from 'core/url';
const data = {
foo: 1,
bar: true,
baz: [1, 2, 3],
ban: {a: 2}
};
toQueryString(data) === 'ban_a=2&bar=true&baz=1&baz=2&baz=3&foo=1';
// {foo: 1, bar: true, baz: [1, 2, 3], ban: {a: 2}}
fromQueryString(toQueryString(data), {separator: '_'});
-
-
-
- Creates a querystring from the specified data and returns it. The method can take additional options:
-interface FromQueryStringOptions {
/**
* If false, then the passed string won't be decoded by using `decodeURIComponent`
* @default `true`
*/
decode?: boolean;
/**
* If false, then all parsed values won't be converted from a string
*
* @default `true`
*
* @example
* ```js
* // {foo: '1'}
* fromQueryString('foo=1', {convert: false});
* ```
*/
convert?: boolean;
/**
* Separator for nested properties
*
* @example
* ```js
* // {foo: {bar: 1}}
* fromQueryString('foo_bar=1', {separator: '_'});
* ```
*/
separator?: string;
/**
* If true, then nested properties will be decoded by using `[]` syntax
*
* @default `false`
*
* @example
* ```js
* // {foo: [1], bar: {bla: 2}}
* fromQueryString('foo[]=1&bar[bla]=2', {arraySyntax: true});
* ```
*/
arraySyntax?: boolean;
}
-
-
-
- Creates a querystring from the specified data and returns it. The method can take additional options:
-interface ToQueryStringOptions {
/**
* If false, then the result string won't be encoded by using `encodeURIComponent`
* @default `true`
*/
encode?: boolean;
/**
* Separator for nested properties
*
* @default `'_'`
*
* @example
* ```js
* // foo.bar=1
* toQueryString({foo: {bar: 1}}, {separator: '.'});
* ```
*/
separator?: string;
/**
* If true, then nested properties will be encoded by using `[]` syntax
*
* @default `false`
*
* @example
* ```js
* // foo[]=1&bar[bla]=2
* toQueryString({foo: [1], bar: {bla: 2}}, {arraySyntax: true});
* ```
*/
arraySyntax?: boolean;
/**
* Filters values that shouldn't be serialized.
* By default, the function skip all values with null-s and empty strings.
*
* @param value
* @param key - property key
* @param path - accumulated property path `({a: {b: 1}} => 'a_b')`
*
* @example
* ```js
* // foo=1
* toQueryString({foo: 1, bar: {bla: 2}}, {paramsFilter: (el, key) => key !== 'bla'});
* ```
*/
paramsFilter?(value: unknown, key: string, path?: string): unknown;
}
-
-Creates a querystring from the specified data and returns it
-Creates a querystring from the specified data and returns it
-additional options
-Creates a dictionary from the specified querystring and returns it
-Creates a dictionary from the specified querystring and returns it
-additional options
-Creates a dictionary from the specified querystring and returns it. -This overload doesn't convert key values from a string.
-additional options
-Creates a querystring from the specified data and returns it
-Creates a querystring from the specified data and returns it
-additional options
-This module provides API to generate, parse and serialize UUID strings and binary sequences.
- - -import { generate, serialize, parse } from 'core/uuid';
// Generates UUID v4
console.log(generate());
const
uuid = new Uint8Array([174, 42, 253, 26, 185, 60, 17, 234, 179, 222, 2, 66, 172, 19, 0, 4]);
console.log(parse('ae2afd1a-b93c-11ea-b3de-0242ac130004')) // = uuid
console.log(serialize(uuid)) // 'ae2afd1a-b93c-11ea-b3de-0242ac130004'
-
-
-
- Generates a UUIDv4 buffer and returns it.
- - -Converts the specified binary UUID to a string and returns it.
- - -Converts the specified UUID string to a binary sequence and returns it.
-Generates a UUIDv4 buffer and returns it
-Converts the specified UUID string to a binary sequence and returns it
-Converts the specified binary UUID to a string and returns it
-This module provides a bunch of helper functions to work with XML documents.
- - -Converts the specified XML node to a DATA:URI string.
import { toDataURI } from 'core/xml';
import { getDataTypeFromURI } from 'core/mime-type';
const node = document.createElement('foo');
node.innerHTML = 'hello';
// "data:image/svg+xml;%3Cfoo xmlns='http://www.w3.org/1999/xhtml'%3Ehello%3C/foo%3E"
console.log(toDataURI(node));
// document
console.log(getDataTypeFromURI(toDataURI(node)));
-
-Converts the specified XML node to a DATA:URI string
-This module provides language pack maps for internationalizing the application. -The structure of the language map consists of several levels:
-The symbolic name of the language or locale for which translations are provided.
-export default {
'ru': { /* ... */ },
'en-gb': { /* ... */ },
'en-us': { /* ... */ }
};
-
-Namespace for language keys (hereinafter "keyset"). Keyset allows you to share the same keys in different contexts. -For example, the key "Next" may have a different value in different components of the application, therefore, -we can use the name of the component as a keyset value.
-export default {
ru: {
'b-reg-form': {
Next: 'Далее'
},
'b-queue': {
Next: 'Следующий'
}
}
};
-
-Keys and translations. The key can be any symbolic sequence. The key values will be replaced with the corresponding translation. -If there is no translation for the given locale or keyset, then the key itself will be displayed.
-Some translations may include special constructions in their text, which will be replaced by other meanings during translation.
-To use such variables, it is enough to place them inside the {variableName} construct, and pass the values for
-translation as an additional parameter to the i18n function.
export default {
en: {
"my-component": {
"my name is {name}": "my name is {name}",
"apple": "apple"
}
}
};
-
-i18n('my-component')('My name is {name}', {name: 'John'});
-
-
-
- Some keys may have multiple translations depending on some numeric value. For example, "1 apple" or "5 apples".
-To specify such translations, a special macro {count} is used, and translations are specified as a tuple [one, some, many, none].
export default {
ru: {
"my-component": {
"time": "время",
"{count} product": [
"{count} продукт",
"{count} продукта",
"{count} продуктов",
"{count} продуктов"
]
}
},
en: {
"my-component": {
"{count} product": [
"{count} product",
"{count} products",
"{count} products",
"{count} products"
]
}
}
};
-
-i18n('my-component', 'ru')('{count} product', {count: 10});
-
-
Class to control asynchronous operations
-