@monterosa/sdk-util 0.17.1-rc.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.esm5.js","sources":["../src/emitter.ts","../src/delay.ts","../src/memoize-promise.ts","../src/global.ts","../src/storage.ts","../src/error.ts","../src/throttle.ts","../src/time.ts"],"sourcesContent":["/**\n * @license\n * subscribe.ts\n * util\n *\n * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2022-02-22\n * Copyright © 2022 Monterosa. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n */\n\nimport mitt, { Emitter as MittEmitter, Handler as MittHandler } from 'mitt';\n\ntype Handler = (...args: any[]) => void;\n\nexport class Emitter {\n private readonly emitter: MittEmitter<Record<string, any>>;\n private readonly handlers = new Map<Handler, MittHandler>();\n\n constructor() {\n this.emitter = mitt<Record<string, any>>();\n }\n\n on(event: string, handler: Handler): Unsubscribe {\n const mittHandler: MittHandler = (args) => {\n handler(...(Array.isArray(args) ? args : [args]));\n };\n\n this.handlers.set(handler, mittHandler);\n this.emitter.on(event, mittHandler);\n\n return () => this.off(event, handler);\n }\n\n off(event: string, handler?: Handler): void {\n if (handler === undefined) {\n this.emitter.off(event);\n return;\n }\n\n const mittHandler = this.handlers.get(handler);\n\n if (mittHandler) {\n this.emitter.off(event, mittHandler);\n this.handlers.delete(handler);\n }\n }\n\n emit(event: string, ...args: any[]): void {\n this.emitter.emit(event, args);\n }\n\n once(event: string, handler: Handler): Unsubscribe {\n const mittHandler: MittHandler = (args) => {\n handler(...(Array.isArray(args) ? args : [args]));\n\n this.off(event, handler);\n };\n\n this.handlers.set(handler, mittHandler);\n this.emitter.on(event, mittHandler);\n\n return () => this.off(event, handler);\n }\n}\n\n/**\n * The unsubscribe function. When it is called, the previously set event\n * listener is removed. It is returned by every observer functions\n *\n * @example\n * ```typescript\n * const unsubscribe: Unsubscribe = onElementPublished((element) => {\n * console.log('Element published', element);\n * });\n *\n * unsubscribe();\n * ```\n */\nexport interface Unsubscribe {\n (): void;\n}\n\n/**\n * @internal\n */\nexport interface Subscribe {\n (\n emitter: Emitter,\n event: string,\n callback: (...args: any[]) => void,\n ): Unsubscribe;\n}\n\n/**\n * @internal\n */\nexport const subscribe: Subscribe = (emitter, event, callback) => {\n emitter.on(event, callback);\n\n return () => emitter.off(event, callback);\n};\n","/**\n * @license\n * delay.ts\n * util\n *\n * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2022-03-24\n * Copyright © 2022 Monterosa. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n */\n\n/**\n * @internal\n */\nexport const delay = async (timeout: number): Promise<void> => {\n await new Promise((resolve) => setTimeout(resolve, timeout));\n};\n","/**\n * @license\n * memoize-promise.ts\n * util\n *\n * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2022-09-20\n * Copyright © 2022 Monterosa. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n */\n\n/**\n * Creates a function that memoizes the result of `func`.\n *\n * @internal\n *\n * @param func - A function that returns a promise. The results of its work will be memoized.\n * @param resolver - A function that determines the cache key.\n * @param config - A configuration object with the following optional properties:\n * `clearOnResolve` - Deletes memoized result upon promise resolve. Defaults to `false`.\n * `clearOnReject` - Deletes memoized result upon promise reject. Defaults to `true`.\n */\n\nexport const memoizePromise = <T>(\n func: (...args: any[]) => Promise<T>,\n resolver: (...args: any[]) => any,\n config: {\n clearOnResolve?: boolean;\n clearOnReject?: boolean;\n } = {},\n): ((...args: any[]) => Promise<T>) => {\n const clearOnResolve = config.clearOnResolve ?? false;\n const clearOnReject = config.clearOnReject ?? true;\n\n const cache: Map<any, Promise<T>> = new Map();\n\n const memoized = (...args: any[]) => {\n const key = resolver(...args);\n\n if (cache.has(key)) {\n return cache.get(key) as Promise<T>;\n }\n\n const promise = func(...args);\n\n cache.set(key, promise);\n\n promise.then(() => clearOnResolve && cache.delete(key));\n promise.catch(() => clearOnReject && cache.delete(key));\n\n return promise;\n };\n\n memoized.cache = cache;\n\n return memoized;\n};\n","/**\n * @license\n * global.ts\n * util\n *\n * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2022-04-21\n * Copyright © 2022 Monterosa. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n */\n\n/* eslint no-restricted-globals: \"off\" */\n\n/**\n * Global object polyfill.\n * Based on MDN article: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis\n *\n * @internal\n *\n * @returns typeof globalThis\n */\nexport function getGlobal(): typeof globalThis {\n if (typeof self !== 'undefined') {\n return self;\n }\n\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n }\n\n if (typeof window !== 'undefined') {\n return window;\n }\n\n if (typeof global !== 'undefined') {\n return global;\n }\n\n throw new Error('Unable to locate global object.');\n}\n","/**\n * @license\n * storage.ts\n * util\n *\n * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2022-04-21\n * Copyright © 2022 Monterosa. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n */\n\nimport { getGlobal } from './global';\n\nconst PREFIX = 'monterosa_sdk_';\n\nconst BAIT = 'bait';\n\nconst globals = getGlobal();\n\n/**\n * @internal\n */\nexport const getKey = (name: string) => `${PREFIX}${name}`;\n\n/**\n * @internal\n */\nexport function getItem(key: string): string | null {\n return globals.localStorage.getItem(getKey(key));\n}\n\n/**\n * @internal\n */\nexport function setItem(key: string, value: string): void {\n return globals.localStorage.setItem(getKey(key), value);\n}\n\n/**\n * @internal\n */\nexport function removeItem(key: string): void {\n return globals.localStorage.removeItem(getKey(key));\n}\n\n/**\n * @internal\n */\nexport function clear(): void {\n return globals.localStorage.clear();\n}\n\n/**\n * Checks locastorage availability.\n * Based on MDN article: https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API\n * and Paul Irish gists: https://gist.github.com/paulirish/5558557\n *\n * @internal\n *\n * @returns boolean\n */\nexport function checkAvailability() {\n try {\n setItem(BAIT, BAIT);\n getItem(BAIT);\n removeItem(BAIT);\n\n return true;\n } catch (e) {\n return false;\n }\n}\n","/**\n * @license\n * error.ts\n * util\n *\n * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2022-03-31\n * Copyright © 2022 Monterosa. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n */\n\n/* eslint max-classes-per-file: [\"error\", 2] */\n\n/**\n * MonterosaError extends the standard JavaScript `Error` object. It has\n * an error code so that user can identify the error. Also it has it's own\n * specific `name` \"MonterosaError\"\n */\nexport class MonterosaError extends Error {\n /**\n * The name property represents a name for the type of error.\n */\n readonly name = 'MonterosaError';\n\n /**\n * Error code string\n */\n readonly code: string;\n\n /**\n * @param code - Error code string\n * @param message - A descriptive message for the error\n */\n constructor(code: string, message: string) {\n super(message);\n\n this.code = code;\n\n // Fix For ES5\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, MonterosaError.prototype);\n }\n}\n\ntype ErrorMap<ErrorCode extends string> = {\n readonly [K in ErrorCode]: (...rest: any[]) => string;\n};\n\n/**\n * @internal\n */\nexport function createError<ErrorCode extends string>(\n code: ErrorCode,\n messages: ErrorMap<ErrorCode>,\n ...params: any[]\n) {\n const message = messages[code](...params);\n\n return new MonterosaError(code, message);\n}\n","/**\n * @license\n * throttle.ts\n * util\n *\n * Created by Josep Rodriguez <josep.rodriguez@monterosa.co.uk> on 2022-07-13\n * Copyright © 2022 Monterosa. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n */\n\n/* eslint-disable */\n// @ts-nocheck\n\n/**\n * lodash (Custom Build) <https://lodash.com/>\n * Build: `lodash modularize exports=\"npm\" -o ./`\n * Copyright jQuery Foundation and other contributors <https://jquery.org/>\n * Released under MIT license <https://lodash.com/license>\n * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>\n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\n\n/** Used as the `TypeError` message for \"Functions\" methods. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/** Used as references for various `Number` constants. */\nvar NAN = 0 / 0;\n\n/** `Object#toString` result references. */\nvar symbolTag = '[object Symbol]';\n\n/** Used to match leading and trailing whitespace. */\nvar reTrim = /^\\s+|\\s+$/g;\n\n/** Used to detect bad signed hexadecimal string values. */\nvar reIsBadHex = /^[-+]0x[0-9a-f]+$/i;\n\n/** Used to detect binary string values. */\nvar reIsBinary = /^0b[01]+$/i;\n\n/** Used to detect octal string values. */\nvar reIsOctal = /^0o[0-7]+$/i;\n\n/** Built-in method references without a dependency on `root`. */\nvar freeParseInt = parseInt;\n\n/** Detect free variable `global` from Node.js. */\nvar freeGlobal =\n typeof global == 'object' && global && global.Object === Object && global;\n\n/** Detect free variable `self`. */\nvar freeSelf =\n typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar objectToString = objectProto.toString;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max,\n nativeMin = Math.min;\n\n/**\n * Gets the timestamp of the number of milliseconds that have elapsed since\n * the Unix epoch (1 January 1970 00:00:00 UTC).\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Date\n * @returns {number} Returns the timestamp.\n * @example\n *\n * _.defer(function(stamp) {\n * console.log(_.now() - stamp);\n * }, _.now());\n * // => Logs the number of milliseconds it took for the deferred invocation.\n */\nvar now = function () {\n return root.Date.now();\n};\n\n/**\n * Creates a debounced function that delays invoking `func` until after `wait`\n * milliseconds have elapsed since the last time the debounced function was\n * invoked. The debounced function comes with a `cancel` method to cancel\n * delayed `func` invocations and a `flush` method to immediately invoke them.\n * Provide `options` to indicate whether `func` should be invoked on the\n * leading and/or trailing edge of the `wait` timeout. The `func` is invoked\n * with the last arguments provided to the debounced function. Subsequent\n * calls to the debounced function return the result of the last `func`\n * invocation.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is\n * invoked on the trailing edge of the timeout only if the debounced function\n * is invoked more than once during the `wait` timeout.\n *\n * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `_.debounce` and `_.throttle`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to debounce.\n * @param {number} [wait=0] The number of milliseconds to delay.\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=false]\n * Specify invoking on the leading edge of the timeout.\n * @param {number} [options.maxWait]\n * The maximum time `func` is allowed to be delayed before it's invoked.\n * @param {boolean} [options.trailing=true]\n * Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new debounced function.\n * @example\n *\n * // Avoid costly calculations while the window size is in flux.\n * jQuery(window).on('resize', _.debounce(calculateLayout, 150));\n *\n * // Invoke `sendMail` when clicked, debouncing subsequent calls.\n * jQuery(element).on('click', _.debounce(sendMail, 300, {\n * 'leading': true,\n * 'trailing': false\n * }));\n *\n * // Ensure `batchLog` is invoked once after 1 second of debounced calls.\n * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });\n * var source = new EventSource('/stream');\n * jQuery(source).on('message', debounced);\n *\n * // Cancel the trailing debounced invocation.\n * jQuery(window).on('popstate', debounced.cancel);\n */\nfunction debounce(func, wait, options) {\n var lastArgs,\n lastThis,\n maxWait,\n result,\n timerId,\n lastCallTime,\n lastInvokeTime = 0,\n leading = false,\n maxing = false,\n trailing = true;\n\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n wait = toNumber(wait) || 0;\n if (isObject(options)) {\n leading = !!options.leading;\n maxing = 'maxWait' in options;\n maxWait = maxing\n ? nativeMax(toNumber(options.maxWait) || 0, wait)\n : maxWait;\n trailing = 'trailing' in options ? !!options.trailing : trailing;\n }\n\n function invokeFunc(time) {\n var args = lastArgs,\n thisArg = lastThis;\n\n lastArgs = lastThis = undefined;\n lastInvokeTime = time;\n result = func.apply(thisArg, args);\n return result;\n }\n\n function leadingEdge(time) {\n // Reset any `maxWait` timer.\n lastInvokeTime = time;\n // Start the timer for the trailing edge.\n timerId = setTimeout(timerExpired, wait);\n // Invoke the leading edge.\n return leading ? invokeFunc(time) : result;\n }\n\n function remainingWait(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime,\n result = wait - timeSinceLastCall;\n\n return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result;\n }\n\n function shouldInvoke(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime;\n\n // Either this is the first call, activity has stopped and we're at the\n // trailing edge, the system time has gone backwards and we're treating\n // it as the trailing edge, or we've hit the `maxWait` limit.\n return (\n lastCallTime === undefined ||\n timeSinceLastCall >= wait ||\n timeSinceLastCall < 0 ||\n (maxing && timeSinceLastInvoke >= maxWait)\n );\n }\n\n function timerExpired() {\n var time = now();\n if (shouldInvoke(time)) {\n return trailingEdge(time);\n }\n // Restart the timer.\n timerId = setTimeout(timerExpired, remainingWait(time));\n }\n\n function trailingEdge(time) {\n timerId = undefined;\n\n // Only invoke if we have `lastArgs` which means `func` has been\n // debounced at least once.\n if (trailing && lastArgs) {\n return invokeFunc(time);\n }\n lastArgs = lastThis = undefined;\n return result;\n }\n\n function cancel() {\n if (timerId !== undefined) {\n clearTimeout(timerId);\n }\n lastInvokeTime = 0;\n lastArgs = lastCallTime = lastThis = timerId = undefined;\n }\n\n function flush() {\n return timerId === undefined ? result : trailingEdge(now());\n }\n\n function debounced() {\n var time = now(),\n isInvoking = shouldInvoke(time);\n\n lastArgs = arguments;\n lastThis = this;\n lastCallTime = time;\n\n if (isInvoking) {\n if (timerId === undefined) {\n return leadingEdge(lastCallTime);\n }\n if (maxing) {\n // Handle invocations in a tight loop.\n timerId = setTimeout(timerExpired, wait);\n return invokeFunc(lastCallTime);\n }\n }\n if (timerId === undefined) {\n timerId = setTimeout(timerExpired, wait);\n }\n return result;\n }\n debounced.cancel = cancel;\n debounced.flush = flush;\n return debounced;\n}\n\n/**\n * Creates a throttled function that only invokes `func` at most once per\n * every `wait` milliseconds. The throttled function comes with a `cancel`\n * method to cancel delayed `func` invocations and a `flush` method to\n * immediately invoke them. Provide `options` to indicate whether `func`\n * should be invoked on the leading and/or trailing edge of the `wait`\n * timeout. The `func` is invoked with the last arguments provided to the\n * throttled function. Subsequent calls to the throttled function return the\n * result of the last `func` invocation.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is\n * invoked on the trailing edge of the timeout only if the throttled function\n * is invoked more than once during the `wait` timeout.\n *\n * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `_.throttle` and `_.debounce`.\n *\n * @internal\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to throttle.\n * @param {number} [wait=0] The number of milliseconds to throttle invocations to.\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=true]\n * Specify invoking on the leading edge of the timeout.\n * @param {boolean} [options.trailing=true]\n * Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new throttled function.\n * @example\n *\n * // Avoid excessively updating the position while scrolling.\n * jQuery(window).on('scroll', _.throttle(updatePosition, 100));\n *\n * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.\n * var throttled = _.throttle(renewToken, 300000, { 'trailing': false });\n * jQuery(element).on('click', throttled);\n *\n * // Cancel the trailing throttled invocation.\n * jQuery(window).on('popstate', throttled.cancel);\n */\nexport function throttle(func, wait, options) {\n var leading = true,\n trailing = true;\n\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n if (isObject(options)) {\n leading = 'leading' in options ? !!options.leading : leading;\n trailing = 'trailing' in options ? !!options.trailing : trailing;\n }\n return debounce(func, wait, {\n leading: leading,\n maxWait: wait,\n trailing: trailing,\n });\n}\n\n/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return !!value && (type == 'object' || type == 'function');\n}\n\n/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return !!value && typeof value == 'object';\n}\n\n/**\n * Checks if `value` is classified as a `Symbol` primitive or object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n * @example\n *\n * _.isSymbol(Symbol.iterator);\n * // => true\n *\n * _.isSymbol('abc');\n * // => false\n */\nfunction isSymbol(value) {\n return (\n typeof value == 'symbol' ||\n (isObjectLike(value) && objectToString.call(value) == symbolTag)\n );\n}\n\n/**\n * Converts `value` to a number.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to process.\n * @returns {number} Returns the number.\n * @example\n *\n * _.toNumber(3.2);\n * // => 3.2\n *\n * _.toNumber(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toNumber(Infinity);\n * // => Infinity\n *\n * _.toNumber('3.2');\n * // => 3.2\n */\nfunction toNumber(value) {\n if (typeof value == 'number') {\n return value;\n }\n if (isSymbol(value)) {\n return NAN;\n }\n if (isObject(value)) {\n var other = typeof value.valueOf == 'function' ? value.valueOf() : value;\n value = isObject(other) ? other + '' : other;\n }\n if (typeof value != 'string') {\n return value === 0 ? value : +value;\n }\n value = value.replace(reTrim, '');\n var isBinary = reIsBinary.test(value);\n return isBinary || reIsOctal.test(value)\n ? freeParseInt(value.slice(2), isBinary ? 2 : 8)\n : reIsBadHex.test(value)\n ? NAN\n : +value;\n}\n","/**\n * @license\n * time.ts\n * util\n *\n * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2025-03-24\n * Copyright © 2025 Monterosa. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n */\n\n/**\n * Time service that maintains current timestamp.\n *\n * Timestamp is set either:\n * - initially with the local timestamp `Date.now()` when there is yet\n * communication with Enmasse server yet\n * - later with the accurate low-latency timestamp that comes in Enmasse\n * message handshake\n *\n * Thereafter the timestamp is maintained by `tick()` function and can be\n * retrieved in two ways:\n *\n * - subscribing to an event using `onTick(callback: () => void)` function\n * that pushes notification every second with the current timestamp\n * - or pulling data directly using function `now()`\n */\n\nimport { Emitter, subscribe, Unsubscribe } from './emitter';\n\nconst emitter = new Emitter();\n\nlet serverTimestamp: number = 0;\nlet lastTickTimestamp: number = 0;\nlet tickTimeoutId: ReturnType<typeof setTimeout>;\n\n/**\n * Returns local timestamp in seconds\n */\nfunction getCurrentTimestamp(): number {\n return Date.now() / 1000;\n}\n\n/**\n * Normalizes the timestamp to reduce fluctuations due to `setTimeout` delays.\n * Ensures the fractional part is around 0.5 to avoid skipping a second.\n *\n * Returns half-second timestamp. It is used to be sure that timestamp will not\n * fluctuate more than in 1 second after each tick due to longer delays.\n * https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#reasons_for_delays_longer_than_specified\n *\n * For example if the initial timestamp has a fractional part 0.9999 then with\n * the setTimeout (tick) longer than specified we might jump over a one second.\n * Lets imaging setTimeout took 1.0002 second, then our timestamp will be 2.0001.\n * Thats why we are trying to keep fractional part in the middle of the second.\n */\nfunction getMiddleTimestamp(timestamp: number): number {\n return Math.floor(timestamp) + 0.5;\n}\n\n/**\n * Calculates the delay for the next tick to keep timestamps stable.\n */\nfunction calculateNextTickDelay(): number {\n const expectedNextTick = getMiddleTimestamp(serverTimestamp) + 1;\n\n return (expectedNextTick - serverTimestamp) * 1000;\n}\n\n/**\n * Main function that maintains current timestamp\n */\nexport function tick() {\n clearTimeout(tickTimeoutId);\n\n const currentTimestamp = getCurrentTimestamp();\n const timeSinceLastTick = currentTimestamp - lastTickTimestamp;\n\n serverTimestamp += timeSinceLastTick;\n lastTickTimestamp = currentTimestamp;\n\n tickTimeoutId = setTimeout(tick, calculateNextTickDelay());\n\n emitter.emit('tick', serverTimestamp);\n}\n\n/**\n * @internal\n *\n * Sets or updates current timestamp\n *\n * @param timestamp - Current timestamp in seconds\n */\nexport function setTimestamp(timestamp: number): void {\n lastTickTimestamp = getCurrentTimestamp();\n serverTimestamp = getMiddleTimestamp(timestamp);\n}\n\n/**\n * Returns current timestamp that is preserved by `tick()` function\n *\n * @returns Current timestamp in seconds\n */\nexport function now(): number {\n return Math.floor(serverTimestamp);\n}\n\n/**\n * Subscribes listener to the timestamp increment\n *\n * @param callback - A handler that executes when the timestamp is incremented\n *\n * @returns A function that unsubscribes the listener\n */\nexport function onTick(callback: (timestamp: number) => void): Unsubscribe {\n return subscribe(emitter, 'tick', callback);\n}\n\n// Initially timestamp is set based on a local date\n// Later on it can be overriden outside at any moment\n// in our case it is populated with the server timestamp\n// which comes from Enmasse session handshake message\nsetTimestamp(getCurrentTimestamp());\n\n// Kicking in timestamp maintaining\ntick();\n"],"names":["now"],"mappings":";;AAAA;;;;;;;;;;;IAmBE;QAFiB,aAAQ,GAAG,IAAI,GAAG,EAAwB,CAAC;QAG1D,IAAI,CAAC,OAAO,GAAG,IAAI,EAAuB,CAAC;KAC5C;IAED,oBAAE,GAAF,UAAG,KAAa,EAAE,OAAgB;QAAlC,iBASC;QARC,IAAM,WAAW,GAAgB,UAAC,IAAI;YACpC,OAAO,gBAAK,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,GAAG;SACnD,CAAC;QAEF,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC;QACxC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,WAAW,CAAC,CAAC;QAEpC,OAAO,cAAM,OAAA,KAAI,CAAC,GAAG,CAAC,KAAK,EAAE,OAAO,CAAC,GAAA,CAAC;KACvC;IAED,qBAAG,GAAH,UAAI,KAAa,EAAE,OAAiB;QAClC,IAAI,OAAO,KAAK,SAAS,EAAE;YACzB,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;YACxB,OAAO;SACR;QAED,IAAM,WAAW,GAAG,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QAE/C,IAAI,WAAW,EAAE;YACf,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,WAAW,CAAC,CAAC;YACrC,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;SAC/B;KACF;IAED,sBAAI,GAAJ,UAAK,KAAa;QAAE,cAAc;aAAd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BAAgB,GAAG,kBAAkB,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC;IAEjE,OAAO,CAAC,gBAAgB,GAAG,eAAe,IAAI,IAAI,CAAC;AACrD,CAAC;AAED;;;SAGgB,IAAI;IAClB,YAAY,CAAC,aAAa,CAAC,CAAC;IAE5B,IAAM,gBAAgB,GAAG,mBAAmB,EAAE,CAAC;IAC/C,IAAM,iBAAiB,GAAG,gBAAgB,GAAG,iBAAiB,CAAC;IAE/D,eAAe,IAAI,iBAAiB,CAAC;IACrC,iBAAiB,GAAG,gBAAgB,CAAC;IAErC,aAAa,GAAG,UAAU,CAAC,IAAI,EAAE,sBAAsB,EAAE,CAAC,CAAC;IAE3D,OAAO,CAAC,IAAI,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC;AACxC,CAAC;AAED;;;;;;;SAOgB,YAAY,CAAC,SAAiB;IAC5C,iBAAiB,GAAG,mBAAmB,EAAE,CAAC;IAC1C,eAAe,GAAG,kBAAkB,CAAC,SAAS,CAAC,CAAC;AAClD,CAAC;AAED;;;;;SAKgB,GAAG;IACjB,OAAO,IAAI,CAAC,KAAK,CAAC,eAAe,CAAC,CAAC;AACrC,CAAC;AAED;;;;;;;SAOgB,MAAM,CAAC,QAAqC;IAC1D,OAAO,SAAS,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC;AAC9C,CAAC;AAED;AACA;AACA;AACA;AACA,YAAY,CAAC,mBAAmB,EAAE,CAAC,CAAC;AAEpC;AACA,IAAI,EAAE;;;;"}
@@ -0,0 +1,25 @@
1
+ /**
2
+ * @license
3
+ * memoize-promise.ts
4
+ * util
5
+ *
6
+ * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2022-09-20
7
+ * Copyright © 2022 Monterosa. All rights reserved.
8
+ *
9
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
10
+ */
11
+ /**
12
+ * Creates a function that memoizes the result of `func`.
13
+ *
14
+ * @internal
15
+ *
16
+ * @param func - A function that returns a promise. The results of its work will be memoized.
17
+ * @param resolver - A function that determines the cache key.
18
+ * @param config - A configuration object with the following optional properties:
19
+ * `clearOnResolve` - Deletes memoized result upon promise resolve. Defaults to `false`.
20
+ * `clearOnReject` - Deletes memoized result upon promise reject. Defaults to `true`.
21
+ */
22
+ export declare const memoizePromise: <T>(func: (...args: any[]) => Promise<T>, resolver: (...args: any[]) => any, config?: {
23
+ clearOnResolve?: boolean | undefined;
24
+ clearOnReject?: boolean | undefined;
25
+ }) => (...args: any[]) => Promise<T>;
@@ -0,0 +1,40 @@
1
+ /**
2
+ * @license
3
+ * storage.ts
4
+ * util
5
+ *
6
+ * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2022-04-21
7
+ * Copyright © 2022 Monterosa. All rights reserved.
8
+ *
9
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
10
+ */
11
+ /**
12
+ * @internal
13
+ */
14
+ export declare const getKey: (name: string) => string;
15
+ /**
16
+ * @internal
17
+ */
18
+ export declare function getItem(key: string): string | null;
19
+ /**
20
+ * @internal
21
+ */
22
+ export declare function setItem(key: string, value: string): void;
23
+ /**
24
+ * @internal
25
+ */
26
+ export declare function removeItem(key: string): void;
27
+ /**
28
+ * @internal
29
+ */
30
+ export declare function clear(): void;
31
+ /**
32
+ * Checks locastorage availability.
33
+ * Based on MDN article: https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API
34
+ * and Paul Irish gists: https://gist.github.com/paulirish/5558557
35
+ *
36
+ * @internal
37
+ *
38
+ * @returns boolean
39
+ */
40
+ export declare function checkAvailability(): boolean;
@@ -0,0 +1,61 @@
1
+ /**
2
+ * @license
3
+ * throttle.ts
4
+ * util
5
+ *
6
+ * Created by Josep Rodriguez <josep.rodriguez@monterosa.co.uk> on 2022-07-13
7
+ * Copyright © 2022 Monterosa. All rights reserved.
8
+ *
9
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
10
+ */
11
+ /**
12
+ * Creates a throttled function that only invokes `func` at most once per
13
+ * every `wait` milliseconds. The throttled function comes with a `cancel`
14
+ * method to cancel delayed `func` invocations and a `flush` method to
15
+ * immediately invoke them. Provide `options` to indicate whether `func`
16
+ * should be invoked on the leading and/or trailing edge of the `wait`
17
+ * timeout. The `func` is invoked with the last arguments provided to the
18
+ * throttled function. Subsequent calls to the throttled function return the
19
+ * result of the last `func` invocation.
20
+ *
21
+ * **Note:** If `leading` and `trailing` options are `true`, `func` is
22
+ * invoked on the trailing edge of the timeout only if the throttled function
23
+ * is invoked more than once during the `wait` timeout.
24
+ *
25
+ * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
26
+ * until to the next tick, similar to `setTimeout` with a timeout of `0`.
27
+ *
28
+ * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
29
+ * for details over the differences between `_.throttle` and `_.debounce`.
30
+ *
31
+ * @internal
32
+ *
33
+ * @static
34
+ * @memberOf _
35
+ * @since 0.1.0
36
+ * @category Function
37
+ * @param {Function} func The function to throttle.
38
+ * @param {number} [wait=0] The number of milliseconds to throttle invocations to.
39
+ * @param {Object} [options={}] The options object.
40
+ * @param {boolean} [options.leading=true]
41
+ * Specify invoking on the leading edge of the timeout.
42
+ * @param {boolean} [options.trailing=true]
43
+ * Specify invoking on the trailing edge of the timeout.
44
+ * @returns {Function} Returns the new throttled function.
45
+ * @example
46
+ *
47
+ * // Avoid excessively updating the position while scrolling.
48
+ * jQuery(window).on('scroll', _.throttle(updatePosition, 100));
49
+ *
50
+ * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
51
+ * var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
52
+ * jQuery(element).on('click', throttled);
53
+ *
54
+ * // Cancel the trailing throttled invocation.
55
+ * jQuery(window).on('popstate', throttled.cancel);
56
+ */
57
+ export declare function throttle(func: any, wait: any, options: any): {
58
+ (): any;
59
+ cancel: () => void;
60
+ flush: () => any;
61
+ };
package/dist/time.d.ts ADDED
@@ -0,0 +1,53 @@
1
+ /**
2
+ * @license
3
+ * time.ts
4
+ * util
5
+ *
6
+ * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2025-03-24
7
+ * Copyright © 2025 Monterosa. All rights reserved.
8
+ *
9
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
10
+ */
11
+ /**
12
+ * Time service that maintains current timestamp.
13
+ *
14
+ * Timestamp is set either:
15
+ * - initially with the local timestamp `Date.now()` when there is yet
16
+ * communication with Enmasse server yet
17
+ * - later with the accurate low-latency timestamp that comes in Enmasse
18
+ * message handshake
19
+ *
20
+ * Thereafter the timestamp is maintained by `tick()` function and can be
21
+ * retrieved in two ways:
22
+ *
23
+ * - subscribing to an event using `onTick(callback: () => void)` function
24
+ * that pushes notification every second with the current timestamp
25
+ * - or pulling data directly using function `now()`
26
+ */
27
+ import { Unsubscribe } from './emitter';
28
+ /**
29
+ * Main function that maintains current timestamp
30
+ */
31
+ export declare function tick(): void;
32
+ /**
33
+ * @internal
34
+ *
35
+ * Sets or updates current timestamp
36
+ *
37
+ * @param timestamp - Current timestamp in seconds
38
+ */
39
+ export declare function setTimestamp(timestamp: number): void;
40
+ /**
41
+ * Returns current timestamp that is preserved by `tick()` function
42
+ *
43
+ * @returns Current timestamp in seconds
44
+ */
45
+ export declare function now(): number;
46
+ /**
47
+ * Subscribes listener to the timestamp increment
48
+ *
49
+ * @param callback - A handler that executes when the timestamp is incremented
50
+ *
51
+ * @returns A function that unsubscribes the listener
52
+ */
53
+ export declare function onTick(callback: (timestamp: number) => void): Unsubscribe;
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "@monterosa/sdk-util",
3
+ "version": "0.17.1-rc.6",
4
+ "description": "Monterosa JS SDK / Utils",
5
+ "author": "Monterosa <hello@monterosa.co.uk> (https://www.monterosa.co/)",
6
+ "main": "dist/index.cjs.js",
7
+ "browser": "dist/index.esm2017.js",
8
+ "module": "dist/index.esm2017.js",
9
+ "esm5": "dist/index.esm5.js",
10
+ "types": "./dist/index.d.ts",
11
+ "files": [
12
+ "dist"
13
+ ],
14
+ "scripts": {
15
+ "dev": "rollup -c -w",
16
+ "build": "rollup -c",
17
+ "test": "jest --color",
18
+ "test:watch": "jest --color --watchAll",
19
+ "test:ci": "jest --color --ci --reporters=jest-junit --coverage",
20
+ "api-report": "api-extractor run --local --verbose"
21
+ },
22
+ "keywords": [],
23
+ "license": "MIT",
24
+ "dependencies": {
25
+ "mitt": "^3.0.1"
26
+ },
27
+ "devDependencies": {
28
+ "@rollup/plugin-json": "^4.1.0",
29
+ "@types/jest": "^27.0.1",
30
+ "jest": "^27.1.0",
31
+ "jest-fetch-mock": "^3.0.3",
32
+ "jest-junit": "^13.0.0",
33
+ "rollup": "^2.57.0",
34
+ "rollup-plugin-typescript2": "^0.30.0",
35
+ "ts-jest": "^27.0.5",
36
+ "tslib": "^2.3.0",
37
+ "typescript": "^4.4.2"
38
+ },
39
+ "publishConfig": {
40
+ "access": "public"
41
+ }
42
+ }