@naturalcycles/internal-web-lib 1.4.0 → 1.6.0

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.
@@ -1 +1 @@
1
- {"version":3,"file":"conversionClient.js","names":["nanoidBrowser","id","bytes","length","generateConversionEventId","_isTruthy","v","_isObject","obj","_isEmpty","k","abortSignalTimeoutOrUndefined","ms","abortSignalTimeout","polyfilledAbortSignalTimeout","ac","abortSignalAnyOrUndefined","filtered","signals","abortSignalAny","polyfilledAbortSignalAny","signal","commonLoggerCreate","emit","input","data","sink","context","toLogData","args","childContext","consoleLogger","fields","msg","err","level","AsyncManager","wrappedPromise","promise","fn","size","started","timeout","resolve","hook","runInBackground","_noop","_args","_objectEntries","_pick","opt","props","_omit","_filterFalsyValues","_filterObject","_filterNullishValues","_filterUndefinedValues","predicate","_mapKeys","map","mapper","_filterEmptyValues","_merge","sources","source","key","target","isServerSide","isClientSide","DETECT_JSON","_jsonParseIfPossible","reviver","_jsonParse","s","JsonParseError","_truncateMiddle","maxLen","omission","mark1","mark2","_anyToError","e","o","errorClass","_errorObjectToError","_anyToErrorObject","errorData","eo","_isErrorLike","_errorLikeToErrorObject","_isBackendErrorResponseObject","_isErrorObject","_stringify","AppError","name","cause","_errorDataAppend","message","HttpRequestError","AssertionError","TimeoutError","UnexpectedPassError","_safeJsonStringify","replacer","spaces","serializer","cycleReplacer","stack","keys","value","thisPos","supportsAggregateError","globalStringifyFunction","stringifyErrorLike","stringifyFn","sLines","i","includeErrorCause","_assertIsError","_assertErrorClassOrRethrow","pDelaySignal","timer","done","_since","_ms","until","from","millis","sec","min","hrs","_clamp","x","minIncl","maxIncl","pTimeout","fakeError","onTimeout","reject","_toUrlOrNull","url","base","HTTP_METHODS","Fetcher","cfg","method","m","payload","res","initGeneration","req","timeoutMillis","fullUrl","signature","logger","retryAttempt","reinitAttempted","shouldReinit","init","responseType","text","fetchFn","responseStatusCode","retryStatus","count","timeoutMultiplier","timeoutMax","retryAfterStr","retryAfterNumber","date","noise","retryPost","statusCode","statusFamily","retry5xx","retry4xx","retry3xx","status","shortUrl","baseUrl","norm","debug","defaultRetryOptions","inputUrl","searchParams","qs","\"accept\"","acceptByResponseType","getFetcher","domainPathKeywordSuppressionMap","debugDomainMap","allowedDomains","WebSignupQueryParam","\"flow\"","\"code\"","\"refId\"","\"referral\"","\"ignoreConfirmation\"","\"ic\"","\"measuringDevice\"","\"irclickid\"","\"fg\"","\"sfg\"","\"sq\"","\"cbo\"","\"ip\"","\"ipv\"","\"appleAuth\"","\"googleAuth\"","\"od\"","\"pl\"","\"ScCid\"","\"fbclid\"","\"ttclid\"","\"rdt_cid\"","\"epik\"","\"adid\"","\"wcf\"","\"we\"","\"werr\"","\"wdpm\"","\"wsc\"","\"ral\"","clickIdParameters","RegistrationFlow","\"OURA\"","\"APPLE_WATCH\"","\"META_LANDING_PAGE\"","\"PAYMENT_REDIRECT_FROM_APP\"","\"B1\"","\"EMAIL_VERIFICATION_REDIRECT\"","\"WHOOP\"","cookieService","cookieStrings","cookie","valueParts","decodedValue","nameEQ","cookies","d","expdays","cname","cvalue","domain","formatMetaClickId","clickId","sanitizeFbclid","parts","lastFbIdx","CLICK_ID_COOKIE_DAYS","MAX_CLICK_ID_LENGTH","MIN_FBCLID_LENGTH","ConversionClient","pathname","href","allowedDomain","origin","keyword","path","json","clientId","param","fallback","search","raw","fbclid"],"sources":["../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.0_undici@8.11.2/node_modules/@naturalcycles/js-lib/dist/nanoid.js","../src/conversion/conversion.util.ts","../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.0_undici@8.11.2/node_modules/@naturalcycles/js-lib/dist/is.util.js","../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.0_undici@8.11.2/node_modules/@naturalcycles/js-lib/dist/abort.js","../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.0_undici@8.11.2/node_modules/@naturalcycles/js-lib/dist/log/commonLogger.js","../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.0_undici@8.11.2/node_modules/@naturalcycles/js-lib/dist/asyncManager.js","../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.0_undici@8.11.2/node_modules/@naturalcycles/js-lib/dist/types.js","../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.0_undici@8.11.2/node_modules/@naturalcycles/js-lib/dist/object/object.util.js","../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.0_undici@8.11.2/node_modules/@naturalcycles/js-lib/dist/env.js","../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.0_undici@8.11.2/node_modules/@naturalcycles/js-lib/dist/string/json.util.js","../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.0_undici@8.11.2/node_modules/@naturalcycles/js-lib/dist/string/string.util.js","../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.0_undici@8.11.2/node_modules/@naturalcycles/js-lib/dist/error/error.util.js","../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.0_undici@8.11.2/node_modules/@naturalcycles/js-lib/dist/string/safeJsonStringify.js","../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.0_undici@8.11.2/node_modules/@naturalcycles/js-lib/dist/string/stringify.js","../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.0_undici@8.11.2/node_modules/@naturalcycles/js-lib/dist/error/assert.js","../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.0_undici@8.11.2/node_modules/@naturalcycles/js-lib/dist/promise/pDelay.js","../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.0_undici@8.11.2/node_modules/@naturalcycles/js-lib/dist/datetime/time.util.js","../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.0_undici@8.11.2/node_modules/@naturalcycles/js-lib/dist/number/number.util.js","../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.0_undici@8.11.2/node_modules/@naturalcycles/js-lib/dist/promise/pTimeout.js","../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.0_undici@8.11.2/node_modules/@naturalcycles/js-lib/dist/string/url.util.js","../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.0_undici@8.11.2/node_modules/@naturalcycles/js-lib/dist/http/http.model.js","../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.0_undici@8.11.2/node_modules/@naturalcycles/js-lib/dist/http/fetcher.js","../../shared/dist/cnst/privacySettings.js","../../shared/dist/cnst/queryParameters.js","../../shared/dist/service/cookie.service.js","../../shared/dist/util/metaClickId.util.js","../src/conversion/conversionClient.ts"],"sourcesContent":["// Vendored from https://github.com/ai/nanoid/blob/main/index.browser.js\n// All credit to nanoid authors: https://github.com/ai/nanoid\n// Reason for vendoring: (still) cannot import esm, and Nanoid went ESM-only since 4.0\n/// <reference lib=\"dom\" preserve=\"true\" />\n// \"0-9a-zA-Z-_\", same as base64url alphabet\nconst urlAlphabet = 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict';\n// oxlint-disable no-bitwise -- NanoID uses bit operations to build compact IDs\nexport function nanoidBrowser(length = 21) {\n let id = '';\n const bytes = globalThis.crypto.getRandomValues(new Uint8Array(length));\n while (length--) {\n // Using the bitwise AND operator to \"cap\" the value of\n // the random byte from 255 to 63, in that way we can make sure\n // that the value will be a valid index for the \"chars\" string.\n id += urlAlphabet[bytes[length] & 63];\n }\n return id;\n}\nconst defaultRandomFunction = (bytes) => globalThis.crypto.getRandomValues(new Uint8Array(bytes));\nexport function nanoidBrowserCustomAlphabet(alphabet, length = 21) {\n return customRandom(alphabet, length, defaultRandomFunction);\n}\nfunction customRandom(alphabet, defaultSize, getRandom) {\n // First, a bitmask is necessary to generate the ID. The bitmask makes bytes\n // values closer to the alphabet size. The bitmask calculates the closest\n // `2^31 - 1` number, which exceeds the alphabet size.\n // For example, the bitmask for the alphabet size 30 is 31 (00011111).\n // `Math.clz32` is not used, because it is not available in browsers.\n const mask = (2 << Math.log2(alphabet.length - 1)) - 1;\n // Though, the bitmask solution is not perfect since the bytes exceeding\n // the alphabet size are refused. Therefore, to reliably generate the ID,\n // the random bytes redundancy has to be satisfied.\n // Note: every hardware random generator call is performance expensive,\n // because the system call for entropy collection takes a lot of time.\n // So, to avoid additional system calls, extra bytes are requested in advance.\n // Next, a step determines how many random bytes to generate.\n // The number of random bytes gets decided upon the ID size, mask,\n // alphabet size, and magic number 1.6 (using 1.6 peaks at performance\n // according to benchmarks).\n // `-~f => Math.ceil(f)` if f is a float\n // `-~i => i + 1` if i is an integer\n const step = -~((1.6 * mask * defaultSize) / alphabet.length);\n return (size = defaultSize) => {\n let id = '';\n while (true) {\n const bytes = getRandom(step);\n // A compact alternative for `for (var i = 0; i < step; i++)`.\n let j = step;\n while (j--) {\n // Adding `|| ''` refuses a random byte that exceeds the alphabet size.\n id += alphabet[bytes[j] & mask] || '';\n if (id.length === size)\n return id;\n }\n }\n };\n}\n","import { nanoidBrowser } from '@naturalcycles/js-lib/nanoid'\n\nexport function generateConversionEventId(): string {\n return nanoidBrowser()\n}\n","export const _isNull = (v) => v === null;\nexport const _isUndefined = (v) => v === undefined;\nexport const _isNullish = (v) => v === undefined || v === null;\nexport const _isNotNullish = (v) => v !== undefined && v !== null;\n/**\n * Same as Boolean, but with correct type output.\n * Related:\n * https://github.com/microsoft/TypeScript/issues/16655\n * https://www.karltarvas.com/2021/03/11/typescript-array-filter-boolean.html\n *\n * @example\n *\n * [1, 2, undefined].filter(_isTruthy)\n * // => [1, 2]\n */\nexport const _isTruthy = (v) => !!v;\nexport const _isFalsy = (v) => !v;\n/**\n * Returns true if item is Object, not null and not Array.\n *\n * Currently treats RegEx as Object too, e.g _isObject(/some/) === true\n */\nexport function _isObject(obj) {\n return (typeof obj === 'object' && obj !== null && !Array.isArray(obj)) || false;\n}\n/**\n * Returns true if item is an object literal: not an Array, Error, RegExp or class instance.\n */\nexport function _isPlainObject(v) {\n if (typeof v !== 'object' || v === null)\n return false;\n const proto = Object.getPrototypeOf(v);\n return proto === Object.prototype || proto === null;\n}\nexport function _isPrimitive(v) {\n return (v === null ||\n v === undefined ||\n typeof v === 'number' ||\n typeof v === 'boolean' ||\n typeof v === 'string' ||\n typeof v === 'bigint' ||\n typeof v === 'symbol');\n}\nexport function _isEmptyObject(obj) {\n // for...in with early return avoids allocating the full Object.keys array.\n // Object.hasOwn matches Object.keys() semantics (own enumerable keys only).\n for (const k in obj) {\n if (Object.hasOwn(obj, k))\n return false;\n }\n return true;\n}\nexport function _isNotEmptyObject(obj) {\n for (const k in obj) {\n if (Object.hasOwn(obj, k))\n return true;\n }\n return false;\n}\n/**\n * Object is considered empty if it's one of:\n * undefined\n * null\n * '' (empty string)\n * [] (empty array)\n * {} (empty object)\n * new Map() (empty Map)\n * new Set() (empty Set)\n */\nexport function _isEmpty(obj) {\n if (obj === undefined || obj === null)\n return true;\n if (typeof obj === 'string' || Array.isArray(obj)) {\n return obj.length === 0;\n }\n if (obj instanceof Map || obj instanceof Set) {\n return obj.size === 0;\n }\n if (typeof obj === 'object') {\n for (const k in obj) {\n if (Object.hasOwn(obj, k))\n return false;\n }\n return true;\n }\n return false;\n}\n/**\n * @see _isEmpty\n */\nexport function _isNotEmpty(obj) {\n return !_isEmpty(obj);\n}\n","import { _isTruthy } from './is.util.js';\n/**\n * Creates AbortableSignal,\n * which is like AbortSignal, but can \"abort itself\" with `.abort()` method.\n *\n * @experimental\n */\nexport function createAbortableSignal() {\n const ac = new AbortController();\n return Object.assign(ac.signal, {\n abort: ac.abort.bind(ac),\n });\n}\n/**\n * Returns AbortSignal if ms is defined.\n * Otherwise returns undefined.\n */\nexport function abortSignalTimeoutOrUndefined(ms) {\n return ms ? abortSignalTimeout(ms) : undefined;\n}\n/**\n * Returns an AbortSignal that aborts after the given number of milliseconds.\n * Uses native `AbortSignal.timeout()` when available, falls back to a polyfill.\n *\n * The abort reason is a DOMException with name \"TimeoutError\".\n */\nexport function abortSignalTimeout(ms) {\n return typeof AbortSignal.timeout === 'function'\n ? AbortSignal.timeout(ms)\n : polyfilledAbortSignalTimeout(ms);\n}\nexport function polyfilledAbortSignalTimeout(ms) {\n const ac = new AbortController();\n setTimeout(() => {\n ac.abort(new DOMException('The operation was aborted due to timeout', 'TimeoutError'));\n }, ms);\n return ac.signal;\n}\n/**\n * Returns AbortSignal.any(signals) is the array (after filtering undefined inputs) is not empty,\n * otherwise undefined.\n */\nexport function abortSignalAnyOrUndefined(signals) {\n const filtered = signals.filter(_isTruthy);\n return filtered.length ? abortSignalAny(filtered) : undefined;\n}\n/**\n * Returns an AbortSignal that aborts when any of the given signals abort.\n * Uses native `AbortSignal.any()` when available, falls back to a polyfill.\n *\n * The abort reason is taken from the first signal that aborts.\n * If any input signal is already aborted, the returned signal is immediately aborted.\n *\n * If only 1 signal is passed in the input array - that Signal is returned as-is.\n */\nexport function abortSignalAny(signals) {\n if (signals.length === 1) {\n return signals[0];\n }\n return typeof AbortSignal.any === 'function'\n ? AbortSignal.any(signals)\n : polyfilledAbortSignalAny(signals);\n}\nexport function polyfilledAbortSignalAny(signals) {\n const ac = new AbortController();\n for (const signal of signals) {\n if (signal.aborted) {\n ac.abort(signal.reason);\n return ac.signal;\n }\n }\n for (const signal of signals) {\n signal.addEventListener('abort', () => ac.abort(signal.reason), {\n once: true,\n signal: ac.signal,\n });\n }\n return ac.signal;\n}\n","// copy-pasted to avoid weird circular dependency\nconst _noop = (..._args) => undefined;\nexport const commonLogLevelNumber = {\n debug: 10,\n log: 20,\n warn: 30,\n error: 40,\n};\n/**\n * Creates a CommonLogger that writes every entry to `sink`.\n * `context` is called on every log call, so it can return values that change\n * after the logger is created (e.g a request context whose user is resolved later).\n */\nexport function commonLoggerCreate(sink, context) {\n const emit = (level, [input, data]) => sink({ ...context?.(), ...toLogData(input, data), level });\n return {\n debug: (...args) => emit('debug', args),\n log: (...args) => emit('log', args),\n warn: (...args) => emit('warn', args),\n error: (...args) => emit('error', args),\n child: childContext => commonLoggerCreate(sink, () => ({ ...context?.(), ...childContext })),\n };\n}\nfunction toLogData(input, data) {\n if (typeof input === 'string')\n return { ...data, msg: input };\n if (input instanceof Error)\n return { err: input };\n return input;\n}\n/**\n * CommonLogger that logs to `console`.\n */\nexport const consoleLogger = commonLoggerCreate(({ level, msg, err, ...fields }) => {\n const args = [];\n if (msg !== undefined)\n args.push(msg);\n if (err !== undefined)\n args.push(err);\n if (Object.keys(fields).length)\n args.push(fields);\n console[level](...args);\n});\n/**\n * CommonLogger that does nothing (noop).\n */\nexport const commonLoggerNoop = {\n debug: _noop,\n log: _noop,\n warn: _noop,\n error: _noop,\n child: () => commonLoggerNoop,\n};\n/**\n * Creates a CommonLogger that is \"limited\" to the specified CommonLogLevel.\n */\nexport function createCommonLoggerAtLevel(logger = consoleLogger, minLevel = 'log') {\n const level = commonLogLevelNumber[minLevel];\n if (level <= commonLogLevelNumber['debug']) {\n // All levels are kept\n return logger;\n }\n return {\n debug: _noop, // otherwise it is \"log everything\" logger (same logger as input)\n log: level <= commonLogLevelNumber['log'] ? (...args) => logger.log(...args) : _noop,\n warn: level <= commonLogLevelNumber['warn'] ? (...args) => logger.warn(...args) : _noop,\n error: (...args) => logger.error(...args),\n child: context => createCommonLoggerAtLevel(logger.child(context), minLevel),\n };\n}\n/**\n * Creates a \"proxy\" CommonLogger that pipes log entries to all provided sub-loggers.\n */\nexport function commonLoggerPipe(loggers) {\n return {\n debug: (...args) => loggers.forEach(logger => logger.debug(...args)),\n log: (...args) => loggers.forEach(logger => logger.log(...args)),\n warn: (...args) => loggers.forEach(logger => logger.warn(...args)),\n error: (...args) => loggers.forEach(logger => logger.error(...args)),\n child: context => commonLoggerPipe(loggers.map(logger => logger.child(context))),\n };\n}\n","import { consoleLogger } from './log/commonLogger.js';\nclass AsyncManagerImpl {\n logger = consoleLogger;\n pendingOps = new Set();\n onErrorHooks = [];\n runInBackground(promise) {\n const wrappedPromise = promise\n .catch(err => this.fireOnErrorHooks(err))\n .finally(() => this.pendingOps.delete(wrappedPromise));\n this.pendingOps.add(wrappedPromise);\n }\n onError(fn) {\n this.onErrorHooks.push(fn);\n }\n /**\n * Resolves when all pending operations settle.\n * They may resolve or reject, allDone will never throw.\n * Errors (rejections) are reported to onErrorHooks (instead).\n *\n * If timeout is specified - it resolves if timeout has reached.\n */\n async allDone(timeout) {\n const { size } = this.pendingOps;\n if (!size)\n return;\n const { logger } = this;\n const started = Date.now();\n if (timeout) {\n const result = await Promise.race([\n Promise.allSettled(this.pendingOps),\n new Promise(resolve => setTimeout(resolve, timeout, 'timeout')),\n ]);\n if (result === 'timeout') {\n logger.warn(`AsyncManager.allDone timed out after ${timeout} ms with ${this.pendingOps.size} pending op(s)`);\n return;\n }\n }\n else {\n await Promise.allSettled(this.pendingOps);\n }\n logger.log(`AsyncManager.allDone for ${size} op(s) in ${Date.now() - started} ms`);\n }\n reset() {\n this.pendingOps.clear();\n this.onErrorHooks = [];\n }\n fireOnErrorHooks(err) {\n if (this.onErrorHooks.length) {\n this.onErrorHooks.forEach(hook => hook(err));\n }\n else {\n this.logger.error({ msg: 'AsyncManager unhandled rejection', err });\n }\n }\n}\n/**\n * Singleton which keeps track of async operations - \"voided promise-returning functions\"\n * that should run in parallel to the main request.\n *\n * It is an alternative to do `void doSomeAnalytics()`, which should run in parallel\n * and not block the request (not slow down nor fail the request on analytics api failure).\n *\n * At the same time, `void doSomeAnalytics()` gets completely detached and untracked,\n * nothing awaits it, its rejection becomes unhandledRejection (and may kill Node.js process).\n *\n * With AsyncManager, you instead register all those \"voided\" calls like this:\n *\n * AsyncManager.runInBackground(doSomeAnalytics())\n *\n * Then, in a few places you may be interested to ensure that all async operations have been finished.\n * The places can be:\n * - Graceful shutdown of a backend service\n * - Before the end of runScript\n * - At the end of each unit test, to make sure async ops don't leak\n *\n * You ensure no pending async operations like this:\n *\n * await AsyncManager.allDone()\n *\n * which never throws, but instead awaits all operations to be settled.\n *\n * @experimental\n */\nexport const AsyncManager = new AsyncManagerImpl();\n// Shorthand alias\nexport const runInBackground = AsyncManager.runInBackground.bind(AsyncManager);\n","/**\n * Symbol to indicate END of Sequence.\n */\nexport const END = Symbol('END');\n/**\n * Symbol to indicate SKIP of item (e.g in AbortableMapper)\n */\nexport const SKIP = Symbol('SKIP');\n/**\n * Symbol to indicate cache miss.\n * To distinguish from cache returning `undefined` or `null`.\n */\nexport const MISS = Symbol('MISS');\nexport const _passthroughMapper = item => item;\nexport const _passUndefinedMapper = () => undefined;\n/**\n * Function that does nothings and returns `undefined`.\n */\nexport const _noop = (..._args) => undefined;\nexport const _passthroughPredicate = () => true;\nexport const _passNothingPredicate = () => false;\nexport const JWT_REGEX = /^[\\w-]+\\.[\\w-]+\\.[\\w-]+$/;\n/**\n * Needed due to https://github.com/microsoft/TypeScript/issues/13778\n * Only affects typings, no runtime effect.\n */\nexport const _stringMapValues = Object.values;\n/**\n * Needed due to https://github.com/microsoft/TypeScript/issues/13778\n * Only affects typings, no runtime effect.\n */\nexport const _stringMapEntries = Object.entries;\n/**\n * Alias of `Object.keys`, but returns keys typed as `keyof T`, not as just `string`.\n * This is how TypeScript should work, actually.\n *\n * Object.keys always returns strings, so numeric keys are stringified via `${K}`.\n * Symbol keys are excluded (Object.keys does not return symbols).\n */\nexport const _objectKeys = Object.keys;\n/**\n * Alias of `Object.entries`, but returns better-typed output.\n *\n * Difference with _stringMapEntries?\n * Use _stringMapEntries when the object is a StringMap<T> - it'll correctly infer T being not undefined.\n * If the object is not a StringMap - use _objectEntries - it'll correctly infer object keys, which can be typed as Enum.\n *\n * So e.g you can use _objectEntries(obj).map([k, v] => {})\n * and `k` will be `keyof obj` instead of generic `string`.\n */\nexport const _objectEntries = Object.entries;\n/**\n * Utility function that helps to cast *existing variable* to needed type T.\n *\n * @example\n * try {} catch (err) {\n * // err is unknown here\n * _typeCast<AppError>(err)\n * // now err is of type AppError\n * err.data = {} // can be done, because it was casted\n * }\n */\nexport function _typeCast(_v) { }\n/**\n * Type-safe Object.assign that checks that part is indeed a Partial<T>\n */\nexport const _objectAssign = Object.assign;\n","import { _isEmpty, _isObject } from '../is.util.js';\nimport { _objectEntries, SKIP } from '../types.js';\n/**\n * Returns clone of `obj` with only `props` preserved.\n * Opposite of Omit.\n */\nexport function _pick(obj, props, opt = {}) {\n if (opt.mutate) {\n // Start as original object (mutable), DELETE properties that are not whitelisted\n for (const k of Object.keys(obj)) {\n if (!props.includes(k))\n delete obj[k];\n }\n return obj;\n }\n // Start as empty object, pick/add needed properties\n const r = {};\n for (const k of props) {\n if (k in obj)\n r[k] = obj[k];\n }\n return r;\n}\n/**\n * Sets all properties of an object except passed ones to `undefined`.\n * This is a more performant alternative to `_pick` that does picking/deleting.\n */\nexport function _pickWithUndefined(obj, props, opt = {}) {\n const r = opt.mutate ? obj : { ...obj };\n for (const k of Object.keys(r)) {\n if (!props.includes(k)) {\n r[k] = undefined;\n }\n }\n return r;\n}\n/**\n * Returns clone of `obj` with `props` omitted.\n * Opposite of Pick.\n */\nexport function _omit(obj, props, opt = {}) {\n if (opt.mutate) {\n for (const k of props) {\n delete obj[k];\n }\n return obj;\n }\n const r = {};\n for (const k of Object.keys(obj)) {\n if (!props.includes(k))\n r[k] = obj[k];\n }\n return r;\n}\n/**\n * Sets all passed properties of an object to `undefined`.\n * This is a more performant alternative to `_omit` that does picking/deleting.\n */\nexport function _omitWithUndefined(obj, props, opt = {}) {\n const r = opt.mutate ? obj : { ...obj };\n for (const k of props) {\n r[k] = undefined;\n }\n return r;\n}\n/**\n * Returns object with filtered keys from `props` array.\n * E.g:\n * _mask({...}, [\n * 'account.id',\n * 'account.updated',\n * ])\n */\nexport function _mask(obj, props, opt = {}) {\n const r = opt.mutate ? obj : _deepCopy(obj);\n for (const k of props) {\n _unset(r, k);\n }\n return r;\n}\n/**\n * Removes \"falsy\" values from the object.\n */\nexport function _filterFalsyValues(obj, opt = {}) {\n return _filterObject(obj, (_k, v) => !!v, opt);\n}\n/**\n * Removes values from the object that are `null` or `undefined`.\n */\nexport function _filterNullishValues(obj, opt = {}) {\n return _filterObject(obj, (_k, v) => v !== undefined && v !== null, opt);\n}\n/**\n * Removes values from the object that are `undefined`.\n * Only `undefined` values are removed. `null` values are kept!\n */\nexport function _filterUndefinedValues(obj, opt = {}) {\n return _filterObject(obj, (_k, v) => v !== undefined, opt);\n}\nexport function _filterEmptyArrays(obj, opt = {}) {\n return _filterObject(obj, (_k, v) => !Array.isArray(v) || v.length > 0, opt);\n}\n/**\n * Returns clone of `obj` without properties that does not pass `predicate`.\n * Allows filtering by both key and value.\n */\nexport function _filterObject(obj, predicate, opt = {}) {\n if (opt.mutate) {\n for (const [k, v] of _objectEntries(obj)) {\n if (!predicate(k, v, obj)) {\n delete obj[k];\n }\n }\n return obj;\n }\n // Not vulnerable to prototype pollution: writes to a new {}, where __proto__\n // assignment only changes the new object's prototype, not Object.prototype.\n const r = {};\n for (const [k, v] of _objectEntries(obj)) {\n if (predicate(k, v, obj)) {\n r[k] = v;\n }\n }\n return r;\n}\n/**\n * var users = {\n * 'fred': { 'user': 'fred', 'age': 40 },\n * 'pebbles': { 'user': 'pebbles', 'age': 1 }\n * }\n *\n * _mapValues(users, (_key, value) => value.age)\n * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)\n *\n * To skip some key-value pairs - use _mapObject instead.\n */\nexport function _mapValues(obj, mapper, opt = {}) {\n // Not vulnerable to prototype pollution: writes to a new {} (or mutates the\n // source in-place where own data properties shadow the __proto__ accessor).\n const map = opt.mutate ? obj : {};\n for (const [k, v] of Object.entries(obj)) {\n map[k] = mapper(k, v, obj);\n }\n return map;\n}\n/**\n * _.mapKeys({ 'a': 1, 'b': 2 }, (key, value) => key + value)\n * // => { 'a1': 1, 'b2': 2 }\n *\n * Does not support `mutate` flag.\n *\n * To skip some key-value pairs - use _mapObject instead.\n */\nexport function _mapKeys(obj, mapper) {\n // Not vulnerable to prototype pollution: writes to a new {}, where __proto__\n // assignment only changes the new object's prototype, not Object.prototype.\n const map = {};\n for (const [k, v] of Object.entries(obj)) {\n map[mapper(k, v, obj)] = v;\n }\n return map;\n}\n/**\n * Maps object through predicate - a function that receives (k, v, obj)\n * k - key\n * v - value\n * obj - whole object\n *\n * Order of arguments in the predicate is different form _mapValues / _mapKeys!\n *\n * Predicate should return a _tuple_ [0, 1], where:\n * 0 - key of returned object (string)\n * 1 - value of returned object (any)\n *\n * If predicate returns SKIP symbol - such key/value pair is ignored (filtered out).\n *\n * Non-string keys are passed via String(...)\n */\nexport function _mapObject(obj, mapper) {\n // Not vulnerable to prototype pollution: writes to a new {}, where __proto__\n // assignment only changes the new object's prototype, not Object.prototype.\n const map = {};\n for (const [k, v] of Object.entries(obj)) {\n const r = mapper(k, v, obj);\n if (r === SKIP)\n continue;\n map[r[0]] = r[1];\n }\n return map;\n}\nexport function _findKeyByValue(obj, v) {\n return Object.entries(obj).find(([_, value]) => value === v)?.[0];\n}\n/**\n * Returns the first key of a non-empty object.\n * Throws if the object is empty.\n *\n * Performance-optimised: uses `for...in` with an early return to avoid\n * allocating the full `Object.keys(obj)` array. The `Object.hasOwn` filter\n * matches `Object.keys()` semantics (own enumerable string keys only) and\n * satisfies the `guard-for-in` lint rule; cost is a single check before\n * the early return. Iteration order matches `Object.keys()` for plain\n * objects (integer-like keys ascending first, then string keys in\n * insertion order).\n */\nexport function _firstKey(obj) {\n for (const k in obj) {\n if (Object.hasOwn(obj, k))\n return k;\n }\n throw new Error('_firstKey called on empty object');\n}\n/**\n * Returns the first key of the object (or undefined if the object is empty).\n * See `_firstKey` for the iteration-order contract.\n */\nexport function _firstKeyOrUndefined(obj) {\n for (const k in obj) {\n if (Object.hasOwn(obj, k))\n return k;\n }\n return undefined;\n}\n/**\n * Returns the first value of a non-empty object.\n * Throws if the object is empty.\n * See `_firstKey` for the iteration-order contract.\n */\nexport function _firstValue(obj) {\n for (const k in obj) {\n if (Object.hasOwn(obj, k))\n return obj[k];\n }\n throw new Error('_firstValue called on empty object');\n}\n/**\n * Returns the first value of the object (or undefined if the object is empty).\n * See `_firstKey` for the iteration-order contract.\n */\nexport function _firstValueOrUndefined(obj) {\n for (const k in obj) {\n if (Object.hasOwn(obj, k))\n return obj[k];\n }\n return undefined;\n}\n/**\n * Returns the first [key, value] tuple of a non-empty object.\n * Throws if the object is empty.\n * See `_firstKey` for the iteration-order contract.\n */\nexport function _firstEntry(obj) {\n for (const k in obj) {\n if (Object.hasOwn(obj, k))\n return [k, obj[k]];\n }\n throw new Error('_firstEntry called on empty object');\n}\n/**\n * Returns the first [key, value] tuple of the object (or undefined if the object is empty).\n * See `_firstKey` for the iteration-order contract.\n */\nexport function _firstEntryOrUndefined(obj) {\n for (const k in obj) {\n if (Object.hasOwn(obj, k))\n return [k, obj[k]];\n }\n return undefined;\n}\nexport function _objectNullValuesToUndefined(obj, opt = {}) {\n return _mapValues(obj, (_k, v) => (v === null ? undefined : v), opt);\n}\n/**\n * Deep copy object (by json parse/stringify, since it has unbeatable performance+simplicity combo).\n */\nexport function _deepCopy(o, reviver) {\n return JSON.parse(JSON.stringify(o), reviver);\n}\n/**\n * Performance-optimized implementation of merging two objects\n * without mutating any of them.\n * (if you are allowed to mutate - there can be a faster implementation).\n *\n * Gives ~40% speedup with map sizes between 10 and 100k items,\n * compared to {...obj1, ...obj2} or Object.assign({}, obj1, obj2).\n *\n * Only use it in hot paths that are known to be performance bottlenecks,\n * otherwise it's not worth it (use normal object spread then).\n */\nexport function _mergeObjects(obj1, obj2) {\n // Not vulnerable to prototype pollution: writes to a new {}, where __proto__\n // assignment only changes the new object's prototype, not Object.prototype.\n const map = {};\n for (const k of Object.keys(obj1))\n map[k] = obj1[k];\n for (const k of Object.keys(obj2))\n map[k] = obj2[k];\n return map;\n}\n/**\n * Returns `undefined` if it's empty (according to `_isEmpty()` specification),\n * otherwise returns the original object.\n */\nexport function _undefinedIfEmpty(obj) {\n return _isEmpty(obj) ? undefined : obj;\n}\n/**\n * Filters the object by removing all key-value pairs where Value is Empty (according to _isEmpty() specification).\n */\nexport function _filterEmptyValues(obj, opt = {}) {\n return _filterObject(obj, (_k, v) => !_isEmpty(v), opt);\n}\n/**\n * Recursively merges own and inherited enumerable properties of source\n * objects into the destination object, skipping source properties that resolve\n * to `undefined`. Array and plain object properties are merged recursively.\n * Other objects and value types are overridden by assignment. Source objects\n * are applied from left to right. Subsequent sources overwrite property\n * assignments of previous sources.\n *\n * Works as \"recursive Object.assign\".\n *\n * **Note:** This method mutates `object`.\n *\n * @param target The destination object.\n * @param sources The source objects.\n * @returns Returns `object`.\n * @example\n *\n * var users = {\n * 'data': [{ 'user': 'barney' }, { 'user': 'fred' }]\n * };\n *\n * var ages = {\n * 'data': [{ 'age': 36 }, { 'age': 40 }]\n * };\n *\n * _.merge(users, ages);\n * // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] }\n *\n * Based on: https://gist.github.com/Salakar/1d7137de9cb8b704e48a\n */\nexport function _merge(target, ...sources) {\n for (const source of sources) {\n if (!_isObject(source))\n continue;\n for (const key of Object.keys(source)) {\n if (key === '__proto__' || key === 'constructor' || key === 'prototype')\n continue;\n if (_isObject(source[key])) {\n ;\n target[key] ||= {};\n _merge(target[key], source[key]);\n }\n else {\n ;\n target[key] = source[key];\n }\n }\n }\n return target;\n}\n/**\n * Trims all object VALUES deeply.\n * Doesn't touch object KEYS.\n * Mutates.\n */\nexport function _deepTrim(o) {\n if (!o)\n return o;\n if (typeof o === 'string') {\n return o.trim();\n }\n if (typeof o === 'object') {\n // Not vulnerable to prototype pollution: mutates in-place on the same object.\n // If __proto__ is an own data property (e.g. from JSON.parse), reads and writes\n // go through the own property, not the Object.prototype accessor.\n for (const k of Object.keys(o)) {\n o[k] = _deepTrim(o[k]);\n }\n }\n return o;\n}\n// from: https://github.com/jonschlinkert/unset-value\n// mutates obj\nexport function _unset(obj, prop) {\n if (!_isObject(obj)) {\n return;\n }\n if (obj.hasOwnProperty(prop)) {\n delete obj[prop];\n return;\n }\n const segs = prop.split('.');\n // Prevent prototype pollution\n if (segs.includes('__proto__') || segs.includes('constructor'))\n return;\n let last = segs.pop();\n while (segs.length && segs[segs.length - 1].endsWith('\\\\')) {\n last = segs.pop().slice(0, -1) + '.' + last;\n }\n while (segs.length && _isObject(obj)) {\n const k = segs.shift();\n obj = obj[k];\n }\n if (!_isObject(obj))\n return;\n delete obj[last];\n}\nexport function _invert(o) {\n const inv = {};\n Object.keys(o).forEach(k => {\n inv[o[k]] = k;\n });\n return inv;\n}\nexport function _invertMap(m) {\n const inv = new Map();\n m.forEach((v, k) => inv.set(v, k));\n return inv;\n}\n/**\n * Gets the property value at path of object.\n *\n * @example\n * const obj = {a: 'a', b: 'b', c: { cc: 'cc' }}\n * _get(obj, 'a') // 'a'\n * _get(obj, 'c.cc') // 'cc'\n * _get(obj, 'c[cc]') // 'cc'\n * _get(obj, 'unknown.path') // undefined\n */\nexport function _get(obj = {}, path = '') {\n return (path\n .replaceAll(/\\[([^\\]]+)]/g, '.$1')\n .split('.')\n // oxlint-disable-next-line unicorn/no-array-reduce\n .reduce((o, p) => o?.[p], obj));\n}\n/**\n * Sets the value at path of object. If a portion of path doesn’t exist it’s created. Arrays are created for\n * missing index properties while objects are created for all other missing properties.\n *\n * @param obj The object to modify.\n * @param path The path of the property to set.\n * @param value The value to set.\n * @returns Returns object.\n *\n * Based on: https://stackoverflow.com/a/54733755/4919972\n */\nexport function _set(obj, path, value) {\n if (!obj || Object(obj) !== obj || !path)\n return obj; // When obj is not an object\n // If not yet an array, get the keys from the string-path\n if (!Array.isArray(path)) {\n path = String(path).match(/[^.[\\]]+/g) || [];\n }\n else if (!path.length) {\n return obj;\n }\n // Prevent prototype pollution\n if (path.includes('__proto__') || path.includes('constructor')) {\n return obj;\n }\n // oxlint-disable-next-line unicorn/no-array-reduce\n ;\n path.slice(0, -1).reduce((a, c, i) => Object(a[c]) === a[c] // Does the key exist and is its value an object?\n ? // Yes: then follow that path\n a[c]\n : // No: create the key. Is the next key a potential array-index?\n (a[c] =\n // oxlint-disable-next-line no-bitwise, no-implicit-coercion, unicorn/prefer-math-trunc\n Math.abs(path[i + 1]) >> 0 === +path[i + 1]\n ? [] // Yes: assign a new array object\n : {}), // No: assign a new plain object\n obj)[path[path.length - 1]] = value; // Finally assign the value to the last key\n return obj; // allow chaining\n}\n/**\n * Checks if `path` is a direct property of `object` (not null, not undefined).\n *\n * @param obj The object to query.\n * @param path The path to check.\n * @returns Returns `true` if `path` exists, else `false`.\n * @example\n *\n * var object = { 'a': { 'b': { 'c': 3 } } };\n * var other = _.create({ 'a': _.create({ 'b': _.create({ 'c': 3 }) }) });\n *\n * _.has(object, 'a');\n * // => true\n *\n * _.has(object, 'a.b.c');\n * // => true\n *\n * _.has(object, ['a', 'b', 'c']);\n * // => true\n *\n * _.has(other, 'a');\n * // => false\n */\nexport function _has(obj, path) {\n const v = _get(obj, path);\n return v !== undefined && v !== null;\n}\n/**\n * Does Object.freeze recursively for given object.\n *\n * Based on: https://github.com/substack/deep-freeze/blob/master/index.js\n */\nexport function _deepFreeze(o) {\n // Not vulnerable to prototype pollution: read-only traversal, only calls\n // Object.freeze — never assigns properties from one object to another.\n Object.freeze(o);\n Object.getOwnPropertyNames(o).forEach(prop => {\n if (o.hasOwnProperty(prop) &&\n o[prop] !== null &&\n (typeof o[prop] === 'object' || typeof o[prop] === 'function') &&\n !Object.isFrozen(o[prop])) {\n _deepFreeze(o[prop]);\n }\n });\n}\n/**\n * let target: T = { a: 'a', n: 1}\n * let source: T = { a: 'a2', b: 'b' }\n *\n * _objectAssignExact(target, source)\n *\n * Does the same as `target = source`,\n * except that it mutates the target to make it exactly the same as source,\n * while keeping the reference to the same object.\n *\n * This way it can \"propagate deletions\".\n * E.g source doesn't have the `n` property, so it'll be deleted from target.\n * With normal Object.assign - it'll override the keys that `source` has, but not the\n * \"missing/deleted keys\".\n *\n * To make mutation extra clear - function returns void (unlike Object.assign).\n */\nexport function _objectAssignExact(target, source) {\n Object.assign(target, source);\n for (const k of Object.keys(target)) {\n if (!(k in source)) {\n // consider setting it to undefined maybe?\n delete target[k];\n }\n }\n}\n/**\n * type MyObj = { a?: string, b?: string }\n *\n * const collection: MyObj[] = [...]\n *\n * const collectionA = collection.filter(_hasProp('a'))\n * --> collectionA is now RequiredProp<MyObj, 'a'>[], i.e. { a: string, b?: string }[]\n */\nexport function _hasProp(prop) {\n return function (object) {\n return typeof object[prop] !== 'undefined';\n };\n}\n","/**\n * Use it to detect SSR/Node.js environment.\n *\n * Will return `true` in Node.js.\n * Will return `false` in the Browser.\n */\nexport function isServerSide() {\n return !isClientSide();\n}\n/**\n * Use it to detect Browser (not SSR/Node) environment.\n *\n * Will return `true` in the Browser.\n * Will return `false` in Node.js.\n */\nexport function isClientSide() {\n // oxlint-disable-next-line unicorn/prefer-global-this\n return typeof window !== 'undefined' && !!window?.document;\n}\n/**\n * Almost the same as isServerSide()\n * (isServerSide should return true for Node),\n * but detects Node specifically (not Deno, not Bun, etc).\n */\nexport function isNode() {\n return typeof process !== 'undefined' && process?.release?.name === 'node';\n}\n","// oxlint-disable-next-line import/no-cycle -- intentional cycle\nimport { JsonParseError } from '../error/error.util.js';\n// const possibleJsonStartTokens = ['{', '[', '\"']\nconst DETECT_JSON = /^\\s*[{[\"\\-\\d]/;\n/**\n * Attempts to parse object as JSON.\n * Returns original object if JSON parse failed (silently).\n */\nexport function _jsonParseIfPossible(obj, reviver) {\n // Optimization: only try to parse if it looks like JSON: starts with a json possible character\n if (typeof obj === 'string' && obj && DETECT_JSON.test(obj)) {\n try {\n return JSON.parse(obj, reviver);\n }\n catch { }\n }\n return obj;\n}\n/**\n * Convenience function that does JSON.parse, but doesn't throw on error,\n * instead - safely returns `undefined`.\n */\nexport function _jsonParseOrUndefined(obj, reviver) {\n // Optimization: only try to parse if it looks like JSON: starts with a json possible character\n if (typeof obj === 'string' && obj && DETECT_JSON.test(obj)) {\n try {\n return JSON.parse(obj, reviver);\n }\n catch { }\n }\n}\n/**\n * Same as JSON.parse, but throws JsonParseError:\n *\n * 1. It's message includes a piece of source text (truncated)\n * 2. It's data.text contains full source text\n */\nexport function _jsonParse(s, reviver) {\n try {\n return JSON.parse(s, reviver);\n }\n catch {\n throw new JsonParseError({\n text: s,\n });\n }\n}\n","/**\n * Converts the first character of string to upper case and the remaining to lower case.\n * Returns a type-safe capitalized string.\n */\nexport function _capitalize(s = '') {\n return (s.charAt(0).toUpperCase() + s.slice(1).toLowerCase());\n}\n/**\n * Convert a string to a type-safe uppercase string.\n */\nexport function _toUpperCase(s) {\n return s.toUpperCase();\n}\n/**\n * Convert a string to a type-safe lowercase string.\n */\nexport function _toLowercase(s) {\n return s.toLowerCase();\n}\nexport function _upperFirst(s = '') {\n return (s.charAt(0).toUpperCase() + s.slice(1));\n}\nexport function _lowerFirst(s) {\n return (s.charAt(0).toLowerCase() + s.slice(1));\n}\n/**\n * Like String.split(), but with limit, returning the tail together with last element.\n *\n * @returns Returns the new array of string segments.\n */\nexport function _split(str, separator, limit) {\n const parts = str.split(separator);\n if (parts.length <= limit)\n return parts;\n return [...parts.slice(0, limit - 1), parts.slice(limit - 1).join(separator)];\n}\nexport function _removeWhitespace(s) {\n return s.replaceAll(/\\s/g, '');\n}\n/**\n * _.truncate('hi-diddly-ho there, neighborino')\n * // => 'hi-diddly-ho there, neighbo...'\n */\nexport function _truncate(s, maxLen, omission = '...') {\n if (!s || s.length <= maxLen)\n return s;\n if (maxLen <= omission.length)\n return omission;\n return s.slice(0, maxLen - omission.length) + omission;\n}\n/**\n * _.truncateMiddle('abcdefghijklmnopqrstuvwxyz', 10)\n * // => 'abcd...xyz'\n */\nexport function _truncateMiddle(s, maxLen, omission = '...') {\n if (!s || s.length <= maxLen)\n return s;\n if (maxLen <= omission.length)\n return omission;\n const mark1 = Math.round((maxLen - omission.length) / 2);\n const mark2 = s.length - Math.floor((maxLen - omission.length) / 2);\n return s.slice(0, mark1) + omission + s.slice(mark2);\n}\n// These functions are modeled after Kotlin's String API\nexport function _substringBefore(s, delimiter) {\n const pos = s.indexOf(delimiter);\n return s.slice(0, pos !== -1 ? pos : undefined);\n}\nexport function _substringBeforeLast(s, delimiter) {\n const pos = s.lastIndexOf(delimiter);\n return s.slice(0, pos !== -1 ? pos : undefined);\n}\nexport function _substringAfter(s, delimiter) {\n const pos = s.indexOf(delimiter);\n return pos !== -1 ? s.slice(pos + delimiter.length) : s;\n}\nexport function _substringAfterLast(s, delimiter) {\n const pos = s.lastIndexOf(delimiter);\n return pos !== -1 ? s.slice(pos + delimiter.length) : s;\n}\n/**\n * Returns the substring between LAST `leftDelimiter` and then FIRST `rightDelimiter`.\n *\n * @example\n *\n * const s = '/Users/lalala/someFile.test.ts'\n * _substringBetweenLast(s, '/', '.')\n * // `someFile`\n */\nexport function _substringBetweenLast(s, leftDelimiter, rightDelimiter) {\n return _substringBefore(_substringAfterLast(s, leftDelimiter), rightDelimiter);\n}\n/**\n * Converts `\\n` (aka new-line) to `<br>`, to be presented in HTML.\n * Keeps `\\n`, so if it's printed in non-HTML environment it still looks ok-ish.\n */\nexport function _nl2br(s) {\n return s.replaceAll('\\n', '<br>\\n');\n}\n","import { isServerSide } from '../env.js';\n// oxlint-disable-next-line import/no-cycle -- intentional cycle\nimport { _jsonParseIfPossible } from '../string/json.util.js';\nimport { _truncate, _truncateMiddle } from '../string/string.util.js';\n// oxlint-disable-next-line import/no-cycle -- intentional cycle\nimport { _stringify } from '../string/stringify.js';\n/**\n * Useful to ensure that error in `catch (err) { ... }`\n * is indeed an Error (and not e.g `string` or `undefined`).\n * 99% of the cases it will be Error already.\n * Becomes more useful since TypeScript 4.4 made `err` of type `unknown` by default.\n *\n * Alternatively, if you're sure it's Error - you can use `_assertIsError(err)`.\n */\nexport function _anyToError(o, errorClass = Error, errorData) {\n let e;\n if (o instanceof errorClass) {\n e = o;\n }\n else {\n // If it's an instance of Error, but ErrorClass is something else (e.g AppError) - it'll be \"repacked\" into AppError\n const errorObject = _anyToErrorObject(o);\n e = _errorObjectToError(errorObject, errorClass);\n }\n if (errorData) {\n ;\n e.data ||= {};\n // Using Object.assign instead of ...data to not override err.data's non-enumerable properties\n Object.assign(e.data, errorData);\n }\n return e;\n}\n/**\n * Converts \"anything\" to ErrorObject.\n * Detects if it's HttpErrorResponse, HttpErrorObject, ErrorObject, Error, etc..\n * If object is Error - Error.message will be used.\n * Objects (not Errors) get converted to prettified JSON string (via `_stringify`).\n */\nexport function _anyToErrorObject(o, errorData) {\n let eo;\n if (_isErrorLike(o)) {\n eo = _errorLikeToErrorObject(o);\n }\n else {\n o = _jsonParseIfPossible(o);\n if (_isBackendErrorResponseObject(o)) {\n eo = o.error;\n }\n else if (_isErrorObject(o)) {\n eo = o;\n }\n else if (_isErrorLike(o)) {\n eo = _errorLikeToErrorObject(o);\n }\n else {\n // Here we are sure it has no `data` property,\n // so, fair to return `data: {}` in the end\n // Also we're sure it includes no \"error name\", e.g no `Error: ...`,\n // so, fair to include `name: 'Error'`\n const message = _stringify(o);\n eo = {\n name: 'Error',\n message,\n data: {}, // empty\n };\n }\n }\n Object.assign(eo.data, errorData);\n return eo;\n}\nexport function _errorLikeToErrorObject(e) {\n // If it's already an ErrorObject - just return it\n // AppError satisfies ErrorObject interface\n // Error does not satisfy (lacks `data`)\n // UPD: no, we expect a \"plain object\" here as an output,\n // because Error classes sometimes have non-enumerable properties (e.g data)\n if (!(e instanceof Error) && _isErrorObject(e)) {\n return e;\n }\n const obj = {\n name: e.name,\n message: e.message,\n data: { ...e.data }, // empty by default\n };\n if (e.stack)\n obj.stack = e.stack;\n if (e.cause) {\n obj.cause = _anyToErrorObject(e.cause);\n }\n return obj;\n}\nexport function _errorObjectToError(o, errorClass = Error) {\n if (o instanceof errorClass)\n return o;\n // Here we pass constructor values assuming it's AppError or sub-class of it\n // If not - will be checked at the next step\n // We cannot check `if (errorClass instanceof AppError)`, only `err instanceof AppError`\n const { name, cause } = o;\n const err = new errorClass(o.message, o.data, { name, cause });\n // name: err.name, // cannot be assigned to a readonly property like this\n // stack: o.stack, // also readonly e.g in Firefox\n if (o.stack) {\n Object.defineProperty(err, 'stack', {\n value: o.stack,\n });\n }\n if (!(err instanceof AppError)) {\n // Following actions are only needed for non-AppError-like errors\n Object.defineProperties(err, {\n name: {\n value: name,\n configurable: true,\n writable: true,\n },\n data: {\n value: o.data,\n writable: true,\n configurable: true,\n enumerable: false,\n },\n cause: {\n value: cause,\n writable: true,\n configurable: true,\n enumerable: true,\n },\n });\n Object.defineProperty(err.constructor, 'name', {\n value: name,\n configurable: true,\n writable: true,\n });\n }\n return err;\n}\n// These \"common\" error classes will not be printed as part of the Error snippet\nconst commonErrorClasses = new Set([\n 'Error',\n 'AppError',\n 'AssertionError',\n 'HttpRequestError',\n 'JoiValidationError',\n]);\n/**\n * Provides a short semi-user-friendly error message snippet,\n * that would allow to give a hint to the user what went wrong,\n * also to developers and CS to distinguish between different errors.\n *\n * It's not supposed to have full information about the error, just a small extract from it.\n */\nexport function _errorSnippet(err, opt = {}) {\n const { maxLineLength = 60, maxLines = 3 } = opt;\n const e = _anyToErrorObject(err);\n const lines = [errorObjectToSnippet(e)];\n let { cause } = e;\n while (cause && lines.length < maxLines) {\n lines.push('Caused by ' + errorObjectToSnippet(cause));\n cause = cause.cause; // insert DiCaprio Inception meme\n }\n return lines.map(line => _truncate(line, maxLineLength)).join('\\n');\n function errorObjectToSnippet(e) {\n // Return snippet if it was already prepared\n if (e.data.snippet)\n return e.data.snippet;\n // Code already serves the purpose of the snippet, so we can just return it\n if (e.data.code)\n return e.data.code;\n return [\n !commonErrorClasses.has(e.name) && e.name,\n // replace \"1+ white space characters\" with a single space\n e.message.replaceAll(/\\s+/gm, ' ').trim(),\n ]\n .filter(Boolean)\n .join(': ');\n }\n}\n// These duck-typing checks read properties of an arbitrary object, which may invoke its\n// property getters, which may throw (e.g a stateful getter, a Proxy trap).\n// A type guard should never throw - an object whose properties cannot even be read safely\n// is, by definition, not a well-behaved Error-like - hence try/catch returning false.\n// try/catch is free in V8 unless it actually catches, so there's no performance penalty.\nexport function _isBackendErrorResponseObject(o) {\n try {\n return _isErrorObject(o?.error);\n }\n catch {\n return false;\n }\n}\nexport function _isHttpRequestErrorObject(o) {\n try {\n return !!o && o.name === 'HttpRequestError' && typeof o.data?.requestUrl === 'string';\n }\n catch {\n return false;\n }\n}\n/**\n * Note: any instance of AppError is also automatically an ErrorObject\n */\nexport function _isErrorObject(o) {\n try {\n return (!!o &&\n typeof o === 'object' &&\n typeof o.name === 'string' &&\n typeof o.message === 'string' &&\n typeof o.data === 'object');\n }\n catch {\n return false;\n }\n}\nexport function _isErrorLike(o) {\n try {\n return (!!o && typeof o === 'object' && typeof o.name === 'string' && typeof o.message === 'string');\n }\n catch {\n return false;\n }\n}\n/**\n * Convenience function to safely add properties to Error's `data` object\n * (even if it wasn't previously existing).\n * Mutates err.\n * Returns err for convenience, so you can re-throw it directly.\n *\n * @example\n *\n * try {} catch (err) {\n * throw _errorDataAppend(err, {\n * backendResponseStatusCode: 401,\n * })\n * }\n */\nexport function _errorDataAppend(err, data) {\n if (!data)\n return err;\n return _anyToError(err, undefined, data);\n}\n/**\n * Base class for all our (not system) errors.\n *\n * message - \"technical\" message. Frontend decides to show it or not.\n * data - optional \"any\" payload.\n * data.userFriendly - if present, will be displayed to the User as is.\n *\n * Based on: `https://medium.com/@xpl/javascript-deriving-from-error-properly-8d2f8f315801`\n */\nexport class AppError extends Error {\n data;\n /**\n * `cause` here is normalized to be an ErrorObject\n */\n cause;\n /**\n * Experimental alternative static constructor.\n */\n static of(opt) {\n return new AppError(opt.message, opt.data, {\n name: opt.name,\n cause: opt.cause,\n });\n }\n constructor(message, data = {}, opt = {}) {\n super(message);\n // Here we default to `this.constructor.name` on Node, but to 'AppError' on the Frontend\n // because Frontend tends to minify class names, so `constructor.name` is not reliable\n const { name = isServerSide() ? this.constructor.name : 'AppError', cause } = opt;\n Object.defineProperties(this, {\n name: {\n value: name,\n configurable: true,\n writable: true,\n },\n data: {\n value: data,\n writable: true,\n configurable: true,\n enumerable: false,\n },\n });\n if (cause) {\n Object.defineProperty(this, 'cause', {\n value: _anyToErrorObject(cause),\n writable: true,\n configurable: true,\n enumerable: true, // unlike standard - setting it to true for \"visibility\"\n });\n }\n else {\n delete this.cause; // otherwise it's printed as `cause: undefined`\n }\n // this is to allow changing this.constuctor.name to a non-minified version\n Object.defineProperty(this.constructor, 'name', {\n value: name,\n configurable: true,\n writable: true,\n });\n // todo: check if it's needed at all!\n // if (Error.captureStackTrace) {\n // Error.captureStackTrace(this, this.constructor)\n // } else {\n // Object.defineProperty(this, 'stack', {\n // value: new Error().stack, // eslint-disable-line unicorn/error-message\n // writable: true,\n // configurable: true,\n // })\n // }\n }\n}\n/**\n * Error that is thrown when Http Request was made and returned an error.\n * Thrown by, for example, Fetcher.\n *\n * On the Frontend this Error class represents the error when calling the API,\n * contains all the necessary request and response information.\n *\n * On the Backend, similarly, it represents the error when calling some 3rd-party API\n * (backend-to-backend call).\n * On the Backend it often propagates all the way to the Backend error handler,\n * where it would be wrapped in BackendErrorResponseObject.\n *\n * Please note that `ErrorData.backendResponseStatusCode` is NOT exactly the same as\n * `HttpRequestErrorData.responseStatusCode`.\n * E.g 3rd-party call may return 401, but our Backend will still wrap it into an 500 error\n * (by default).\n */\nexport class HttpRequestError extends AppError {\n constructor(message, data, opt) {\n if (data.response) {\n Object.defineProperty(data, 'response', {\n enumerable: false,\n });\n }\n super(message, data, { ...opt, name: 'HttpRequestError' });\n }\n}\nexport class AssertionError extends AppError {\n constructor(message, data) {\n super(message, data, { name: 'AssertionError' });\n }\n}\nexport class JsonParseError extends AppError {\n constructor(data) {\n const message = ['Failed to parse', data.text && _truncateMiddle(data.text, 200)]\n .filter(Boolean)\n .join(': ');\n super(message, data, { name: 'JsonParseError' });\n }\n}\nexport class TimeoutError extends AppError {\n constructor(message, data, opt) {\n super(message, data, { ...opt, name: 'TimeoutError' });\n }\n}\n/**\n * It is thrown when Error was expected, but didn't happen\n * (\"pass\" happened instead).\n * \"Pass\" means \"no error\".\n */\nexport class UnexpectedPassError extends AppError {\n constructor(message) {\n super(message || 'expected error was not thrown', {}, {\n name: 'UnexpectedPassError',\n });\n }\n}\n","/**\n * JSON.stringify that avoids circular references, prints them as [Circular ~]\n *\n * Based on: https://github.com/moll/json-stringify-safe/\n */\nexport function _safeJsonStringify(obj, replacer, spaces, cycleReplacer) {\n try {\n // Try native first (as it's ~3 times faster)\n return JSON.stringify(obj, replacer, spaces);\n }\n catch {\n // Native failed - resort to the \"safe\" serializer\n return JSON.stringify(obj, serializer(replacer, cycleReplacer), spaces);\n }\n}\nfunction serializer(replacer, cycleReplacer) {\n const stack = [];\n const keys = [];\n cycleReplacer ??= (_key, value) => {\n if (stack[0] === value)\n return '[Circular ~]';\n return '[Circular ~.' + keys.slice(0, stack.indexOf(value)).join('.') + ']';\n };\n return function (key, value) {\n if (stack.length > 0) {\n const thisPos = stack.indexOf(this);\n if (thisPos !== -1) {\n stack.splice(thisPos + 1);\n keys.splice(thisPos, Infinity, key);\n }\n else {\n stack.push(this);\n keys.push(key);\n }\n if (stack.includes(value)) {\n value = cycleReplacer.call(this, key, value);\n }\n }\n else {\n stack.push(value);\n }\n return replacer == null ? value : replacer.call(this, key, value);\n };\n}\n","// oxlint-disable-next-line import/no-cycle -- intentional cycle\nimport { _isBackendErrorResponseObject, _isErrorLike, _isErrorObject } from '../error/error.util.js';\n// oxlint-disable-next-line import/no-cycle -- intentional cycle\nimport { _jsonParseIfPossible } from './json.util.js';\nimport { _safeJsonStringify } from './safeJsonStringify.js';\nimport { _truncateMiddle } from './string.util.js';\nconst supportsAggregateError = typeof globalThis.AggregateError === 'function';\nlet globalStringifyFunction = _safeJsonStringify;\n/**\n * Allows to set Global \"stringifyFunction\" that will be used to \"pretty-print\" objects\n * in various cases.\n *\n * Used, for example, by _stringify() to pretty-print objects/arrays.\n *\n * Defaults to _safeJsonStringify.\n *\n * Node.js project can set it to _inspect, which allows to use `util.inspect`\n * as pretty-printing function.\n *\n * It's recommended that this function is circular-reference-safe.\n */\nexport function setGlobalStringifyFunction(fn) {\n globalStringifyFunction = fn;\n}\nexport function resetGlobalStringifyFunction() {\n globalStringifyFunction = _safeJsonStringify;\n}\n/**\n * Inspired by `_inspect` from nodejs-lib, which is based on util.inpect that is not available in the Browser.\n * Potentially can do this (with extra 2Kb gz size): https://github.com/deecewan/browser-util-inspect\n *\n * Transforms ANY to human-readable string (via JSON.stringify pretty).\n * Safe (no error throwing).\n *\n * Correctly prints Errors, AppErrors, ErrorObjects: error.message + \\n + _stringify(error.data)\n *\n * Enforces max length (default to 1000, pass 0 to skip it).\n *\n * Logs numbers as-is, e.g: `6`.\n * Logs strings as-is (without single quotes around, unlike default util.inspect behavior).\n * Otherwise - just uses JSON.stringify().\n *\n * Returns 'empty_string' if empty string is passed.\n * Returns 'undefined' if undefined is passed (default util.inspect behavior).\n */\nexport function _stringify(obj, opt = {}) {\n if (obj === undefined)\n return 'undefined';\n if (obj === null)\n return 'null';\n if (typeof obj === 'function')\n return 'function';\n if (typeof obj === 'symbol')\n return obj.toString();\n let s;\n // Parse JSON string, if possible\n obj = _jsonParseIfPossible(obj); // in case it's e.g non-pretty JSON, or even a stringified ErrorObject\n //\n // HttpErrorResponse\n //\n if (_isBackendErrorResponseObject(obj)) {\n return _stringify(obj.error, opt);\n }\n if (obj instanceof Error || _isErrorLike(obj)) {\n s = stringifyErrorLike(obj, opt);\n }\n else if (typeof obj === 'string') {\n s = obj.trim() || 'empty_string';\n // todo: think about it more\n // Stringifying it like a JSON would.\n // To highlight that it's a String (and not a Number) - using double-quotes, JSON-like.\n // s = `\"${obj}\"`\n }\n else if (typeof obj === 'number') {\n s = String(obj);\n // todo: support RegExp and Date, when split between Browser and Node stringification is implemented\n // } else if (obj instanceof RegExp) {\n // s = String(obj)\n // } else if (obj instanceof Date) {\n // s = `Date (${obj.toISOString()})`\n }\n else {\n //\n // Other\n //\n if (obj instanceof Map) {\n // todo: double-check it, maybe Node's inspect has good built-in stringification\n obj = Object.fromEntries(obj);\n }\n else if (obj instanceof Set) {\n obj = Array.from(obj);\n }\n try {\n const { stringifyFn = globalStringifyFunction } = opt;\n s = stringifyFn(obj, undefined, 2);\n }\n catch {\n s = String(obj); // fallback\n }\n }\n // Shouldn't happen, but some weird input parameters may return this\n if (s === undefined)\n return 'undefined';\n // Handle maxLen\n const { maxLen = 10_000 } = opt;\n if (maxLen && s.length > maxLen) {\n return _truncateMiddle(s, maxLen, `\\n... ${Math.ceil(s.length / 1024)} Kb message truncated ...\\n`);\n }\n return s;\n}\nfunction stringifyErrorLike(obj, opt) {\n const { includeErrorCause = true } = opt;\n let s = [obj.name, obj.message].filter(Boolean).join(': ');\n if (typeof obj.code === 'string') {\n // Error that has no `data`, but has `code` property\n s += `\\ncode: ${obj.code}`;\n }\n if (opt.includeErrorData && _isErrorObject(obj) && Object.keys(obj.data).length) {\n s += '\\n' + _stringify(obj.data, opt);\n }\n if (opt.includeErrorStack && obj.stack) {\n // Here we're using the previously-generated \"title line\" (e.g \"Error: some_message\"),\n // concatenating it with the Stack (but without the title line of the Stack)\n // This is to fix the rare error (happened with Got) where `err.message` was changed,\n // but err.stack had \"old\" err.message\n // This should \"fix\" that\n const sLines = s.split('\\n').length;\n s = [s, ...obj.stack.split('\\n').slice(sLines)].join('\\n');\n }\n if (supportsAggregateError && obj instanceof AggregateError && obj.errors.length) {\n s = [\n s,\n `${obj.errors.length} error(s):`,\n ...obj.errors.map((err, i) => `${i + 1}. ${_stringify(err, opt)}`),\n ].join('\\n');\n }\n if (obj.cause && includeErrorCause) {\n s = s + '\\nCaused by: ' + _stringify(obj.cause, opt);\n }\n return s;\n}\n","import { _deepEquals } from '../object/deepEquals.js';\nimport { _stringify } from '../string/stringify.js';\nimport { _isBackendErrorResponseObject, _isErrorObject, AssertionError } from './error.util.js';\n/**\n * Evaluates the `condition` (casts it to Boolean).\n * Expects it to be truthy, otherwise throws AppError.\n *\n * Should be used NOT for \"expected\" / user-facing errors, but\n * vice-versa - for completely unexpected and 100% buggy \"should never happen\" cases.\n *\n * It'll result in http 500 on the server (cause that's the right code for \"unexpected\" errors).\n * Pass { backendResponseStatusCode: x } at errorData argument to override the http code (will be picked up by backend-lib).\n *\n * API is similar to Node's assert(), except:\n * 1. Throws js-lib's AppError\n * 2. Has a default message, if not provided\n *\n * Since 2024-07-10 it no longer sets `userFriendly: true` by default.\n */\nexport function _assert(condition, // will be evaluated as Boolean\nmessage, errorData) {\n if (!condition) {\n throw new AssertionError(message || 'condition failed', {\n ...errorData,\n });\n }\n}\n/**\n * Like _assert(), but prints more helpful error message.\n * API is similar to Node's assert.equals().\n *\n * Does SHALLOW, but strict equality (===), use _assertDeepEquals() for deep equality.\n */\nexport function _assertEquals(actual, expected, message, errorData) {\n if (actual !== expected) {\n const msg = message ||\n ['not equal', `expected: ${_stringify(expected)}`, `got : ${_stringify(actual)}`]\n .filter(Boolean)\n .join('\\n');\n throw new AssertionError(msg, {\n ...errorData,\n });\n }\n}\n/**\n * Like _assert(), but prints more helpful error message.\n * API is similar to Node's assert.deepEquals().\n *\n * Does DEEP equality via _deepEquals()\n */\nexport function _assertDeepEquals(actual, expected, message, errorData) {\n if (!_deepEquals(actual, expected)) {\n const msg = message ||\n ['not deeply equal', `expected: ${_stringify(expected)}`, `got : ${_stringify(actual)}`]\n .filter(Boolean)\n .join('\\n');\n throw new AssertionError(msg, {\n ...errorData,\n });\n }\n}\nexport function _assertIsError(err, errorClass = Error) {\n if (!(err instanceof errorClass)) {\n throw new AssertionError(`Expected to be instanceof ${errorClass.name}, actual typeof: ${typeof err}`);\n }\n}\n/**\n * Asserts that passed object is indeed an Error of defined ErrorClass.\n * If yes - returns peacefully (with TypeScript assertion).\n * In not - throws (re-throws) that error up.\n */\nexport function _assertErrorClassOrRethrow(err, errorClass) {\n if (!(err instanceof errorClass)) {\n // re-throw\n throw err;\n }\n}\nexport function _assertIsErrorObject(obj) {\n if (!_isErrorObject(obj)) {\n throw new AssertionError(`Expected to be ErrorObject, actual typeof: ${typeof obj}`);\n }\n}\nexport function _assertIsBackendErrorResponseObject(obj) {\n if (!_isBackendErrorResponseObject(obj)) {\n throw new AssertionError(`Expected to be BackendErrorResponseObject, actual typeof: ${typeof obj}`);\n }\n}\nexport function _assertIsString(v, message) {\n _assertTypeOf(v, 'string', message);\n}\nexport function _assertIsNumber(v, message) {\n _assertTypeOf(v, 'number', message);\n}\nexport function _assertTypeOf(v, expectedType, message) {\n if (typeof v !== expectedType) {\n const msg = message || `Expected typeof ${expectedType}, actual typeof: ${typeof v}`;\n throw new AssertionError(msg);\n }\n}\n/**\n * Casts an arbitrary number as UnixTimestamp.\n * Right now does not perform any validation (unlike `asUnixTimestamp2000`),\n * but only type casting.\n */\nexport function asUnixTimestamp(n) {\n return n;\n}\nconst TS_2500 = 16725225600; // 2500-01-01\nconst TS_2000 = 946684800; // 2000-01-01\n/**\n * Casts an arbitrary number as UnixTimestamp2000.\n * Throws if the number is not inside 2000-01-01 and 2500-01-01 time interval,\n * which would indicate a bug.\n */\nexport function asUnixTimestamp2000(n) {\n if (!n || n < TS_2000 || n > TS_2500) {\n throw new AssertionError(`Number is not a valid UnixTimestamp2000: ${n}`, {\n fingerprint: 'asUnixTimestamp2000',\n });\n }\n return n;\n}\n","import { pDefer } from './pDefer.js';\n/**\n * Promisified version of setTimeout.\n *\n * Can return a value.\n * If value is instanceof Error - rejects the Promise instead of resolving.\n */\nexport async function pDelay(ms = 0, value) {\n return await new Promise((resolve, reject) => setTimeout(value instanceof Error ? reject : resolve, ms, value));\n}\n/**\n * Like pDelay, but also resolves early (without an error) as soon as\n * the passed AbortSignal aborts.\n */\nexport async function pDelaySignal(ms, signal) {\n if (signal?.aborted)\n return;\n await new Promise(resolve => {\n const timer = setTimeout(done, ms);\n function done() {\n clearTimeout(timer);\n signal?.removeEventListener('abort', done);\n resolve();\n }\n signal?.addEventListener('abort', done);\n });\n}\n/* oxlint-disable @typescript-eslint/promise-function-async */\n/**\n * Promisified version of setTimeout.\n *\n * Wraps the passed function with try/catch,\n * catch will propagate to pDelayFn rejection,\n * otherwise pDelayFn will resolve with returned value.\n *\n * On abort() - clears the Timeout and immediately resolves the Promise with void.\n */\nexport function pDelayFn(ms, fn) {\n const p = pDefer();\n const timer = setTimeout(async () => {\n try {\n p.resolve(await fn());\n }\n catch (err) {\n p.reject(err);\n }\n }, ms);\n p.abort = () => {\n clearTimeout(timer);\n // p.rejectAborted(reason) // nope\n p.resolve();\n };\n return p;\n}\n","/**\n * using _ = blockTimer()\n * // will log \"took 1.234 sec\" on dispose\n *\n * using _ = blockTimer('named')\n * // will log \"named took 1.234 sec\" on dispose\n *\n * @experimental\n */\nexport function _blockTimer(name) {\n const started = Date.now();\n return {\n [Symbol.dispose]() {\n console.log(`${name ? name + ' ' : ''}took ${_since(started)}`);\n },\n };\n}\n/**\n * Returns time passed since `from` until `until` (default to Date.now())\n */\nexport function _since(from, until = Date.now()) {\n return _ms(until - from);\n}\n/**\n * Returns, e.g:\n * 125 ms\n * 1.125 sec\n * 11 sec\n * 1m12s\n * 59m2s\n * 1h3m12s\n */\nexport function _ms(millis) {\n // <1 sec\n if (millis < 1000)\n return `${Math.round(millis)} ms`;\n // < 10 sec\n if (millis < 10_000) {\n const s = millis / 1000;\n return `${s.toFixed(2)} sec`;\n }\n const sec = Math.floor(millis / 1000) % 60;\n const min = Math.floor(millis / (60 * 1000)) % 60;\n const hrs = Math.floor(millis / (3600 * 1000));\n // <1 hr\n if (hrs === 0) {\n // <1 min\n if (min === 0)\n return `${sec} sec`;\n return `${min}m${sec}s`;\n }\n if (hrs < 24) {\n return `${hrs}h${min}m`;\n }\n if (hrs < 48) {\n return `${Math.round(hrs + min / 60)}h`;\n }\n // >= 48 hours\n const days = Math.floor(hrs / 24);\n return `${days} days`;\n}\n","export function _randomInt(minIncl, maxIncl) {\n return Math.floor(Math.random() * (maxIncl - minIncl + 1) + minIncl);\n}\n/**\n * Returns random item from an array.\n * Should be used on non-empty arrays! (otherwise will return undefined,\n * which is not reflected in the output type)\n */\nexport function _randomArrayItem(array) {\n return array[_randomInt(0, array.length - 1)];\n}\n/**\n * Convenience function to \"throttle\" some code - run it less often.\n *\n * @example\n *\n * if (_runLessOften(10)) {\n * // this code will run only 10% of the time\n * }\n */\nexport function _runLessOften(percent) {\n return Math.random() * 100 < percent;\n}\n// todo: _.random to support floats\n/**\n * _isBetween(-10, 1, 5) // false\n * _isBetween(1, 1, 5) // true\n * _isBetween(3, 1, 5) // true\n * _isBetween(5, 1, 5) // false\n * _isBetween(7, 1, 5) // false\n *\n * Also works with strings:\n * _isBetween('2020-01-03', '2020-01-01', '2020-01-05') // true\n */\nexport function _isBetween(x, min, max, incl) {\n if (x < min || x > max)\n return false;\n if (x === max && incl === '[)')\n return false;\n return true;\n}\nexport function _clamp(x, minIncl, maxIncl) {\n if (x <= minIncl)\n return minIncl;\n if (x >= maxIncl)\n return maxIncl;\n return x;\n}\n/**\n * Same as .toFixed(), but conveniently casts the output to Number.\n *\n * @example\n *\n * _toFixed(1.2345, 2)\n * // 1.23\n *\n * _toFixed(1.10, 2)\n * // 1.1\n */\nexport function _toFixed(n, fractionDigits) {\n return Number(n.toFixed(fractionDigits));\n}\n/**\n * Same as .toPrecision(), but conveniently casts the output to Number.\n *\n * @example\n *\n * _toPrecision(1634.56, 1)\n * // 2000\n *\n * _toPrecision(1634.56, 2)\n * // 1600\n */\nexport function _toPrecision(n, precision) {\n return Number(n.toPrecision(precision));\n}\n/**\n * @example\n *\n * _round(1634, 1000) // 2000\n * _round(1634, 500) // 1500\n * _round(1634, 100) // 1600\n * _round(1634, 10) // 1630\n * _round(1634, 1) // 1634\n * _round(1634.5678, 0.1) // 1634.6\n * _round(1634.5678, 0.01) // 1634.57\n */\nexport function _round(n, precisionUnit) {\n if (precisionUnit >= 1) {\n return Math.round(n / precisionUnit) * precisionUnit;\n }\n const v = Math.floor(n) + Math.round((n % 1) / precisionUnit) * precisionUnit;\n return Number(v.toFixed(String(precisionUnit).length - 2)); // '0.\n}\n","import { _errorDataAppend, TimeoutError } from '../error/error.util.js';\nimport { _typeCast } from '../types.js';\n/**\n * Decorates a Function with a timeout.\n * Returns a decorated Function.\n *\n * Throws an Error if the Function is not resolved in a certain time.\n * If the Function rejects - passes this rejection further.\n */\nexport function pTimeoutFn(fn, opt) {\n opt.name ||= fn.name;\n if (!opt.timeout) {\n return fn;\n }\n return async function pTimeoutInternalFn(...args) {\n return await pTimeout(() => fn.apply(this, args), opt);\n };\n}\n/**\n * Decorates a Function with a timeout and immediately calls it.\n *\n * Throws an Error if the Function is not resolved in a certain time.\n * If the Function rejects - passes this rejection further.\n */\nexport async function pTimeout(fn, opt) {\n const ac = new AbortController();\n const { signal } = ac;\n if (!opt.timeout) {\n // short-circuit to direct execution if 0 timeout is passed\n return await fn(signal);\n }\n const { timeout, name = fn.name || 'pTimeout function', onTimeout } = opt;\n const fakeError = opt.fakeError || new Error('TimeoutError');\n return await new Promise(async (resolve, reject) => {\n // Prepare the timeout timer\n const timer = setTimeout(() => {\n const err = new TimeoutError(`\"${name}\" timed out after ${timeout} ms`, opt.errorData);\n // keep original stack\n err.stack = fakeError.stack.replace('Error: TimeoutError', 'TimeoutError: ' + err.message);\n if (onTimeout) {\n try {\n resolve(onTimeout(err));\n }\n catch (err) {\n _typeCast(err);\n // keep original stack\n err.stack = fakeError.stack.replace('Error: TimeoutError', err.name + ': ' + err.message);\n // oxlint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject(_errorDataAppend(err, opt.errorData));\n }\n ac.abort(err);\n return;\n }\n reject(err);\n ac.abort(err);\n }, timeout);\n // Execute the Function\n try {\n resolve(await fn(signal));\n }\n catch (err) {\n // oxlint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject(err);\n }\n finally {\n clearTimeout(timer);\n }\n });\n}\n","/**\n * Parses `location.search` string (e.g `?a=1&b=2`) into a StringMap, e.g:\n * `{ a: '1', b: '2' }`\n *\n * Pass `location.search` to it in the Frontend, or any other string on the Backend (where `location.search` is not available).\n *\n * Works both with and without leading `?` character.\n *\n * Yes, there's `URLSearchParams` existing in the Frontend (not in Node yet), but it's API is not\n * as convenient. And the implementation here is super-small.\n *\n * Goal of this function is to produce exactly same output as URLSearchParams would.\n */\nexport function _parseQueryString(search) {\n const qs = {};\n search\n .slice(search.startsWith('?') ? 1 : 0)\n .split('&')\n .forEach(p => {\n const [k, v] = p.split('=');\n if (!k)\n return;\n qs[decodeURIComponent(k)] = decodeURIComponent(v || '');\n });\n return qs;\n}\n/**\n * A wrapper around `new URL(href)`, but it returns `null` instead of throwing an error.\n * While `URL.parse` exists, and behaves similarly, it's not widely supported.\n *\n * `null` was chosen instead of `undefined` in the return type union to make it easier to move to `URL.parse` if it ever becomes widely supported.\n */\nexport function _toUrlOrNull(url, base) {\n if (typeof url !== 'string')\n return null;\n try {\n return new URL(url, base || undefined);\n }\n catch {\n return null;\n }\n}\n","export const HTTP_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD'];\n","/// <reference lib=\"es2023\" preserve=\"true\" />\n/// <reference lib=\"dom\" preserve=\"true\" />\n/// <reference lib=\"dom.iterable\" preserve=\"true\" />\nimport { abortSignalAnyOrUndefined, abortSignalTimeoutOrUndefined } from '../abort.js';\nimport { _ms, _since } from '../datetime/time.util.js';\nimport { isServerSide } from '../env.js';\nimport { _assertErrorClassOrRethrow, _assertIsError } from '../error/assert.js';\nimport { _anyToError, _anyToErrorObject, _errorDataAppend, _errorLikeToErrorObject, HttpRequestError, UnexpectedPassError, } from '../error/error.util.js';\nimport { consoleLogger } from '../log/commonLogger.js';\nimport { _clamp } from '../number/number.util.js';\nimport { _filterFalsyValues, _filterNullishValues, _filterUndefinedValues, _mapKeys, _merge, _omit, _pick, } from '../object/object.util.js';\nimport { pDelaySignal } from '../promise/pDelay.js';\nimport { pTimeout } from '../promise/pTimeout.js';\nimport { _toUrlOrNull } from '../string/index.js';\nimport { _jsonParse, _jsonParseIfPossible } from '../string/json.util.js';\nimport { HTTP_METHODS } from './http.model.js';\n/**\n * Experimental wrapper around Fetch.\n * Works in both Browser and Node, using `globalThis.fetch`.\n */\nexport class Fetcher {\n /**\n * Included in UserAgent when run in Node.\n * In the browser it's not included, as we want \"browser own\" UserAgent to be included instead.\n *\n * Version is to be incremented every time a difference in behaviour (or a bugfix) is done.\n */\n static VERSION = 5;\n /**\n * userAgent is statically exposed as Fetcher.userAgent.\n * It can be modified globally, and will be used (read) at the start of every request.\n */\n static userAgent = isServerSide() ? `fetcher/${this.VERSION}` : undefined;\n constructor(cfg = {}) {\n if (typeof globalThis.fetch !== 'function') {\n throw new TypeError('globalThis.fetch is not available');\n }\n this.cfg = this.normalizeCfg(cfg);\n // Dynamically create all helper methods\n for (const method of HTTP_METHODS) {\n const m = method.toLowerCase();\n this[`${m}Void`] = async (url, opt) => {\n return await this.fetch({\n url,\n method,\n responseType: 'void',\n ...opt,\n });\n };\n if (method === 'HEAD') {\n continue; // responseType=text\n }\n ;\n this[`${m}Text`] = async (url, opt) => {\n return await this.fetch({\n url,\n method,\n responseType: 'text',\n ...opt,\n });\n };\n this[m] = async (url, opt) => {\n return await this.fetch({\n url,\n method,\n responseType: 'json',\n ...opt,\n });\n };\n }\n }\n /**\n * Add BeforeRequest hook at the end of the hooks list.\n */\n onBeforeRequest(hook) {\n ;\n (this.cfg.hooks.beforeRequest ||= []).push(hook);\n return this;\n }\n onAfterResponse(hook) {\n ;\n (this.cfg.hooks.afterResponse ||= []).push(hook);\n return this;\n }\n onBeforeRetry(hook) {\n ;\n (this.cfg.hooks.beforeRetry ||= []).push(hook);\n return this;\n }\n onError(hook) {\n ;\n (this.cfg.hooks.onError ||= []).push(hook);\n return this;\n }\n /**\n * Init hooks run lazily, once per Fetcher instance, before the first request.\n * See FetcherInitHook docs.\n */\n onInit(hook) {\n ;\n (this.cfg.hooks.init ||= []).push(hook);\n return this;\n }\n /**\n * Clears the cached result of the init hooks, so they re-run before the next request.\n * Useful when the state acquired during init (e.g an auth token) becomes stale.\n * See also `cfg.hooks.shouldReinit`, which calls this automatically.\n */\n resetInit() {\n this.initPromise = undefined;\n this.initGeneration++;\n }\n cfg;\n initPromise;\n initGeneration = 0;\n static create(cfg = {}) {\n return new Fetcher(cfg);\n }\n // These methods are generated dynamically in the constructor\n // These default methods use responseType=json\n get;\n post;\n put;\n patch;\n delete;\n // responseType=text\n getText;\n postText;\n putText;\n patchText;\n deleteText;\n // responseType=void (no body fetching/parsing)\n getVoid;\n postVoid;\n putVoid;\n patchVoid;\n deleteVoid;\n headVoid;\n /**\n * Small convenience wrapper that allows to issue GraphQL queries.\n * In practice, all it does is:\n * - Defines convenience `query` input option\n * - Unwraps `response.data`\n * - Unwraps `response.errors` and throws, if it's defined (as GQL famously returns http 200 even for errors)\n *\n * Currently it only unwraps and uses the first error from the `errors` array, for simplicity.\n */\n async queryGraphQL(opt) {\n opt = { ...opt }; // avoid mutating the input options\n opt.method ||= this.cfg.init.method; // defaults to GET\n const payload = _filterFalsyValues({\n query: opt.query,\n variables: opt.variables,\n });\n // Checking the query length, and not allowing to use GET if above 1900\n if (opt.method === 'GET' && opt.query.length > 1900) {\n opt.method = 'POST';\n }\n if (opt.method === 'GET') {\n opt.searchParams = {\n ...opt.searchParams,\n ...payload,\n };\n }\n else {\n opt.json = payload;\n }\n const res = await this.doFetch(opt);\n if (res.err) {\n throw res.err;\n }\n if (res.body.errors) {\n // unwrap errors and throw\n const err = res.body.errors[0];\n // todo: consider creating a new GraphQLError class for this\n throw new HttpRequestError(err.message, {\n ...payload, // query and variables\n errors: res.body.errors, // full errors payload returned\n response: res.fetchResponse,\n responseStatusCode: res.statusCode,\n requestUrl: res.req.fullUrl,\n requestBaseUrl: this.cfg.baseUrl,\n requestMethod: res.req.init.method,\n requestSignature: res.signature,\n requestName: res.req.requestName,\n fetcherName: this.cfg.name,\n requestDuration: Date.now() - res.req.started,\n });\n }\n const { data } = res.body;\n if (opt.unwrapObject) {\n return data[opt.unwrapObject];\n }\n return data;\n }\n // responseType=bytes\n /**\n * Returns response body as Uint8Array.\n */\n async getBytes(url, opt) {\n return await this.fetch({\n url,\n responseType: 'bytes',\n ...opt,\n });\n }\n // responseType=readableStream\n /**\n * Returns raw fetchResponse.body, which is a ReadableStream<Uint8Array>\n *\n * More on streams and Node interop:\n * https://css-tricks.com/web-streams-everywhere-and-fetch-for-node-js/\n */\n async getReadableStream(url, opt) {\n return await this.fetch({\n url,\n responseType: 'readableStream',\n ...opt,\n });\n }\n async fetch(opt) {\n const res = await this.doFetch(opt);\n if (res.err && (res.req.throwHttpErrors || res.fetchResponse?.ok !== false)) {\n // With throwHttpErrors=false only http errors (response received, but !ok) are returned instead of thrown.\n // Other errors (network failure, timeout, body parsing) are still thrown.\n throw res.err;\n }\n return res.body;\n }\n /**\n * Like `fetch`, but returns the whole FetcherSuccessResponse, not just the body.\n * Allows to access response metadata, e.g `fetchResponse.headers` and `statusCode`,\n * while still throwing on errors (unlike `doFetch`).\n *\n * Note: `throwHttpErrors: false` is ignored here, http errors are always thrown -\n * otherwise the returned FetcherSuccessResponse type would lie.\n * Use `doFetch` if you don't want throwing.\n */\n async fetchWithMeta(opt) {\n const res = await this.doFetch(opt);\n if (res.err) {\n throw res.err;\n }\n return res;\n }\n /**\n * Execute fetch and expect/assert it to return an Error (which will be wrapped in\n * HttpRequestError as it normally would).\n * If fetch succeeds, which is unexpected, it'll throw an UnexpectedPass error.\n * Useful in unit testing.\n */\n async expectError(opt) {\n const res = await this.doFetch(opt);\n if (!res.err) {\n throw new UnexpectedPassError('Fetch was expected to error');\n }\n _assertIsError(res.err, HttpRequestError);\n return res.err;\n }\n /**\n * Like pTry - returns a [err, data] tuple (aka ErrorDataTuple).\n * err, if defined, is strictly HttpRequestError.\n * UPD: actually not, err is typed as Error, as it feels unsafe to guarantee error type.\n * UPD: actually yes - it will return HttpRequestError, and throw if there's an error\n * of any other type.\n */\n async tryFetch(opt) {\n const res = await this.doFetch(opt);\n if (res.err) {\n _assertErrorClassOrRethrow(res.err, HttpRequestError);\n return [res.err, null];\n }\n return [null, res.body];\n }\n /**\n * Returns FetcherResponse.\n * Never throws, returns `err` property in the response instead.\n * (Exception: errors thrown from init/beforeRequest hooks are re-thrown as-is.)\n * Use this method instead of `throwHttpErrors: false` or try-catching.\n *\n * Note: responseType defaults to the Fetcher's cfg responseType (`json`, unless overridden).\n */\n async doFetch(opt) {\n let initGeneration = 0;\n if (this.cfg.hooks.init) {\n try {\n await (this.initPromise ??= this.runInitHooks());\n }\n catch (err) {\n // Reset, so init hooks are re-attempted on the next request\n this.resetInit();\n throw err;\n }\n initGeneration = this.initGeneration;\n }\n const req = this.normalizeOptions(opt);\n const { logger } = this.cfg;\n const { init: { method }, } = req;\n const timeoutMillis = req.timeoutSeconds ? req.timeoutSeconds * 1000 : undefined;\n for (const hook of this.cfg.hooks.beforeRequest || []) {\n await hook(req);\n }\n const isFullUrl = req.fullUrl.includes('://');\n const fullUrl = isFullUrl ? new URL(req.fullUrl) : undefined;\n const shortUrl = fullUrl ? this.getShortUrl(fullUrl) : req.fullUrl;\n const signature = [method, shortUrl].join(' ');\n const res = {\n req,\n retryStatus: {\n retryAttempt: 0,\n retryStopped: false,\n retryTimeout: req.retry.timeout,\n },\n signature,\n };\n while (!res.retryStatus.retryStopped) {\n req.started = Date.now();\n res.body = undefined;\n req.init.signal = abortSignalAnyOrUndefined([\n abortSignalTimeoutOrUndefined(timeoutMillis),\n opt.signal,\n ]);\n if (req.logRequest) {\n const { retryAttempt } = res.retryStatus;\n logger.log([' >>', signature, retryAttempt && `try#${retryAttempt + 1}/${req.retry.count + 1}`]\n .filter(Boolean)\n .join(' '));\n if (req.logRequestBody && req.init.body) {\n logger.log({ body: req.init.body }); // todo: check if we can _inspect it\n }\n }\n try {\n res.fetchResponse = await (req.overrideFetchFn || Fetcher.callNativeFetch)(req.fullUrl, req.init, req.fetchFn);\n res.ok = res.fetchResponse.ok;\n // important to set it to undefined, otherwise it can keep the previous value (from previous try)\n res.err = undefined;\n }\n catch (err) {\n // For example, CORS error would result in \"TypeError: failed to fetch\" here\n // or, `fetch failed` with the cause of `unexpected redirect`\n // AbortSignal.timeout() throws a DOMException with name \"TimeoutError\"\n res.err = _anyToError(err);\n res.ok = false;\n // important to set it to undefined, otherwise it can keep the previous value (from previous try)\n res.fetchResponse = undefined;\n }\n res.statusFamily = this.getStatusFamily(res);\n res.statusCode = res.fetchResponse?.status;\n if (res.fetchResponse?.ok) {\n try {\n // We are applying a separate Timeout (as long as original Timeout for now) to \"download and parse the body\"\n await pTimeout(async () => await this.onOkResponse(res), {\n // 0 means \"no timeout\" for pTimeout\n timeout: timeoutMillis ?? 0,\n name: 'Fetcher.downloadBody',\n });\n }\n catch (err) {\n // Important to cancel the original request to not keep it running (and occupying resources)\n // UPD: no, we probably don't need to, because \"request\" has already completed, it's just the \"body\" is pending\n // if (err instanceof TimeoutError) {}\n // onOkResponse can still fail, e.g when loading/parsing json, text or doing other response manipulation\n res.err = _anyToError(err);\n res.ok = false;\n await this.onNotOkResponse(res);\n }\n }\n else {\n // !res.ok\n await this.onNotOkResponse(res);\n }\n }\n if (res.err) {\n _errorDataAppend(res.err, req.errorData);\n req.onError?.(res.err);\n for (const hook of this.cfg.hooks.onError || []) {\n await hook(res.err);\n }\n }\n for (const hook of this.cfg.hooks.afterResponse || []) {\n await hook(res);\n }\n if (res.err && (await this.detectStaleInit(opt, res, initGeneration))) {\n // Stale init (e.g expired auth token) was detected and reset - retry the request once\n return await this.doFetch({ ...opt, [reinitAttempted]: true });\n }\n return res;\n }\n /**\n * Consults cfg.hooks.shouldReinit to detect \"stale init\" (e.g expired auth token).\n * If detected - resets the init (so it re-runs) and returns true,\n * telling the caller to retry the request. At most once per request.\n */\n async detectStaleInit(opt, res, initGeneration) {\n const { shouldReinit, init } = this.cfg.hooks;\n if (!shouldReinit || !init)\n return false;\n if (opt[reinitAttempted])\n return false;\n if (!(await shouldReinit(res)))\n return false;\n // Generation check prevents concurrent stale requests from resetting the already-fresh init\n if (initGeneration === this.initGeneration) {\n this.resetInit();\n }\n return true;\n }\n async runInitHooks() {\n for (const hook of this.cfg.hooks.init || []) {\n await hook(this.cfg);\n }\n }\n async onOkResponse(res) {\n const { req } = res;\n const { responseType } = res.req;\n // This function is subject to a separate timeout to \"download and parse the data\"\n if (responseType === 'json') {\n if (res.fetchResponse.body) {\n const text = await res.fetchResponse.text();\n if (text) {\n res.body = text;\n res.body = _jsonParse(text, req.jsonReviver);\n // Error while parsing json can happen - it'll be handled upstream\n }\n else {\n // Body had a '' (empty string)\n res.body = {};\n }\n }\n else {\n // if no body: set responseBody as {}\n // do not throw a \"cannot parse null as Json\" error\n res.body = {};\n }\n }\n else if (responseType === 'text') {\n res.body = res.fetchResponse.body ? await res.fetchResponse.text() : '';\n }\n else if (responseType === 'arrayBuffer') {\n res.body = res.fetchResponse.body ? await res.fetchResponse.arrayBuffer() : new ArrayBuffer(0);\n }\n else if (responseType === 'bytes') {\n // Not using fetchResponse.bytes(), as it's unavailable in older browsers (e.g Safari <18.4)\n res.body = res.fetchResponse.body\n ? new Uint8Array(await res.fetchResponse.arrayBuffer())\n : new Uint8Array();\n }\n else if (responseType === 'blob') {\n res.body = res.fetchResponse.body ? await res.fetchResponse.blob() : new Blob();\n }\n else if (responseType === 'void') {\n // Cancel the body (without downloading it), to free the underlying connection for reuse\n await res.fetchResponse.body?.cancel();\n }\n else if (responseType === 'readableStream') {\n res.body = res.fetchResponse.body;\n if (res.body === null) {\n // Error is to be handled upstream\n throw new Error('fetchResponse.body is null');\n }\n }\n res.retryStatus.retryStopped = true;\n if (req.logResponse) {\n const { retryAttempt } = res.retryStatus;\n const { logger } = this.cfg;\n logger.log([\n ' <<',\n res.fetchResponse.status,\n res.signature,\n retryAttempt && `try#${retryAttempt + 1}/${req.retry.count + 1}`,\n _since(res.req.started),\n ]\n .filter(Boolean)\n .join(' '));\n if (req.logResponseBody && res.body !== undefined) {\n logger.log({ body: res.body });\n }\n }\n }\n /**\n * This method exists to be able to easily mock it.\n * It is static, so mocking applies to ALL instances (even future ones) of Fetcher at once.\n */\n static async callNativeFetch(url, init, fetchFn) {\n return await (fetchFn || globalThis.fetch)(url, init);\n }\n async onNotOkResponse(res) {\n let cause;\n // Try to fetch body and attach to res.body\n // (but don't fail if it doesn't work)\n if (!res.body && res.fetchResponse) {\n try {\n res.body = _jsonParseIfPossible(await res.fetchResponse.text());\n }\n catch {\n // ignore body fetching/parsing errors at this point\n }\n }\n if (res.err) {\n // This is only possible on JSON.parse error, or CORS error,\n // or `unexpected redirect`\n // This check should go first, to avoid calling .text() twice (which will fail)\n cause = _errorLikeToErrorObject(res.err);\n }\n else if (res.body) {\n cause = _anyToErrorObject(res.body);\n }\n else {\n cause = {\n name: 'Error',\n message: 'Fetch failed',\n data: {},\n };\n }\n let responseStatusCode = res.fetchResponse?.status || 0;\n if (res.statusFamily === 2) {\n // important to reset responseStatusCode to 0 in this case, as status 2xx can be misleading\n res.statusFamily = undefined;\n res.statusCode = undefined;\n responseStatusCode = 0;\n }\n const message = [res.statusCode, res.signature].filter(Boolean).join(' ');\n res.err = new HttpRequestError(message, _filterNullishValues({\n response: res.fetchResponse,\n responseStatusCode,\n // These properties are provided to be used in e.g custom Sentry error grouping\n // Actually, disabled now, to avoid unnecessary error printing when both msg and data are printed\n // Enabled, cause `data` is not printed by default when error is HttpError\n // method: req.method,\n // tryCount: req.tryCount,\n requestUrl: res.req.fullUrl,\n requestBaseUrl: this.cfg.baseUrl || undefined,\n requestMethod: res.req.init.method,\n requestSignature: res.signature,\n requestName: res.req.requestName,\n fetcherName: this.cfg.name,\n requestDuration: Date.now() - res.req.started,\n }), {\n cause,\n });\n await this.processRetry(res);\n }\n async processRetry(res) {\n const { retryStatus } = res;\n if (!this.shouldRetry(res)) {\n retryStatus.retryStopped = true;\n }\n for (const hook of this.cfg.hooks.beforeRetry || []) {\n await hook(res);\n }\n const { count, timeoutMultiplier, timeoutMax } = res.req.retry;\n if (retryStatus.retryAttempt >= count) {\n retryStatus.retryStopped = true;\n }\n // We don't log \"last error\", because it will be thrown and logged by consumer,\n // but we should log all previous errors, otherwise they are lost.\n // Here is the right place where we know it's not the \"last error\".\n // lastError = retryStatus.retryStopped\n // We need to log the response \"anyway\" if logResponse is true\n if (res.err && (!retryStatus.retryStopped || res.req.logResponse)) {\n this.cfg.logger.error({\n msg: [\n ' <<',\n res.fetchResponse?.status || 0,\n res.signature,\n count &&\n (retryStatus.retryAttempt || !retryStatus.retryStopped) &&\n `try#${retryStatus.retryAttempt + 1}/${count + 1}`,\n _since(res.req.started),\n ]\n .filter(Boolean)\n .join(' '),\n err: res.err.cause || res.err,\n });\n }\n if (retryStatus.retryStopped)\n return;\n retryStatus.retryAttempt++;\n const timeout = this.getRetryTimeout(res);\n if (timeout === null) {\n this.cfg.logger.warn(`${res.signature} server-indicated delay exceeds maxRetryAfter, will not retry`);\n retryStatus.retryStopped = true;\n return;\n }\n // Increase the timeout for the next possible retry\n retryStatus.retryTimeout = _clamp(retryStatus.retryTimeout * timeoutMultiplier, 0, timeoutMax);\n if (res.req.debug) {\n this.cfg.logger.log(` .. ${res.signature} waiting ${_ms(timeout)}`);\n }\n await pDelaySignal(timeout, res.req.signal);\n if (res.req.signal?.aborted) {\n // Aborted while waiting for the retry - stop, without issuing another request\n retryStatus.retryStopped = true;\n }\n }\n /**\n * Returns the delay before the next retry attempt.\n * Returns null if the server-indicated delay exceeds `retry.maxRetryAfter`,\n * meaning the retry should not be attempted at all.\n */\n getRetryTimeout(res) {\n let timeout = 0;\n // Handling http 429 with specific retry headers\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After\n if (res.fetchResponse && [429, 503].includes(res.fetchResponse.status)) {\n const retryAfterStr = res.fetchResponse.headers.get('retry-after') ??\n res.fetchResponse.headers.get('x-ratelimit-reset');\n if (retryAfterStr) {\n const retryAfterNumber = Number(retryAfterStr);\n if (retryAfterNumber) {\n if (retryAfterNumber > 10 ** 9) {\n // Value is too large to be a \"seconds from now\" delay,\n // treat it as a UnixTimestamp instead (e.g GitHub sends `x-ratelimit-reset` like that)\n timeout = retryAfterNumber * 1000 - Date.now();\n }\n else {\n timeout = retryAfterNumber * 1000;\n }\n }\n else {\n const date = new Date(retryAfterStr);\n if (!Number.isNaN(date.getTime())) {\n timeout = date.getTime() - Date.now();\n }\n }\n this.cfg.logger.log(`retry-after: ${retryAfterStr}`);\n if (!timeout) {\n this.cfg.logger.warn('retry-after could not be parsed');\n }\n }\n }\n if (timeout) {\n if (timeout > res.req.retry.maxRetryAfter) {\n return null;\n }\n // Server-indicated delay is honored as-is (a negative value means \"retry now\")\n return Math.max(0, timeout);\n }\n const noise = Math.random() * 500;\n return res.retryStatus.retryTimeout + noise;\n }\n /**\n * Default is yes,\n * unless there's reason not to (e.g method is POST).\n *\n * statusCode of 0 (or absense of it) will BE retried.\n */\n shouldRetry(res) {\n // Don't retry if the input AbortSignal was aborted\n if (res.req.signal?.aborted)\n return false;\n const { retryPost, retry3xx, retry4xx, retry5xx } = res.req;\n const { method } = res.req.init;\n if (method === 'POST' && !retryPost)\n return false;\n const { statusFamily } = res;\n const statusCode = res.fetchResponse?.status || 0;\n if (statusFamily === 5 && !retry5xx)\n return false;\n if ([408, 429].includes(statusCode)) {\n // these codes are always retried\n return true;\n }\n if (statusFamily === 4 && !retry4xx)\n return false;\n if (statusFamily === 3 && !retry3xx)\n return false;\n // should not retry on `unexpected redirect` in error.cause.cause\n if (res.err?.cause?.cause?.message?.includes('unexpected redirect')) {\n return false;\n }\n return true; // default is true\n }\n getStatusFamily(res) {\n const status = res.fetchResponse?.status;\n if (!status)\n return;\n if (status >= 500)\n return 5;\n if (status >= 400)\n return 4;\n if (status >= 300)\n return 3;\n if (status >= 200)\n return 2;\n if (status >= 100)\n return 1;\n }\n /**\n * Returns url without baseUrl and before ?queryString\n */\n getShortUrl(url) {\n const { baseUrl } = this.cfg;\n if (url.password) {\n url = new URL(url.toString()); // prevent original url mutation\n url.password = '[redacted]';\n }\n let shortUrl = url.toString();\n if (!this.cfg.logWithSearchParams) {\n shortUrl = shortUrl.split('?')[0];\n }\n if (!this.cfg.logWithBaseUrl && baseUrl && shortUrl.startsWith(baseUrl)) {\n shortUrl = shortUrl.slice(baseUrl.length);\n }\n return shortUrl;\n }\n normalizeCfg(cfg) {\n const { debug = false, logger = consoleLogger } = cfg;\n if (cfg.baseUrl?.endsWith('/')) {\n logger.warn(`Fetcher: baseUrl should not end with slash: ${cfg.baseUrl}`);\n cfg.baseUrl = cfg.baseUrl.slice(0, cfg.baseUrl.length - 1);\n }\n const norm = _merge({\n baseUrl: '',\n name: this.getFetcherName(cfg),\n inputUrl: '',\n responseType: 'json',\n searchParams: {},\n timeoutSeconds: 30,\n retryPost: false,\n retry3xx: false,\n retry4xx: false,\n retry5xx: true,\n logger,\n debug,\n logRequest: debug,\n logRequestBody: debug,\n logResponse: debug,\n logResponseBody: debug,\n logWithBaseUrl: isServerSide(),\n logWithSearchParams: true,\n retry: { ...defaultRetryOptions },\n init: {\n method: cfg.method || 'GET',\n headers: _filterNullishValues({\n 'user-agent': Fetcher.userAgent,\n ...cfg.headers,\n }),\n credentials: cfg.credentials,\n redirect: cfg.redirect,\n dispatcher: cfg.dispatcher,\n keepalive: cfg.keepalive,\n },\n hooks: {},\n throwHttpErrors: true,\n errorData: {},\n }, _omit(cfg, ['method', 'credentials', 'headers', 'redirect', 'logger', 'name', 'keepalive']));\n norm.init.headers = _mapKeys(norm.init.headers, k => k.toLowerCase());\n return norm;\n }\n getFetcherName(cfg) {\n let { name } = cfg;\n if (!name && cfg.baseUrl) {\n // derive FetcherName from baseUrl\n const url = _toUrlOrNull(cfg.baseUrl);\n if (url) {\n name = url.hostname;\n }\n }\n return name;\n }\n normalizeOptions(opt) {\n const req = {\n ..._pick(this.cfg, [\n 'timeoutSeconds',\n 'retryPost',\n 'retry3xx',\n 'retry4xx',\n 'retry5xx',\n 'responseType',\n 'jsonReviver',\n 'logRequest',\n 'logRequestBody',\n 'logResponse',\n 'logResponseBody',\n 'debug',\n 'throwHttpErrors',\n 'errorData',\n 'fetchFn',\n 'overrideFetchFn',\n ]),\n started: Date.now(),\n ..._omit(opt, ['method', 'headers', 'credentials']),\n inputUrl: opt.url || '',\n fullUrl: opt.url || '',\n retry: {\n ...this.cfg.retry,\n ..._filterUndefinedValues(opt.retry || {}),\n },\n init: _merge({\n ...this.cfg.init,\n headers: {\n ...this.cfg.init.headers, // this avoids mutation\n 'user-agent': Fetcher.userAgent, // re-load it here, to support setting it globally post-fetcher-creation\n },\n method: opt.method || this.cfg.init.method,\n credentials: opt.credentials || this.cfg.init.credentials,\n redirect: opt.redirect || this.cfg.init.redirect || 'follow',\n keepalive: opt.keepalive ?? this.cfg.init.keepalive,\n }, {\n headers: _mapKeys(opt.headers || {}, k => k.toLowerCase()),\n }),\n };\n // Because all header values are stringified, so `a: undefined` becomes `undefined` as a string\n _filterNullishValues(req.init.headers, { mutate: true });\n // setup url\n const baseUrl = opt.baseUrl || this.cfg.baseUrl;\n if (baseUrl) {\n let { inputUrl } = req;\n if (inputUrl.startsWith('/')) {\n this.cfg.logger.warn('Fetcher: url should not start with / when baseUrl is specified');\n inputUrl = inputUrl.slice(1);\n }\n req.fullUrl = `${baseUrl}/${inputUrl}`;\n }\n const searchParams = _filterUndefinedValues({\n ...this.cfg.searchParams,\n ...opt.searchParams,\n });\n if (Object.keys(searchParams).length) {\n const qs = new URLSearchParams(searchParams).toString();\n req.fullUrl += (req.fullUrl.includes('?') ? '&' : '?') + qs;\n }\n // setup request body\n // Unless it's a well-defined input type (json, text) - content-type is set automatically by the native fetch\n // Explicitly passed `content-type` header always wins\n if (opt.json !== undefined) {\n req.init.body = JSON.stringify(opt.json);\n req.init.headers['content-type'] ||= 'application/json';\n }\n else if (opt.text !== undefined) {\n req.init.body = opt.text;\n req.init.headers['content-type'] ||= 'text/plain';\n }\n else if (opt.form) {\n if (opt.form instanceof URLSearchParams || opt.form instanceof FormData) {\n req.init.body = opt.form;\n }\n else {\n req.init.body = new URLSearchParams(opt.form);\n req.init.headers['content-type'] ||= 'application/x-www-form-urlencoded';\n }\n }\n else if (opt.body !== undefined) {\n req.init.body = opt.body;\n }\n // Unless `accept` header was already set - set it based on responseType\n req.init.headers['accept'] ||= acceptByResponseType[req.responseType];\n return req;\n }\n}\nexport function getFetcher(cfg = {}) {\n return Fetcher.create(cfg);\n}\n// Marks FetcherOptions of a request that was already retried due to a reinit,\n// to guarantee at most one reinit per request\nconst reinitAttempted = Symbol('reinitAttempted');\nconst acceptByResponseType = {\n text: 'text/plain',\n json: 'application/json',\n void: '*/*',\n readableStream: 'application/octet-stream',\n arrayBuffer: 'application/octet-stream',\n bytes: 'application/octet-stream',\n blob: 'application/octet-stream',\n};\nconst defaultRetryOptions = {\n count: 2,\n timeout: 1000,\n timeoutMax: 30_000,\n timeoutMultiplier: 2,\n maxRetryAfter: 600_000, // 10 minutes\n};\n","/**\n * Data privacy checklist for quiz-style UX, e.g. onboarding quiz, also applicable to special pages like period calculator.\n * - Does the quiz state or imply sensitive data? If yes, next items?\n * - E.g. Cycle length, medical conditions, contraceptive choice\n * - Do we need marketing pixels on this page?\n * - If it’s not a high-value page, the simplest solution can be to add the page to the exclusion list to disable triggering of pixels altogether. E.g.Most pages in the on-boarding quiz are excluded based on this necessity test.\n * - If it is a high-value page, we need to perform some extra checks to confirm that sensitive data is not being shared\n * - Avoid having title / URL of next page being the answer of the question on the previous page as that is generally shared with pixels\n * - Inspect pixel behavior (e.g. using network tab) to confirm that sensitive data is not sent.\n * - Confirm that clicked button captions (text) is not sent - NC pixels should NOT capture button copy\n */\nexport const domainPathKeywordSuppressionMap = {\n 'https://www.naturalcycles.com/': [\n 'shop',\n 'research-library',\n 'plan-pregnancy',\n 'postpartum',\n 'cyclematters/period-calculator',\n 'cyclematters/search',\n 'cyclematters/perimenopause-quiz',\n ],\n 'https://www.naturalcycles.me/': [],\n 'https://signup.naturalcycles.com/': ['account', 'onboarding'],\n 'https://se.naturalcycles.com/': [],\n 'https://br.naturalcycles.com/': [],\n 'https://uk.naturalcycles.com/': [],\n};\nexport const debugDomainMap = {\n 'http://localhost:8000': 'https://www.naturalcycles.com/',\n 'http://localhost:8001': 'https://www.naturalcycles.me/',\n 'http://localhost:4200': 'https://signup.naturalcycles.com/',\n};\nexport const allowedDomains = [\n 'https://www.naturalcycles.com/',\n 'https://www.naturalcycles.me/',\n 'https://signup.naturalcycles.com/',\n 'https://se.naturalcycles.com/',\n 'https://br.naturalcycles.com/',\n 'https://uk.naturalcycles.com/',\n];\n","/**\n * Query parameter keys used by WebSignup\n */\nexport var WebSignupQueryParam;\n(function (WebSignupQueryParam) {\n WebSignupQueryParam[\"flow\"] = \"flow\";\n WebSignupQueryParam[\"code\"] = \"code\";\n WebSignupQueryParam[\"refId\"] = \"refId\";\n WebSignupQueryParam[\"referral\"] = \"referral\";\n /**\n * @deprecated Use \"ic\" instead\n */\n WebSignupQueryParam[\"ignoreConfirmation\"] = \"ignoreConfirmation\";\n WebSignupQueryParam[\"ic\"] = \"ic\";\n WebSignupQueryParam[\"measuringDevice\"] = \"measuringDevice\";\n /**\n * Passed by Impact in the URL\n */\n WebSignupQueryParam[\"irclickid\"] = \"irclickid\";\n /**\n * Fertility goal\n */\n WebSignupQueryParam[\"fg\"] = \"fg\";\n /**\n * Skip fertility goal boolean used for the cycle matters fertility goal component AB test\n */\n WebSignupQueryParam[\"sfg\"] = \"sfg\";\n /**\n * Skip entire quiz, go directly to wearable selection.\n */\n WebSignupQueryParam[\"sq\"] = \"sq\";\n /**\n * Clearblue offer\n */\n WebSignupQueryParam[\"cbo\"] = \"cbo\";\n /**\n * The chosen insurance provider option (InsuranceProviderOption enum)\n */\n WebSignupQueryParam[\"ip\"] = \"ip\";\n /**\n * The chosen insurance provider variant\n *\n * For BlueCross BlueShield, this will likely be an item in the list\n * of BCBS variants but can be any inputted string.\n * For other providers, this will likely be an item in the list of other providers,\n * but can also be any inputted string. Just intended for analytics.\n */\n WebSignupQueryParam[\"ipv\"] = \"ipv\";\n /**\n * Added by the apple auth sign in flow\n */\n WebSignupQueryParam[\"appleAuth\"] = \"appleAuth\";\n /**\n * Added by the google auth sign in flow (redirect mode for WebView)\n */\n WebSignupQueryParam[\"googleAuth\"] = \"googleAuth\";\n /**\n * Owns device. Used to determine if the owns the measuring device for flows starting on the plans page.\n * Eg. Email verification on web flow\n */\n WebSignupQueryParam[\"od\"] = \"od\";\n /**\n * Plan\n * The plan which the user has selected.\n * Used in the flow where the user is redirected to WebSignup from the app for payment.\n */\n WebSignupQueryParam[\"pl\"] = \"pl\";\n /**\n * Passed by Snapchat ads in the URL\n */\n WebSignupQueryParam[\"ScCid\"] = \"ScCid\";\n /**\n * Passed by Meta ads in the URL\n */\n WebSignupQueryParam[\"fbclid\"] = \"fbclid\";\n /**\n * Passed by TikTok ads in the URL\n */\n WebSignupQueryParam[\"ttclid\"] = \"ttclid\";\n /**\n * Passed by Reddit ads in the URL\n */\n WebSignupQueryParam[\"rdt_cid\"] = \"rdt_cid\";\n /**\n * Passed by Pinterest ads in the URL\n */\n WebSignupQueryParam[\"epik\"] = \"epik\";\n /**\n * Adjust ID\n * Passed from the app when a user is coming from to the app to the web to pay\n */\n WebSignupQueryParam[\"adid\"] = \"adid\";\n /**\n * Whoop connection failed\n */\n WebSignupQueryParam[\"wcf\"] = \"wcf\";\n /**\n * Whoop eligibility. Value is 'false' when the user is not eligible for the free trial.\n */\n WebSignupQueryParam[\"we\"] = \"we\";\n /**\n * Whoop eligibility rejection reason(s). Only present when `we` is 'false'. Comma-separated\n * `WhoopFreeTrialFailedCriterion` values, e.g. 'NOT_NC_COUNTRY,NOT_COMPATIBLE_DEVICE'.\n */\n WebSignupQueryParam[\"werr\"] = \"werr\";\n /**\n * Whoop device picker modal. Value 'true' signals the destination page\n * to open the WHOOP device picker modal on init.\n */\n WebSignupQueryParam[\"wdpm\"] = \"wdpm\";\n /**\n * Skip Whoop connect flow\n */\n WebSignupQueryParam[\"wsc\"] = \"wsc\";\n /**\n * Redirect after login. Path to navigate to after a successful login.\n * Only paths in loginRedirectAllowedPaths are accepted.\n */\n WebSignupQueryParam[\"ral\"] = \"ral\";\n})(WebSignupQueryParam || (WebSignupQueryParam = {}));\nexport const loginRedirectAllowedPaths = ['account/profile'];\nexport function isLoginRedirectAllowedPath(path) {\n return loginRedirectAllowedPaths.some(allowedPath => allowedPath === path);\n}\n/**\n * Parameters from CAPI platforms and other sources of traffic that identify\n * the click that brought the user here.\n *\n * These should be saved so that we can access these after navigation and\n * pass them to the relevant platform\n */\nexport const clickIdParameters = [\n WebSignupQueryParam.ScCid,\n WebSignupQueryParam.irclickid,\n WebSignupQueryParam.fbclid,\n WebSignupQueryParam.ttclid,\n WebSignupQueryParam.rdt_cid,\n WebSignupQueryParam.epik,\n];\nconst safeToTrackQueryParams = new Set([\n WebSignupQueryParam.flow,\n WebSignupQueryParam.code,\n WebSignupQueryParam.ignoreConfirmation,\n WebSignupQueryParam.ic,\n WebSignupQueryParam.fg,\n WebSignupQueryParam.sfg,\n WebSignupQueryParam.sq,\n WebSignupQueryParam.cbo,\n WebSignupQueryParam.ip,\n WebSignupQueryParam.ipv,\n WebSignupQueryParam.od,\n WebSignupQueryParam.pl,\n WebSignupQueryParam.wcf,\n WebSignupQueryParam.we,\n WebSignupQueryParam.wdpm,\n WebSignupQueryParam.wsc,\n WebSignupQueryParam.ral,\n 'percentage',\n 'asAmount',\n 'includesThermometer',\n 'lead',\n 'lang',\n]);\nfunction isQueryParameterSafeToTrack(key) {\n return safeToTrackQueryParams.has(key) || key.startsWith('utm_');\n}\nconst SCRUBBED_VALUE = '(scrubbed)';\n/**\n * Filters URL query params for forwarding into analytics event properties.\n * Safe-to-track params keep their actual value; everything else has its value\n * replaced with a sentinel string so we know the param was on the URL\n * without leaking its value (click ids, referral codes, unknown params).\n */\nexport function scrubQueryParameters(params) {\n const scrubbed = {};\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined)\n continue;\n if (isQueryParameterSafeToTrack(key)) {\n scrubbed[key] = value;\n }\n else {\n scrubbed[key] = SCRUBBED_VALUE;\n }\n }\n return scrubbed;\n}\nexport var RegistrationFlow;\n(function (RegistrationFlow) {\n RegistrationFlow[RegistrationFlow[\"OURA\"] = 1] = \"OURA\";\n RegistrationFlow[RegistrationFlow[\"APPLE_WATCH\"] = 2] = \"APPLE_WATCH\";\n RegistrationFlow[RegistrationFlow[\"META_LANDING_PAGE\"] = 3] = \"META_LANDING_PAGE\";\n RegistrationFlow[RegistrationFlow[\"PAYMENT_REDIRECT_FROM_APP\"] = 4] = \"PAYMENT_REDIRECT_FROM_APP\";\n RegistrationFlow[RegistrationFlow[\"B1\"] = 5] = \"B1\";\n RegistrationFlow[RegistrationFlow[\"EMAIL_VERIFICATION_REDIRECT\"] = 6] = \"EMAIL_VERIFICATION_REDIRECT\";\n RegistrationFlow[RegistrationFlow[\"WHOOP\"] = 7] = \"WHOOP\";\n})(RegistrationFlow || (RegistrationFlow = {}));\nexport function isRedirectFromAppRegistrationFlow(flow) {\n if (!flow)\n return false;\n return [\n RegistrationFlow.PAYMENT_REDIRECT_FROM_APP,\n RegistrationFlow.EMAIL_VERIFICATION_REDIRECT,\n ].includes(flow);\n}\n","// oxlint-disable unicorn/no-document-cookie\nclass CookieService {\n getAllCookies() {\n const map = {};\n const cookieStrings = document.cookie.split('; ');\n for (const cookie of cookieStrings) {\n const [name, ...valueParts] = cookie.split('=');\n if (name) {\n // Join back in case value contains '='\n const value = valueParts.join('=');\n const decodedValue = value ? decodeURIComponent(value) : undefined;\n if (decodedValue) {\n map[name] = decodedValue;\n }\n }\n }\n return map;\n }\n getCookie(name) {\n const nameEQ = `${name}=`;\n const cookies = document.cookie.split('; ');\n for (const cookie of cookies) {\n if (cookie.startsWith(nameEQ)) {\n return decodeURIComponent(cookie.slice(nameEQ.length));\n }\n }\n // returns undefined if not found\n }\n setCookie(cname, cvalue, expdays, domain) {\n const d = new Date();\n d.setTime(d.getTime() + expdays * 24 * 60 * 60 * 1000);\n let cookie = `${cname}=${encodeURIComponent(cvalue)};expires=${d.toUTCString()};path=/`;\n if (domain) {\n cookie += `;domain=${domain}`;\n }\n document.cookie = cookie;\n }\n clearAllCookies() {\n const cookies = document.cookie.split('; ');\n for (const cookie of cookies) {\n const [name] = cookie.split('=');\n if (name) {\n document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/`;\n }\n }\n }\n deleteCookie(name) {\n // Set the cookie with an expiration date in the past to delete it\n document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/`;\n }\n}\nexport const cookieService = new CookieService();\n","export function formatMetaClickId(clickId) {\n if (!clickId) {\n return;\n }\n // https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/fbp-and-fbc/\n // fbc = version.subdomainIndex.creationTime.<fbclid>\n if (clickId.startsWith('fb.')) {\n // fbclid is already formatted\n return clickId;\n }\n return `fb.1.${Date.now()}.${clickId}`;\n}\nexport function isFbcValid(fbc) {\n if (!fbc) {\n return false;\n }\n // Facebook _fbc format: fb.{subdomainIndex}.{timestamp}.{fbclid}\n // Example: fb.1.1234567890123.AbC123_dEf-456\n const parts = fbc.split('.');\n // Must have exactly 4 parts\n if (parts.length !== 4) {\n return false;\n }\n const [prefix, subdomainIndex, timestamp, fbclid] = parts;\n // Part 1: Must be 'fb'\n if (prefix !== 'fb') {\n return false;\n }\n // Part 2: Subdomain index must be a number (typically 1 or 2)\n if (!/^\\d+$/.test(subdomainIndex)) {\n return false;\n }\n // Part 3: Timestamp must be a valid 13-digit unix timestamp in milliseconds\n if (!/^\\d{13}$/.test(timestamp)) {\n return false;\n }\n // Validate timestamp is reasonable (after 2000-01-01 and before year 2100)\n const timestampNum = parseInt(timestamp);\n const minTimestamp = 946684800000; // 2000-01-01\n const maxTimestamp = 4102444800000; // 2100-01-01\n if (timestampNum < minTimestamp || timestampNum > maxTimestamp) {\n return false;\n }\n // Part 4: fbclid must exist and contain valid characters\n // Facebook fbclid typically contains alphanumeric, hyphens, and underscores\n if (!fbclid?.length) {\n return false;\n }\n return /^[a-zA-Z0-9_-]+$/.test(fbclid);\n}\n/**\n * Mitigates known Facebook bugs that corrupt the fbclid URL parameter.\n * See: https://nc1.slack.com/archives/C07M5HTABU7/p1770855728868539\n *\n * Pattern A: runaway %25-encoding chain appended after _aem_ suffix\n * Pattern B: double ?fbclid= in URL (Facebook in-app browser re-decoration)\n * Pattern C: prior _fbc value with dots escaped as __DOT__ leaked back into URL\n *\n * todo: remove it after enough time has passed\n */\nexport function sanitizeFbclid(value) {\n if (!value)\n return;\n // Pattern B: strip second ?fbclid= appended with wrong delimiter\n value = value.split('?')[0];\n // Pattern C: decode __DOT__-escaped _fbc value back to dotted format\n if (value.includes('__DOT__')) {\n value = value.replaceAll('__DOT__', '.');\n }\n // Pattern A: strip runaway %-encoding (% is never valid in base64url fbclid)\n value = value.split('%')[0];\n // Pattern E: &\n value = value.split('&')[0];\n // Pattern F: nested fbc - fbclid is itself an fbc value, possibly multiple levels deep\n // fb.1.ts1.fb.1.ts2.fb.1.ts3.clickid → fb.1.ts3.clickid\n const parts = value.split('.');\n const lastFbIdx = parts.lastIndexOf('fb');\n if (lastFbIdx > 0 && parts.length - lastFbIdx >= 4) {\n value = parts.slice(lastFbIdx).join('.');\n }\n return value;\n}\n","import { runInBackground } from '@naturalcycles/js-lib'\nimport { _anyToError } from '@naturalcycles/js-lib/error'\nimport { getFetcher } from '@naturalcycles/js-lib/http'\nimport type { Fetcher } from '@naturalcycles/js-lib/http'\nimport { _filterEmptyValues } from '@naturalcycles/js-lib/object'\nimport { _noop } from '@naturalcycles/js-lib/types'\nimport type { StringMap } from '@naturalcycles/js-lib/types'\nimport type { ClientId, PageViewInput, PurchaseInput } from '@naturalcycles/shared'\nimport {\n allowedDomains,\n clickIdParameters,\n cookieService,\n debugDomainMap,\n domainPathKeywordSuppressionMap,\n formatMetaClickId,\n sanitizeFbclid,\n WebSignupQueryParam,\n} from '@naturalcycles/shared'\n\nconst CLICK_ID_COOKIE_DAYS = 30\n// Keeps the click-id cookies well below the browser's per-cookie size limit\nconst MAX_CLICK_ID_LENGTH = 200\n// Shorter values are junk like the literal string `fbclid`, not a real click id\nconst MIN_FBCLID_LENGTH = 20\n\n/**\n * Client for our Conversions API endpoints (`web/p`, `web/purchase`). Captures ad click ids from\n * the URL, stores them in cookies once marketing consent is given and sends them as headers. Nothing\n * is sent without marketing consent. Calls never throw, failures go to `onError`.\n */\nexport class ConversionClient {\n constructor(cfg: ConversionClientCfg) {\n this.cfg = { ...cfg, enabled: cfg.enabled ?? true, onError: cfg.onError ?? _noop }\n this.fetcher = getFetcher({ baseUrl: cfg.url })\n }\n\n private readonly cfg: ConversionClientNormalizedCfg\n private readonly fetcher: Fetcher\n private lastCapturedHref: string | undefined\n // Kept in memory until marketing consent, any browser storage needs consent too (ePrivacy Art. 5(3))\n private pendingClickIds: StringMap = {}\n\n /** Captures ad click ids from the landing URL into memory. Call on page load. */\n init(): void {\n if (!this.cfg.enabled) return\n this.tryOrReport(() => this.captureClickIds(), undefined)\n }\n\n pageView(input: PageViewInput, opt: ConversionRequestOptions = {}): void {\n if (!this.cfg.enabled || !this.hasMarketingConsent(input)) return\n const pathname = this.getAllowedPathname(input.pathname)\n if (pathname === null) return\n runInBackground(this.send('p', { ...input, pathname }, opt))\n }\n\n purchase(input: PurchaseInput, opt: ConversionRequestOptions = {}): void {\n if (!this.cfg.enabled || !this.hasMarketingConsent(input)) return\n const pathname = this.getAllowedPathname(input.pathname)\n if (pathname === null) return\n runInBackground(this.send('purchase', { ...input, pathname }, opt))\n }\n\n private hasMarketingConsent(input: PageViewInput | PurchaseInput): boolean {\n return (input.marketingConsent ?? input.marketingCookie) === true\n }\n\n /** Returns null outside the allowed domains or on a path of their exclusion list. */\n private getAllowedPathname(pathname: string): string | null {\n const { href, origin } = globalThis.location\n const domain =\n allowedDomains.find(allowedDomain => href.startsWith(allowedDomain)) || debugDomainMap[origin]\n if (!domain) return null\n const isSuppressed = domainPathKeywordSuppressionMap[domain].some(keyword =>\n pathname.includes(keyword),\n )\n return isSuppressed ? null : pathname\n }\n\n private async send(\n path: 'p' | 'purchase',\n json: PageViewInput | PurchaseInput,\n opt: ConversionRequestOptions,\n ): Promise<void> {\n try {\n const res = await this.fetcher.doFetch({\n url: path,\n method: 'POST',\n json,\n headers: {\n ...this.getHeaders({ marketingConsent: json.marketingConsent ?? json.marketingCookie }),\n ...opt.extraHeaders,\n },\n keepalive: true,\n responseType: 'void',\n })\n if (res.err) this.cfg.onError(res.err)\n } catch (err) {\n this.cfg.onError(_anyToError(err))\n }\n }\n\n /** Click ids are only included with marketing consent. */\n getHeaders(input: ConversionHeadersInput): ConversionHeaders {\n const clientId = String(this.cfg.clientId)\n if (!input.marketingConsent) return { clientId }\n return this.tryOrReport<ConversionHeaders>(\n () => {\n if (this.cfg.enabled) this.storeClickIds()\n\n return _filterEmptyValues({\n clientId,\n fbc:\n cookieService.getCookie('_fbc') ||\n formatMetaClickId(cookieService.getCookie(WebSignupQueryParam.fbclid)),\n fbp: cookieService.getCookie('_fbp'),\n scCid: cookieService.getCookie(WebSignupQueryParam.ScCid),\n ttclid: cookieService.getCookie(WebSignupQueryParam.ttclid),\n rdtCid: cookieService.getCookie(WebSignupQueryParam.rdt_cid),\n epik:\n cookieService.getCookie('_epik') || cookieService.getCookie(WebSignupQueryParam.epik),\n uuid_c1: cookieService.getCookie('_scid') || cookieService.getCookie('uuid_c1'),\n })\n },\n { clientId },\n )\n }\n\n private storeClickIds(): void {\n this.captureClickIds()\n for (const [param, value] of Object.entries(this.pendingClickIds)) {\n cookieService.setCookie(param, value!, CLICK_ID_COOKIE_DAYS, this.cfg.cookieDomain)\n }\n this.pendingClickIds = {}\n }\n\n private tryOrReport<T>(fn: () => T, fallback: T): T {\n try {\n return fn()\n } catch (err) {\n this.cfg.onError(_anyToError(err))\n return fallback\n }\n }\n\n private captureClickIds(): void {\n const { href, search } = globalThis.location\n if (href === this.lastCapturedHref) return\n this.lastCapturedHref = href\n\n const searchParams = new URLSearchParams(search)\n for (const param of clickIdParameters) {\n const raw = searchParams.get(param) || searchParams.get(param.toLowerCase())\n if (!raw) continue\n const value =\n param === WebSignupQueryParam.fbclid ? this.toFbc(raw) : raw.slice(0, MAX_CLICK_ID_LENGTH)\n if (value) this.pendingClickIds[param] = value\n }\n }\n\n /** Returns undefined when this click is already captured, so its timestamp is kept. */\n private toFbc(raw: string): string | undefined {\n const fbclid = sanitizeFbclid(raw)\n if (!fbclid || fbclid.length < MIN_FBCLID_LENGTH) return\n const capturedFbc =\n this.pendingClickIds[WebSignupQueryParam.fbclid] ||\n cookieService.getCookie(WebSignupQueryParam.fbclid)\n if (capturedFbc?.endsWith(`.${fbclid}`)) return\n return formatMetaClickId(fbclid)\n }\n}\n\ninterface ConversionClientNormalizedCfg extends ConversionClientCfg {\n enabled: boolean\n onError: (err: Error) => void\n}\n\nexport interface ConversionClientCfg {\n /** Backend base url including `/web`, e.g. `https://api.example.com/web`. */\n url: string\n clientId: ClientId\n /** `Domain` of the click-id cookies, e.g. `.naturalcycles.com`. Host-only when unset. */\n cookieDomain?: string\n /** Pass false to make every call a no-op, e.g. for bots and e2e tests. Defaults to true. */\n enabled?: boolean\n onError?: (err: Error) => void\n}\n\nexport interface ConversionRequestOptions {\n extraHeaders?: StringMap\n}\n\nexport interface ConversionHeadersInput {\n marketingConsent: boolean | undefined\n}\n\nexport interface ConversionHeaders {\n clientId: string\n fbc?: string\n fbp?: string\n scCid?: string\n ttclid?: string\n rdtCid?: string\n epik?: string\n uuid_c1?: string\n}\n"],"ignoreList":[0,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21],"mappings":"AAOA,SAAgBA,EAAc,IAAS,IAAI;CACvC,IAAIC,IAAK,IACHC,IAAQ,WAAW,OAAO,gBAAgB,IAAI,WAAWC,CAAM,CAAC;CACtE,OAAO,MAIH,KAAM,mEAAYD,EAAMC,KAAU;CAEtC,OAAOF;AACX;;;ACfA,SAAgBG,IAAoC;CAClD,OAAOJ,EAAc;AACvB;;;ACWA,IAAaK,KAAa,MAAM,CAAC,CAACC;AAOlC,SAAgBC,EAAU,GAAK;CAC3B,OAAQ,OAAOC,KAAQ,cAAYA,KAAgB,CAAC,MAAM,QAAQA,CAAG,KAAM;AAC/E;AA6CA,SAAgBC,EAAS,GAAK;CAC1B,IAAID,KAA6B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AAY,CAAC;GAC3E,IAAI,CAACG,GAAK;GACV,IAAM3J,IACJwJ,MAAUrE,EAAoB,SAAS,KAAK,MAAMwE,CAAG,IAAIA,EAAI,MAAM,GAAGd,EAAmB;GAC3F,AAAI7I,MAAO,KAAK,gBAAgBwJ,KAASxJ;EAC3C;CACF;CAGA,MAAc,GAAiC;EAC7C,IAAM4J,IAASnB,GAAekB,CAAG;EACjC,IAAI,GAACC,KAAUA,EAAO,SAASd,OAI/B,EAFE,KAAK,gBAAgB3D,EAAoB,WACzCwC,EAAc,UAAUxC,EAAoB,MAAM,EAAA,EACnC,SAAS,IAAIyE,GAAQ,GACtC,OAAOrB,EAAkBqB,CAAM;CACjC;AACF"}
1
+ {"version":3,"file":"conversionClient.js","names":["nanoidBrowser","id","bytes","length","generateConversionEventId","_isTruthy","v","_isObject","obj","_isEmpty","k","abortSignalTimeoutOrUndefined","ms","abortSignalTimeout","polyfilledAbortSignalTimeout","ac","abortSignalAnyOrUndefined","filtered","signals","abortSignalAny","polyfilledAbortSignalAny","signal","commonLoggerCreate","emit","input","data","sink","context","toLogData","args","childContext","consoleLogger","fields","msg","err","level","AsyncManager","wrappedPromise","promise","fn","size","started","timeout","resolve","hook","runInBackground","_noop","_args","_objectEntries","_pick","opt","props","_omit","_filterFalsyValues","_filterObject","_filterNullishValues","_filterUndefinedValues","predicate","_mapKeys","map","mapper","_filterEmptyValues","_merge","sources","source","key","target","isServerSide","isClientSide","DETECT_JSON","_jsonParseIfPossible","reviver","_jsonParse","s","JsonParseError","_truncateMiddle","maxLen","omission","mark1","mark2","_substringBefore","pos","delimiter","_anyToError","e","o","errorClass","_errorObjectToError","_anyToErrorObject","errorData","eo","_isErrorLike","_errorLikeToErrorObject","_isBackendErrorResponseObject","_isErrorObject","_stringify","AppError","name","cause","_errorDataAppend","message","HttpRequestError","AssertionError","TimeoutError","UnexpectedPassError","_safeJsonStringify","replacer","spaces","serializer","cycleReplacer","stack","keys","value","thisPos","supportsAggregateError","globalStringifyFunction","stringifyErrorLike","stringifyFn","sLines","i","includeErrorCause","_assertIsError","_assertErrorClassOrRethrow","pDelaySignal","timer","done","_since","_ms","until","from","millis","sec","min","hrs","_clamp","x","minIncl","maxIncl","pTimeout","fakeError","onTimeout","reject","_toUrlOrNull","url","base","HTTP_METHODS","Fetcher","cfg","method","m","payload","res","initGeneration","req","timeoutMillis","fullUrl","signature","logger","retryAttempt","reinitAttempted","shouldReinit","init","responseType","text","fetchFn","responseStatusCode","retryStatus","count","timeoutMultiplier","timeoutMax","retryAfterStr","retryAfterNumber","date","noise","retryPost","statusCode","statusFamily","retry5xx","retry4xx","retry3xx","status","shortUrl","baseUrl","norm","debug","defaultRetryOptions","inputUrl","searchParams","qs","\"accept\"","acceptByResponseType","getFetcher","domainPathKeywordSuppressionMap","substringThroughOrNull","pathname","index","debugDomainMap","allowedDomains","WebSignupQueryParam","\"flow\"","\"code\"","\"refId\"","\"referral\"","\"ignoreConfirmation\"","\"ic\"","\"measuringDevice\"","\"irclickid\"","\"fg\"","\"sfg\"","\"sq\"","\"cbo\"","\"ip\"","\"ipv\"","\"appleAuth\"","\"googleAuth\"","\"od\"","\"pl\"","\"ScCid\"","\"fbclid\"","\"ttclid\"","\"rdt_cid\"","\"epik\"","\"adid\"","\"wcf\"","\"we\"","\"werr\"","\"wdpm\"","\"wsc\"","\"ral\"","clickIdParameters","RegistrationFlow","\"OURA\"","\"APPLE_WATCH\"","\"META_LANDING_PAGE\"","\"PAYMENT_REDIRECT_FROM_APP\"","\"B1\"","\"EMAIL_VERIFICATION_REDIRECT\"","\"WHOOP\"","conversionService","domain","allowedDomain","origin","scrubbedPathname","rule","cookieService","cookieStrings","cookie","valueParts","decodedValue","nameEQ","cookies","d","expdays","cname","cvalue","formatMetaClickId","clickId","sanitizeFbclid","parts","lastFbIdx","CLICK_ID_COOKIE_DAYS","MAX_CLICK_ID_LENGTH","MIN_FBCLID_LENGTH","ConversionClient","path","json","clientId","param","fallback","href","search","raw","fbclid"],"sources":["../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.1_undici@8.12.1/node_modules/@naturalcycles/js-lib/dist/nanoid.js","../src/conversion/conversion.util.ts","../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.1_undici@8.12.1/node_modules/@naturalcycles/js-lib/dist/is.util.js","../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.1_undici@8.12.1/node_modules/@naturalcycles/js-lib/dist/abort.js","../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.1_undici@8.12.1/node_modules/@naturalcycles/js-lib/dist/log/commonLogger.js","../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.1_undici@8.12.1/node_modules/@naturalcycles/js-lib/dist/asyncManager.js","../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.1_undici@8.12.1/node_modules/@naturalcycles/js-lib/dist/types.js","../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.1_undici@8.12.1/node_modules/@naturalcycles/js-lib/dist/object/object.util.js","../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.1_undici@8.12.1/node_modules/@naturalcycles/js-lib/dist/env.js","../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.1_undici@8.12.1/node_modules/@naturalcycles/js-lib/dist/string/json.util.js","../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.1_undici@8.12.1/node_modules/@naturalcycles/js-lib/dist/string/string.util.js","../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.1_undici@8.12.1/node_modules/@naturalcycles/js-lib/dist/error/error.util.js","../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.1_undici@8.12.1/node_modules/@naturalcycles/js-lib/dist/string/safeJsonStringify.js","../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.1_undici@8.12.1/node_modules/@naturalcycles/js-lib/dist/string/stringify.js","../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.1_undici@8.12.1/node_modules/@naturalcycles/js-lib/dist/error/assert.js","../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.1_undici@8.12.1/node_modules/@naturalcycles/js-lib/dist/promise/pDelay.js","../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.1_undici@8.12.1/node_modules/@naturalcycles/js-lib/dist/datetime/time.util.js","../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.1_undici@8.12.1/node_modules/@naturalcycles/js-lib/dist/number/number.util.js","../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.1_undici@8.12.1/node_modules/@naturalcycles/js-lib/dist/promise/pTimeout.js","../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.1_undici@8.12.1/node_modules/@naturalcycles/js-lib/dist/string/url.util.js","../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.1_undici@8.12.1/node_modules/@naturalcycles/js-lib/dist/http/http.model.js","../../../node_modules/.pnpm/@naturalcycles+js-lib@15.93.1_undici@8.12.1/node_modules/@naturalcycles/js-lib/dist/http/fetcher.js","../../shared/dist/cnst/privacySettings.js","../../shared/dist/cnst/queryParameters.js","../../shared/dist/service/capi.shared.service.js","../../shared/dist/service/cookie.service.js","../../shared/dist/util/metaClickId.util.js","../src/conversion/conversionClient.ts"],"sourcesContent":["// Vendored from https://github.com/ai/nanoid/blob/main/index.browser.js\n// All credit to nanoid authors: https://github.com/ai/nanoid\n// Reason for vendoring: (still) cannot import esm, and Nanoid went ESM-only since 4.0\n/// <reference lib=\"dom\" preserve=\"true\" />\n// \"0-9a-zA-Z-_\", same as base64url alphabet\nconst urlAlphabet = 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict';\n// oxlint-disable no-bitwise -- NanoID uses bit operations to build compact IDs\nexport function nanoidBrowser(length = 21) {\n let id = '';\n const bytes = globalThis.crypto.getRandomValues(new Uint8Array(length));\n while (length--) {\n // Using the bitwise AND operator to \"cap\" the value of\n // the random byte from 255 to 63, in that way we can make sure\n // that the value will be a valid index for the \"chars\" string.\n id += urlAlphabet[bytes[length] & 63];\n }\n return id;\n}\nconst defaultRandomFunction = (bytes) => globalThis.crypto.getRandomValues(new Uint8Array(bytes));\nexport function nanoidBrowserCustomAlphabet(alphabet, length = 21) {\n return customRandom(alphabet, length, defaultRandomFunction);\n}\nfunction customRandom(alphabet, defaultSize, getRandom) {\n // First, a bitmask is necessary to generate the ID. The bitmask makes bytes\n // values closer to the alphabet size. The bitmask calculates the closest\n // `2^31 - 1` number, which exceeds the alphabet size.\n // For example, the bitmask for the alphabet size 30 is 31 (00011111).\n // `Math.clz32` is not used, because it is not available in browsers.\n const mask = (2 << Math.log2(alphabet.length - 1)) - 1;\n // Though, the bitmask solution is not perfect since the bytes exceeding\n // the alphabet size are refused. Therefore, to reliably generate the ID,\n // the random bytes redundancy has to be satisfied.\n // Note: every hardware random generator call is performance expensive,\n // because the system call for entropy collection takes a lot of time.\n // So, to avoid additional system calls, extra bytes are requested in advance.\n // Next, a step determines how many random bytes to generate.\n // The number of random bytes gets decided upon the ID size, mask,\n // alphabet size, and magic number 1.6 (using 1.6 peaks at performance\n // according to benchmarks).\n // `-~f => Math.ceil(f)` if f is a float\n // `-~i => i + 1` if i is an integer\n const step = -~((1.6 * mask * defaultSize) / alphabet.length);\n return (size = defaultSize) => {\n let id = '';\n while (true) {\n const bytes = getRandom(step);\n // A compact alternative for `for (var i = 0; i < step; i++)`.\n let j = step;\n while (j--) {\n // Adding `|| ''` refuses a random byte that exceeds the alphabet size.\n id += alphabet[bytes[j] & mask] || '';\n if (id.length === size)\n return id;\n }\n }\n };\n}\n","import { nanoidBrowser } from '@naturalcycles/js-lib/nanoid'\n\nexport function generateConversionEventId(): string {\n return nanoidBrowser()\n}\n","export const _isNull = (v) => v === null;\nexport const _isUndefined = (v) => v === undefined;\nexport const _isNullish = (v) => v === undefined || v === null;\nexport const _isNotNullish = (v) => v !== undefined && v !== null;\n/**\n * Same as Boolean, but with correct type output.\n * Related:\n * https://github.com/microsoft/TypeScript/issues/16655\n * https://www.karltarvas.com/2021/03/11/typescript-array-filter-boolean.html\n *\n * @example\n *\n * [1, 2, undefined].filter(_isTruthy)\n * // => [1, 2]\n */\nexport const _isTruthy = (v) => !!v;\nexport const _isFalsy = (v) => !v;\n/**\n * Returns true if item is Object, not null and not Array.\n *\n * Currently treats RegEx as Object too, e.g _isObject(/some/) === true\n */\nexport function _isObject(obj) {\n return (typeof obj === 'object' && obj !== null && !Array.isArray(obj)) || false;\n}\n/**\n * Returns true if item is an object literal: not an Array, Error, RegExp or class instance.\n */\nexport function _isPlainObject(v) {\n if (typeof v !== 'object' || v === null)\n return false;\n const proto = Object.getPrototypeOf(v);\n return proto === Object.prototype || proto === null;\n}\nexport function _isPrimitive(v) {\n return (v === null ||\n v === undefined ||\n typeof v === 'number' ||\n typeof v === 'boolean' ||\n typeof v === 'string' ||\n typeof v === 'bigint' ||\n typeof v === 'symbol');\n}\nexport function _isEmptyObject(obj) {\n // for...in with early return avoids allocating the full Object.keys array.\n // Object.hasOwn matches Object.keys() semantics (own enumerable keys only).\n for (const k in obj) {\n if (Object.hasOwn(obj, k))\n return false;\n }\n return true;\n}\nexport function _isNotEmptyObject(obj) {\n for (const k in obj) {\n if (Object.hasOwn(obj, k))\n return true;\n }\n return false;\n}\n/**\n * Object is considered empty if it's one of:\n * undefined\n * null\n * '' (empty string)\n * [] (empty array)\n * {} (empty object)\n * new Map() (empty Map)\n * new Set() (empty Set)\n */\nexport function _isEmpty(obj) {\n if (obj === undefined || obj === null)\n return true;\n if (typeof obj === 'string' || Array.isArray(obj)) {\n return obj.length === 0;\n }\n if (obj instanceof Map || obj instanceof Set) {\n return obj.size === 0;\n }\n if (typeof obj === 'object') {\n for (const k in obj) {\n if (Object.hasOwn(obj, k))\n return false;\n }\n return true;\n }\n return false;\n}\n/**\n * @see _isEmpty\n */\nexport function _isNotEmpty(obj) {\n return !_isEmpty(obj);\n}\n","import { _isTruthy } from './is.util.js';\n/**\n * Creates AbortableSignal,\n * which is like AbortSignal, but can \"abort itself\" with `.abort()` method.\n *\n * @experimental\n */\nexport function createAbortableSignal() {\n const ac = new AbortController();\n return Object.assign(ac.signal, {\n abort: ac.abort.bind(ac),\n });\n}\n/**\n * Returns AbortSignal if ms is defined.\n * Otherwise returns undefined.\n */\nexport function abortSignalTimeoutOrUndefined(ms) {\n return ms ? abortSignalTimeout(ms) : undefined;\n}\n/**\n * Returns an AbortSignal that aborts after the given number of milliseconds.\n * Uses native `AbortSignal.timeout()` when available, falls back to a polyfill.\n *\n * The abort reason is a DOMException with name \"TimeoutError\".\n */\nexport function abortSignalTimeout(ms) {\n return typeof AbortSignal.timeout === 'function'\n ? AbortSignal.timeout(ms)\n : polyfilledAbortSignalTimeout(ms);\n}\nexport function polyfilledAbortSignalTimeout(ms) {\n const ac = new AbortController();\n setTimeout(() => {\n ac.abort(new DOMException('The operation was aborted due to timeout', 'TimeoutError'));\n }, ms);\n return ac.signal;\n}\n/**\n * Returns AbortSignal.any(signals) is the array (after filtering undefined inputs) is not empty,\n * otherwise undefined.\n */\nexport function abortSignalAnyOrUndefined(signals) {\n const filtered = signals.filter(_isTruthy);\n return filtered.length ? abortSignalAny(filtered) : undefined;\n}\n/**\n * Returns an AbortSignal that aborts when any of the given signals abort.\n * Uses native `AbortSignal.any()` when available, falls back to a polyfill.\n *\n * The abort reason is taken from the first signal that aborts.\n * If any input signal is already aborted, the returned signal is immediately aborted.\n *\n * If only 1 signal is passed in the input array - that Signal is returned as-is.\n */\nexport function abortSignalAny(signals) {\n if (signals.length === 1) {\n return signals[0];\n }\n return typeof AbortSignal.any === 'function'\n ? AbortSignal.any(signals)\n : polyfilledAbortSignalAny(signals);\n}\nexport function polyfilledAbortSignalAny(signals) {\n const ac = new AbortController();\n for (const signal of signals) {\n if (signal.aborted) {\n ac.abort(signal.reason);\n return ac.signal;\n }\n }\n for (const signal of signals) {\n signal.addEventListener('abort', () => ac.abort(signal.reason), {\n once: true,\n signal: ac.signal,\n });\n }\n return ac.signal;\n}\n","// copy-pasted to avoid weird circular dependency\nconst _noop = (..._args) => undefined;\nexport const commonLogLevelNumber = {\n debug: 10,\n log: 20,\n warn: 30,\n error: 40,\n};\n/**\n * Creates a CommonLogger that writes every entry to `sink`.\n * `context` is called on every log call, so it can return values that change\n * after the logger is created (e.g a request context whose user is resolved later).\n */\nexport function commonLoggerCreate(sink, context) {\n const emit = (level, [input, data]) => sink({ ...context?.(), ...toLogData(input, data), level });\n return {\n debug: (...args) => emit('debug', args),\n log: (...args) => emit('log', args),\n warn: (...args) => emit('warn', args),\n error: (...args) => emit('error', args),\n child: childContext => commonLoggerCreate(sink, () => ({ ...context?.(), ...childContext })),\n };\n}\nfunction toLogData(input, data) {\n if (typeof input === 'string')\n return { ...data, msg: input };\n if (input instanceof Error)\n return { err: input };\n return input;\n}\n/**\n * CommonLogger that logs to `console`.\n */\nexport const consoleLogger = commonLoggerCreate(({ level, msg, err, ...fields }) => {\n const args = [];\n if (msg !== undefined)\n args.push(msg);\n if (err !== undefined)\n args.push(err);\n if (Object.keys(fields).length)\n args.push(fields);\n console[level](...args);\n});\n/**\n * CommonLogger that does nothing (noop).\n */\nexport const commonLoggerNoop = {\n debug: _noop,\n log: _noop,\n warn: _noop,\n error: _noop,\n child: () => commonLoggerNoop,\n};\n/**\n * Creates a CommonLogger that is \"limited\" to the specified CommonLogLevel.\n */\nexport function createCommonLoggerAtLevel(logger = consoleLogger, minLevel = 'log') {\n const level = commonLogLevelNumber[minLevel];\n if (level <= commonLogLevelNumber['debug']) {\n // All levels are kept\n return logger;\n }\n return {\n debug: _noop, // otherwise it is \"log everything\" logger (same logger as input)\n log: level <= commonLogLevelNumber['log'] ? (...args) => logger.log(...args) : _noop,\n warn: level <= commonLogLevelNumber['warn'] ? (...args) => logger.warn(...args) : _noop,\n error: (...args) => logger.error(...args),\n child: context => createCommonLoggerAtLevel(logger.child(context), minLevel),\n };\n}\n/**\n * Creates a \"proxy\" CommonLogger that pipes log entries to all provided sub-loggers.\n */\nexport function commonLoggerPipe(loggers) {\n return {\n debug: (...args) => loggers.forEach(logger => logger.debug(...args)),\n log: (...args) => loggers.forEach(logger => logger.log(...args)),\n warn: (...args) => loggers.forEach(logger => logger.warn(...args)),\n error: (...args) => loggers.forEach(logger => logger.error(...args)),\n child: context => commonLoggerPipe(loggers.map(logger => logger.child(context))),\n };\n}\n","import { consoleLogger } from './log/commonLogger.js';\nclass AsyncManagerImpl {\n logger = consoleLogger;\n pendingOps = new Set();\n onErrorHooks = [];\n runInBackground(promise) {\n const wrappedPromise = promise\n .catch(err => this.fireOnErrorHooks(err))\n .finally(() => this.pendingOps.delete(wrappedPromise));\n this.pendingOps.add(wrappedPromise);\n }\n onError(fn) {\n this.onErrorHooks.push(fn);\n }\n /**\n * Resolves when all pending operations settle.\n * They may resolve or reject, allDone will never throw.\n * Errors (rejections) are reported to onErrorHooks (instead).\n *\n * If timeout is specified - it resolves if timeout has reached.\n */\n async allDone(timeout) {\n const { size } = this.pendingOps;\n if (!size)\n return;\n const { logger } = this;\n const started = Date.now();\n if (timeout) {\n const result = await Promise.race([\n Promise.allSettled(this.pendingOps),\n new Promise(resolve => setTimeout(resolve, timeout, 'timeout')),\n ]);\n if (result === 'timeout') {\n logger.warn(`AsyncManager.allDone timed out after ${timeout} ms with ${this.pendingOps.size} pending op(s)`);\n return;\n }\n }\n else {\n await Promise.allSettled(this.pendingOps);\n }\n logger.log(`AsyncManager.allDone for ${size} op(s) in ${Date.now() - started} ms`);\n }\n reset() {\n this.pendingOps.clear();\n this.onErrorHooks = [];\n }\n fireOnErrorHooks(err) {\n if (this.onErrorHooks.length) {\n this.onErrorHooks.forEach(hook => hook(err));\n }\n else {\n this.logger.error({ msg: 'AsyncManager unhandled rejection', err });\n }\n }\n}\n/**\n * Singleton which keeps track of async operations - \"voided promise-returning functions\"\n * that should run in parallel to the main request.\n *\n * It is an alternative to do `void doSomeAnalytics()`, which should run in parallel\n * and not block the request (not slow down nor fail the request on analytics api failure).\n *\n * At the same time, `void doSomeAnalytics()` gets completely detached and untracked,\n * nothing awaits it, its rejection becomes unhandledRejection (and may kill Node.js process).\n *\n * With AsyncManager, you instead register all those \"voided\" calls like this:\n *\n * AsyncManager.runInBackground(doSomeAnalytics())\n *\n * Then, in a few places you may be interested to ensure that all async operations have been finished.\n * The places can be:\n * - Graceful shutdown of a backend service\n * - Before the end of runScript\n * - At the end of each unit test, to make sure async ops don't leak\n *\n * You ensure no pending async operations like this:\n *\n * await AsyncManager.allDone()\n *\n * which never throws, but instead awaits all operations to be settled.\n *\n * @experimental\n */\nexport const AsyncManager = new AsyncManagerImpl();\n// Shorthand alias\nexport const runInBackground = AsyncManager.runInBackground.bind(AsyncManager);\n","/**\n * Symbol to indicate END of Sequence.\n */\nexport const END = Symbol('END');\n/**\n * Symbol to indicate SKIP of item (e.g in AbortableMapper)\n */\nexport const SKIP = Symbol('SKIP');\n/**\n * Symbol to indicate cache miss.\n * To distinguish from cache returning `undefined` or `null`.\n */\nexport const MISS = Symbol('MISS');\nexport const _passthroughMapper = item => item;\nexport const _passUndefinedMapper = () => undefined;\n/**\n * Function that does nothings and returns `undefined`.\n */\nexport const _noop = (..._args) => undefined;\nexport const _passthroughPredicate = () => true;\nexport const _passNothingPredicate = () => false;\nexport const JWT_REGEX = /^[\\w-]+\\.[\\w-]+\\.[\\w-]+$/;\n/**\n * Needed due to https://github.com/microsoft/TypeScript/issues/13778\n * Only affects typings, no runtime effect.\n */\nexport const _stringMapValues = Object.values;\n/**\n * Needed due to https://github.com/microsoft/TypeScript/issues/13778\n * Only affects typings, no runtime effect.\n */\nexport const _stringMapEntries = Object.entries;\n/**\n * Alias of `Object.keys`, but returns keys typed as `keyof T`, not as just `string`.\n * This is how TypeScript should work, actually.\n *\n * Object.keys always returns strings, so numeric keys are stringified via `${K}`.\n * Symbol keys are excluded (Object.keys does not return symbols).\n */\nexport const _objectKeys = Object.keys;\n/**\n * Alias of `Object.entries`, but returns better-typed output.\n *\n * Difference with _stringMapEntries?\n * Use _stringMapEntries when the object is a StringMap<T> - it'll correctly infer T being not undefined.\n * If the object is not a StringMap - use _objectEntries - it'll correctly infer object keys, which can be typed as Enum.\n *\n * So e.g you can use _objectEntries(obj).map([k, v] => {})\n * and `k` will be `keyof obj` instead of generic `string`.\n */\nexport const _objectEntries = Object.entries;\n/**\n * Utility function that helps to cast *existing variable* to needed type T.\n *\n * @example\n * try {} catch (err) {\n * // err is unknown here\n * _typeCast<AppError>(err)\n * // now err is of type AppError\n * err.data = {} // can be done, because it was casted\n * }\n */\nexport function _typeCast(_v) { }\n/**\n * Type-safe Object.assign that checks that part is indeed a Partial<T>\n */\nexport const _objectAssign = Object.assign;\n","import { _isEmpty, _isObject } from '../is.util.js';\nimport { _objectEntries, SKIP } from '../types.js';\n/**\n * Returns clone of `obj` with only `props` preserved.\n * Opposite of Omit.\n */\nexport function _pick(obj, props, opt = {}) {\n if (opt.mutate) {\n // Start as original object (mutable), DELETE properties that are not whitelisted\n for (const k of Object.keys(obj)) {\n if (!props.includes(k))\n delete obj[k];\n }\n return obj;\n }\n // Start as empty object, pick/add needed properties\n const r = {};\n for (const k of props) {\n if (k in obj)\n r[k] = obj[k];\n }\n return r;\n}\n/**\n * Sets all properties of an object except passed ones to `undefined`.\n * This is a more performant alternative to `_pick` that does picking/deleting.\n */\nexport function _pickWithUndefined(obj, props, opt = {}) {\n const r = opt.mutate ? obj : { ...obj };\n for (const k of Object.keys(r)) {\n if (!props.includes(k)) {\n r[k] = undefined;\n }\n }\n return r;\n}\n/**\n * Returns clone of `obj` with `props` omitted.\n * Opposite of Pick.\n */\nexport function _omit(obj, props, opt = {}) {\n if (opt.mutate) {\n for (const k of props) {\n delete obj[k];\n }\n return obj;\n }\n const r = {};\n for (const k of Object.keys(obj)) {\n if (!props.includes(k))\n r[k] = obj[k];\n }\n return r;\n}\n/**\n * Sets all passed properties of an object to `undefined`.\n * This is a more performant alternative to `_omit` that does picking/deleting.\n */\nexport function _omitWithUndefined(obj, props, opt = {}) {\n const r = opt.mutate ? obj : { ...obj };\n for (const k of props) {\n r[k] = undefined;\n }\n return r;\n}\n/**\n * Returns object with filtered keys from `props` array.\n * E.g:\n * _mask({...}, [\n * 'account.id',\n * 'account.updated',\n * ])\n */\nexport function _mask(obj, props, opt = {}) {\n const r = opt.mutate ? obj : _deepCopy(obj);\n for (const k of props) {\n _unset(r, k);\n }\n return r;\n}\n/**\n * Removes \"falsy\" values from the object.\n */\nexport function _filterFalsyValues(obj, opt = {}) {\n return _filterObject(obj, (_k, v) => !!v, opt);\n}\n/**\n * Removes values from the object that are `null` or `undefined`.\n */\nexport function _filterNullishValues(obj, opt = {}) {\n return _filterObject(obj, (_k, v) => v !== undefined && v !== null, opt);\n}\n/**\n * Removes values from the object that are `undefined`.\n * Only `undefined` values are removed. `null` values are kept!\n */\nexport function _filterUndefinedValues(obj, opt = {}) {\n return _filterObject(obj, (_k, v) => v !== undefined, opt);\n}\nexport function _filterEmptyArrays(obj, opt = {}) {\n return _filterObject(obj, (_k, v) => !Array.isArray(v) || v.length > 0, opt);\n}\n/**\n * Returns clone of `obj` without properties that does not pass `predicate`.\n * Allows filtering by both key and value.\n */\nexport function _filterObject(obj, predicate, opt = {}) {\n if (opt.mutate) {\n for (const [k, v] of _objectEntries(obj)) {\n if (!predicate(k, v, obj)) {\n delete obj[k];\n }\n }\n return obj;\n }\n // Not vulnerable to prototype pollution: writes to a new {}, where __proto__\n // assignment only changes the new object's prototype, not Object.prototype.\n const r = {};\n for (const [k, v] of _objectEntries(obj)) {\n if (predicate(k, v, obj)) {\n r[k] = v;\n }\n }\n return r;\n}\n/**\n * var users = {\n * 'fred': { 'user': 'fred', 'age': 40 },\n * 'pebbles': { 'user': 'pebbles', 'age': 1 }\n * }\n *\n * _mapValues(users, (_key, value) => value.age)\n * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)\n *\n * To skip some key-value pairs - use _mapObject instead.\n */\nexport function _mapValues(obj, mapper, opt = {}) {\n // Not vulnerable to prototype pollution: writes to a new {} (or mutates the\n // source in-place where own data properties shadow the __proto__ accessor).\n const map = opt.mutate ? obj : {};\n for (const [k, v] of Object.entries(obj)) {\n map[k] = mapper(k, v, obj);\n }\n return map;\n}\n/**\n * _.mapKeys({ 'a': 1, 'b': 2 }, (key, value) => key + value)\n * // => { 'a1': 1, 'b2': 2 }\n *\n * Does not support `mutate` flag.\n *\n * To skip some key-value pairs - use _mapObject instead.\n */\nexport function _mapKeys(obj, mapper) {\n // Not vulnerable to prototype pollution: writes to a new {}, where __proto__\n // assignment only changes the new object's prototype, not Object.prototype.\n const map = {};\n for (const [k, v] of Object.entries(obj)) {\n map[mapper(k, v, obj)] = v;\n }\n return map;\n}\n/**\n * Maps object through predicate - a function that receives (k, v, obj)\n * k - key\n * v - value\n * obj - whole object\n *\n * Order of arguments in the predicate is different form _mapValues / _mapKeys!\n *\n * Predicate should return a _tuple_ [0, 1], where:\n * 0 - key of returned object (string)\n * 1 - value of returned object (any)\n *\n * If predicate returns SKIP symbol - such key/value pair is ignored (filtered out).\n *\n * Non-string keys are passed via String(...)\n */\nexport function _mapObject(obj, mapper) {\n // Not vulnerable to prototype pollution: writes to a new {}, where __proto__\n // assignment only changes the new object's prototype, not Object.prototype.\n const map = {};\n for (const [k, v] of Object.entries(obj)) {\n const r = mapper(k, v, obj);\n if (r === SKIP)\n continue;\n map[r[0]] = r[1];\n }\n return map;\n}\nexport function _findKeyByValue(obj, v) {\n return Object.entries(obj).find(([_, value]) => value === v)?.[0];\n}\n/**\n * Returns the first key of a non-empty object.\n * Throws if the object is empty.\n *\n * Performance-optimised: uses `for...in` with an early return to avoid\n * allocating the full `Object.keys(obj)` array. The `Object.hasOwn` filter\n * matches `Object.keys()` semantics (own enumerable string keys only) and\n * satisfies the `guard-for-in` lint rule; cost is a single check before\n * the early return. Iteration order matches `Object.keys()` for plain\n * objects (integer-like keys ascending first, then string keys in\n * insertion order).\n */\nexport function _firstKey(obj) {\n for (const k in obj) {\n if (Object.hasOwn(obj, k))\n return k;\n }\n throw new Error('_firstKey called on empty object');\n}\n/**\n * Returns the first key of the object (or undefined if the object is empty).\n * See `_firstKey` for the iteration-order contract.\n */\nexport function _firstKeyOrUndefined(obj) {\n for (const k in obj) {\n if (Object.hasOwn(obj, k))\n return k;\n }\n return undefined;\n}\n/**\n * Returns the first value of a non-empty object.\n * Throws if the object is empty.\n * See `_firstKey` for the iteration-order contract.\n */\nexport function _firstValue(obj) {\n for (const k in obj) {\n if (Object.hasOwn(obj, k))\n return obj[k];\n }\n throw new Error('_firstValue called on empty object');\n}\n/**\n * Returns the first value of the object (or undefined if the object is empty).\n * See `_firstKey` for the iteration-order contract.\n */\nexport function _firstValueOrUndefined(obj) {\n for (const k in obj) {\n if (Object.hasOwn(obj, k))\n return obj[k];\n }\n return undefined;\n}\n/**\n * Returns the first [key, value] tuple of a non-empty object.\n * Throws if the object is empty.\n * See `_firstKey` for the iteration-order contract.\n */\nexport function _firstEntry(obj) {\n for (const k in obj) {\n if (Object.hasOwn(obj, k))\n return [k, obj[k]];\n }\n throw new Error('_firstEntry called on empty object');\n}\n/**\n * Returns the first [key, value] tuple of the object (or undefined if the object is empty).\n * See `_firstKey` for the iteration-order contract.\n */\nexport function _firstEntryOrUndefined(obj) {\n for (const k in obj) {\n if (Object.hasOwn(obj, k))\n return [k, obj[k]];\n }\n return undefined;\n}\nexport function _objectNullValuesToUndefined(obj, opt = {}) {\n return _mapValues(obj, (_k, v) => (v === null ? undefined : v), opt);\n}\n/**\n * Deep copy object (by json parse/stringify, since it has unbeatable performance+simplicity combo).\n */\nexport function _deepCopy(o, reviver) {\n return JSON.parse(JSON.stringify(o), reviver);\n}\n/**\n * Performance-optimized implementation of merging two objects\n * without mutating any of them.\n * (if you are allowed to mutate - there can be a faster implementation).\n *\n * Gives ~40% speedup with map sizes between 10 and 100k items,\n * compared to {...obj1, ...obj2} or Object.assign({}, obj1, obj2).\n *\n * Only use it in hot paths that are known to be performance bottlenecks,\n * otherwise it's not worth it (use normal object spread then).\n */\nexport function _mergeObjects(obj1, obj2) {\n // Not vulnerable to prototype pollution: writes to a new {}, where __proto__\n // assignment only changes the new object's prototype, not Object.prototype.\n const map = {};\n for (const k of Object.keys(obj1))\n map[k] = obj1[k];\n for (const k of Object.keys(obj2))\n map[k] = obj2[k];\n return map;\n}\n/**\n * Returns `undefined` if it's empty (according to `_isEmpty()` specification),\n * otherwise returns the original object.\n */\nexport function _undefinedIfEmpty(obj) {\n return _isEmpty(obj) ? undefined : obj;\n}\n/**\n * Filters the object by removing all key-value pairs where Value is Empty (according to _isEmpty() specification).\n */\nexport function _filterEmptyValues(obj, opt = {}) {\n return _filterObject(obj, (_k, v) => !_isEmpty(v), opt);\n}\n/**\n * Recursively merges own and inherited enumerable properties of source\n * objects into the destination object, skipping source properties that resolve\n * to `undefined`. Array and plain object properties are merged recursively.\n * Other objects and value types are overridden by assignment. Source objects\n * are applied from left to right. Subsequent sources overwrite property\n * assignments of previous sources.\n *\n * Works as \"recursive Object.assign\".\n *\n * **Note:** This method mutates `object`.\n *\n * @param target The destination object.\n * @param sources The source objects.\n * @returns Returns `object`.\n * @example\n *\n * var users = {\n * 'data': [{ 'user': 'barney' }, { 'user': 'fred' }]\n * };\n *\n * var ages = {\n * 'data': [{ 'age': 36 }, { 'age': 40 }]\n * };\n *\n * _.merge(users, ages);\n * // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] }\n *\n * Based on: https://gist.github.com/Salakar/1d7137de9cb8b704e48a\n */\nexport function _merge(target, ...sources) {\n for (const source of sources) {\n if (!_isObject(source))\n continue;\n for (const key of Object.keys(source)) {\n if (key === '__proto__' || key === 'constructor' || key === 'prototype')\n continue;\n if (_isObject(source[key])) {\n ;\n target[key] ||= {};\n _merge(target[key], source[key]);\n }\n else {\n ;\n target[key] = source[key];\n }\n }\n }\n return target;\n}\n/**\n * Trims all object VALUES deeply.\n * Doesn't touch object KEYS.\n * Mutates.\n */\nexport function _deepTrim(o) {\n if (!o)\n return o;\n if (typeof o === 'string') {\n return o.trim();\n }\n if (typeof o === 'object') {\n // Not vulnerable to prototype pollution: mutates in-place on the same object.\n // If __proto__ is an own data property (e.g. from JSON.parse), reads and writes\n // go through the own property, not the Object.prototype accessor.\n for (const k of Object.keys(o)) {\n o[k] = _deepTrim(o[k]);\n }\n }\n return o;\n}\n// from: https://github.com/jonschlinkert/unset-value\n// mutates obj\nexport function _unset(obj, prop) {\n if (!_isObject(obj)) {\n return;\n }\n if (obj.hasOwnProperty(prop)) {\n delete obj[prop];\n return;\n }\n const segs = prop.split('.');\n // Prevent prototype pollution\n if (segs.includes('__proto__') || segs.includes('constructor'))\n return;\n let last = segs.pop();\n while (segs.length && segs[segs.length - 1].endsWith('\\\\')) {\n last = segs.pop().slice(0, -1) + '.' + last;\n }\n while (segs.length && _isObject(obj)) {\n const k = segs.shift();\n obj = obj[k];\n }\n if (!_isObject(obj))\n return;\n delete obj[last];\n}\nexport function _invert(o) {\n const inv = {};\n Object.keys(o).forEach(k => {\n inv[o[k]] = k;\n });\n return inv;\n}\nexport function _invertMap(m) {\n const inv = new Map();\n m.forEach((v, k) => inv.set(v, k));\n return inv;\n}\n/**\n * Gets the property value at path of object.\n *\n * @example\n * const obj = {a: 'a', b: 'b', c: { cc: 'cc' }}\n * _get(obj, 'a') // 'a'\n * _get(obj, 'c.cc') // 'cc'\n * _get(obj, 'c[cc]') // 'cc'\n * _get(obj, 'unknown.path') // undefined\n */\nexport function _get(obj = {}, path = '') {\n return (path\n .replaceAll(/\\[([^\\]]+)]/g, '.$1')\n .split('.')\n // oxlint-disable-next-line unicorn/no-array-reduce\n .reduce((o, p) => o?.[p], obj));\n}\n/**\n * Sets the value at path of object. If a portion of path doesn’t exist it’s created. Arrays are created for\n * missing index properties while objects are created for all other missing properties.\n *\n * @param obj The object to modify.\n * @param path The path of the property to set.\n * @param value The value to set.\n * @returns Returns object.\n *\n * Based on: https://stackoverflow.com/a/54733755/4919972\n */\nexport function _set(obj, path, value) {\n if (!obj || Object(obj) !== obj || !path)\n return obj; // When obj is not an object\n // If not yet an array, get the keys from the string-path\n if (!Array.isArray(path)) {\n path = String(path).match(/[^.[\\]]+/g) || [];\n }\n else if (!path.length) {\n return obj;\n }\n // Prevent prototype pollution\n if (path.includes('__proto__') || path.includes('constructor')) {\n return obj;\n }\n // oxlint-disable-next-line unicorn/no-array-reduce\n ;\n path.slice(0, -1).reduce((a, c, i) => Object(a[c]) === a[c] // Does the key exist and is its value an object?\n ? // Yes: then follow that path\n a[c]\n : // No: create the key. Is the next key a potential array-index?\n (a[c] =\n // oxlint-disable-next-line no-bitwise, no-implicit-coercion, unicorn/prefer-math-trunc\n Math.abs(path[i + 1]) >> 0 === +path[i + 1]\n ? [] // Yes: assign a new array object\n : {}), // No: assign a new plain object\n obj)[path[path.length - 1]] = value; // Finally assign the value to the last key\n return obj; // allow chaining\n}\n/**\n * Checks if `path` is a direct property of `object` (not null, not undefined).\n *\n * @param obj The object to query.\n * @param path The path to check.\n * @returns Returns `true` if `path` exists, else `false`.\n * @example\n *\n * var object = { 'a': { 'b': { 'c': 3 } } };\n * var other = _.create({ 'a': _.create({ 'b': _.create({ 'c': 3 }) }) });\n *\n * _.has(object, 'a');\n * // => true\n *\n * _.has(object, 'a.b.c');\n * // => true\n *\n * _.has(object, ['a', 'b', 'c']);\n * // => true\n *\n * _.has(other, 'a');\n * // => false\n */\nexport function _has(obj, path) {\n const v = _get(obj, path);\n return v !== undefined && v !== null;\n}\n/**\n * Does Object.freeze recursively for given object.\n *\n * Based on: https://github.com/substack/deep-freeze/blob/master/index.js\n */\nexport function _deepFreeze(o) {\n // Not vulnerable to prototype pollution: read-only traversal, only calls\n // Object.freeze — never assigns properties from one object to another.\n Object.freeze(o);\n Object.getOwnPropertyNames(o).forEach(prop => {\n if (o.hasOwnProperty(prop) &&\n o[prop] !== null &&\n (typeof o[prop] === 'object' || typeof o[prop] === 'function') &&\n !Object.isFrozen(o[prop])) {\n _deepFreeze(o[prop]);\n }\n });\n}\n/**\n * let target: T = { a: 'a', n: 1}\n * let source: T = { a: 'a2', b: 'b' }\n *\n * _objectAssignExact(target, source)\n *\n * Does the same as `target = source`,\n * except that it mutates the target to make it exactly the same as source,\n * while keeping the reference to the same object.\n *\n * This way it can \"propagate deletions\".\n * E.g source doesn't have the `n` property, so it'll be deleted from target.\n * With normal Object.assign - it'll override the keys that `source` has, but not the\n * \"missing/deleted keys\".\n *\n * To make mutation extra clear - function returns void (unlike Object.assign).\n */\nexport function _objectAssignExact(target, source) {\n Object.assign(target, source);\n for (const k of Object.keys(target)) {\n if (!(k in source)) {\n // consider setting it to undefined maybe?\n delete target[k];\n }\n }\n}\n/**\n * type MyObj = { a?: string, b?: string }\n *\n * const collection: MyObj[] = [...]\n *\n * const collectionA = collection.filter(_hasProp('a'))\n * --> collectionA is now RequiredProp<MyObj, 'a'>[], i.e. { a: string, b?: string }[]\n */\nexport function _hasProp(prop) {\n return function (object) {\n return typeof object[prop] !== 'undefined';\n };\n}\n","/**\n * Use it to detect SSR/Node.js environment.\n *\n * Will return `true` in Node.js.\n * Will return `false` in the Browser.\n */\nexport function isServerSide() {\n return !isClientSide();\n}\n/**\n * Use it to detect Browser (not SSR/Node) environment.\n *\n * Will return `true` in the Browser.\n * Will return `false` in Node.js.\n */\nexport function isClientSide() {\n // oxlint-disable-next-line unicorn/prefer-global-this\n return typeof window !== 'undefined' && !!window?.document;\n}\n/**\n * Almost the same as isServerSide()\n * (isServerSide should return true for Node),\n * but detects Node specifically (not Deno, not Bun, etc).\n */\nexport function isNode() {\n return typeof process !== 'undefined' && process?.release?.name === 'node';\n}\n","// oxlint-disable-next-line import/no-cycle -- intentional cycle\nimport { JsonParseError } from '../error/error.util.js';\n// const possibleJsonStartTokens = ['{', '[', '\"']\nconst DETECT_JSON = /^\\s*[{[\"\\-\\d]/;\n/**\n * Attempts to parse object as JSON.\n * Returns original object if JSON parse failed (silently).\n */\nexport function _jsonParseIfPossible(obj, reviver) {\n // Optimization: only try to parse if it looks like JSON: starts with a json possible character\n if (typeof obj === 'string' && obj && DETECT_JSON.test(obj)) {\n try {\n return JSON.parse(obj, reviver);\n }\n catch { }\n }\n return obj;\n}\n/**\n * Convenience function that does JSON.parse, but doesn't throw on error,\n * instead - safely returns `undefined`.\n */\nexport function _jsonParseOrUndefined(obj, reviver) {\n // Optimization: only try to parse if it looks like JSON: starts with a json possible character\n if (typeof obj === 'string' && obj && DETECT_JSON.test(obj)) {\n try {\n return JSON.parse(obj, reviver);\n }\n catch { }\n }\n}\n/**\n * Same as JSON.parse, but throws JsonParseError:\n *\n * 1. It's message includes a piece of source text (truncated)\n * 2. It's data.text contains full source text\n */\nexport function _jsonParse(s, reviver) {\n try {\n return JSON.parse(s, reviver);\n }\n catch {\n throw new JsonParseError({\n text: s,\n });\n }\n}\n","/**\n * Converts the first character of string to upper case and the remaining to lower case.\n * Returns a type-safe capitalized string.\n */\nexport function _capitalize(s = '') {\n return (s.charAt(0).toUpperCase() + s.slice(1).toLowerCase());\n}\n/**\n * Convert a string to a type-safe uppercase string.\n */\nexport function _toUpperCase(s) {\n return s.toUpperCase();\n}\n/**\n * Convert a string to a type-safe lowercase string.\n */\nexport function _toLowercase(s) {\n return s.toLowerCase();\n}\nexport function _upperFirst(s = '') {\n return (s.charAt(0).toUpperCase() + s.slice(1));\n}\nexport function _lowerFirst(s) {\n return (s.charAt(0).toLowerCase() + s.slice(1));\n}\n/**\n * Like String.split(), but with limit, returning the tail together with last element.\n *\n * @returns Returns the new array of string segments.\n */\nexport function _split(str, separator, limit) {\n const parts = str.split(separator);\n if (parts.length <= limit)\n return parts;\n return [...parts.slice(0, limit - 1), parts.slice(limit - 1).join(separator)];\n}\nexport function _removeWhitespace(s) {\n return s.replaceAll(/\\s/g, '');\n}\n/**\n * _.truncate('hi-diddly-ho there, neighborino')\n * // => 'hi-diddly-ho there, neighbo...'\n */\nexport function _truncate(s, maxLen, omission = '...') {\n if (!s || s.length <= maxLen)\n return s;\n if (maxLen <= omission.length)\n return omission;\n return s.slice(0, maxLen - omission.length) + omission;\n}\n/**\n * _.truncateMiddle('abcdefghijklmnopqrstuvwxyz', 10)\n * // => 'abcd...xyz'\n */\nexport function _truncateMiddle(s, maxLen, omission = '...') {\n if (!s || s.length <= maxLen)\n return s;\n if (maxLen <= omission.length)\n return omission;\n const mark1 = Math.round((maxLen - omission.length) / 2);\n const mark2 = s.length - Math.floor((maxLen - omission.length) / 2);\n return s.slice(0, mark1) + omission + s.slice(mark2);\n}\n// These functions are modeled after Kotlin's String API\nexport function _substringBefore(s, delimiter) {\n const pos = s.indexOf(delimiter);\n return s.slice(0, pos !== -1 ? pos : undefined);\n}\nexport function _substringBeforeLast(s, delimiter) {\n const pos = s.lastIndexOf(delimiter);\n return s.slice(0, pos !== -1 ? pos : undefined);\n}\nexport function _substringAfter(s, delimiter) {\n const pos = s.indexOf(delimiter);\n return pos !== -1 ? s.slice(pos + delimiter.length) : s;\n}\nexport function _substringAfterLast(s, delimiter) {\n const pos = s.lastIndexOf(delimiter);\n return pos !== -1 ? s.slice(pos + delimiter.length) : s;\n}\n/**\n * Returns the substring between LAST `leftDelimiter` and then FIRST `rightDelimiter`.\n *\n * @example\n *\n * const s = '/Users/lalala/someFile.test.ts'\n * _substringBetweenLast(s, '/', '.')\n * // `someFile`\n */\nexport function _substringBetweenLast(s, leftDelimiter, rightDelimiter) {\n return _substringBefore(_substringAfterLast(s, leftDelimiter), rightDelimiter);\n}\n/**\n * Converts `\\n` (aka new-line) to `<br>`, to be presented in HTML.\n * Keeps `\\n`, so if it's printed in non-HTML environment it still looks ok-ish.\n */\nexport function _nl2br(s) {\n return s.replaceAll('\\n', '<br>\\n');\n}\n","import { isServerSide } from '../env.js';\n// oxlint-disable-next-line import/no-cycle -- intentional cycle\nimport { _jsonParseIfPossible } from '../string/json.util.js';\nimport { _truncate, _truncateMiddle } from '../string/string.util.js';\n// oxlint-disable-next-line import/no-cycle -- intentional cycle\nimport { _stringify } from '../string/stringify.js';\n/**\n * Useful to ensure that error in `catch (err) { ... }`\n * is indeed an Error (and not e.g `string` or `undefined`).\n * 99% of the cases it will be Error already.\n * Becomes more useful since TypeScript 4.4 made `err` of type `unknown` by default.\n *\n * Alternatively, if you're sure it's Error - you can use `_assertIsError(err)`.\n */\nexport function _anyToError(o, errorClass = Error, errorData) {\n let e;\n if (o instanceof errorClass) {\n e = o;\n }\n else {\n // If it's an instance of Error, but ErrorClass is something else (e.g AppError) - it'll be \"repacked\" into AppError\n const errorObject = _anyToErrorObject(o);\n e = _errorObjectToError(errorObject, errorClass);\n }\n if (errorData) {\n ;\n e.data ||= {};\n // Using Object.assign instead of ...data to not override err.data's non-enumerable properties\n Object.assign(e.data, errorData);\n }\n return e;\n}\n/**\n * Converts \"anything\" to ErrorObject.\n * Detects if it's HttpErrorResponse, HttpErrorObject, ErrorObject, Error, etc..\n * If object is Error - Error.message will be used.\n * Objects (not Errors) get converted to prettified JSON string (via `_stringify`).\n */\nexport function _anyToErrorObject(o, errorData) {\n let eo;\n if (_isErrorLike(o)) {\n eo = _errorLikeToErrorObject(o);\n }\n else {\n o = _jsonParseIfPossible(o);\n if (_isBackendErrorResponseObject(o)) {\n eo = o.error;\n }\n else if (_isErrorObject(o)) {\n eo = o;\n }\n else if (_isErrorLike(o)) {\n eo = _errorLikeToErrorObject(o);\n }\n else {\n // Here we are sure it has no `data` property,\n // so, fair to return `data: {}` in the end\n // Also we're sure it includes no \"error name\", e.g no `Error: ...`,\n // so, fair to include `name: 'Error'`\n const message = _stringify(o);\n eo = {\n name: 'Error',\n message,\n data: {}, // empty\n };\n }\n }\n Object.assign(eo.data, errorData);\n return eo;\n}\nexport function _errorLikeToErrorObject(e) {\n // If it's already an ErrorObject - just return it\n // AppError satisfies ErrorObject interface\n // Error does not satisfy (lacks `data`)\n // UPD: no, we expect a \"plain object\" here as an output,\n // because Error classes sometimes have non-enumerable properties (e.g data)\n if (!(e instanceof Error) && _isErrorObject(e)) {\n return e;\n }\n const obj = {\n name: e.name,\n message: e.message,\n data: { ...e.data }, // empty by default\n };\n if (e.stack)\n obj.stack = e.stack;\n if (e.cause) {\n obj.cause = _anyToErrorObject(e.cause);\n }\n return obj;\n}\nexport function _errorObjectToError(o, errorClass = Error) {\n if (o instanceof errorClass)\n return o;\n // Here we pass constructor values assuming it's AppError or sub-class of it\n // If not - will be checked at the next step\n // We cannot check `if (errorClass instanceof AppError)`, only `err instanceof AppError`\n const { name, cause } = o;\n const err = new errorClass(o.message, o.data, { name, cause });\n // name: err.name, // cannot be assigned to a readonly property like this\n // stack: o.stack, // also readonly e.g in Firefox\n if (o.stack) {\n Object.defineProperty(err, 'stack', {\n value: o.stack,\n });\n }\n if (!(err instanceof AppError)) {\n // Following actions are only needed for non-AppError-like errors\n Object.defineProperties(err, {\n name: {\n value: name,\n configurable: true,\n writable: true,\n },\n data: {\n value: o.data,\n writable: true,\n configurable: true,\n enumerable: false,\n },\n cause: {\n value: cause,\n writable: true,\n configurable: true,\n enumerable: true,\n },\n });\n Object.defineProperty(err.constructor, 'name', {\n value: name,\n configurable: true,\n writable: true,\n });\n }\n return err;\n}\n// These \"common\" error classes will not be printed as part of the Error snippet\nconst commonErrorClasses = new Set([\n 'Error',\n 'AppError',\n 'AssertionError',\n 'HttpRequestError',\n 'JoiValidationError',\n]);\n/**\n * Provides a short semi-user-friendly error message snippet,\n * that would allow to give a hint to the user what went wrong,\n * also to developers and CS to distinguish between different errors.\n *\n * It's not supposed to have full information about the error, just a small extract from it.\n */\nexport function _errorSnippet(err, opt = {}) {\n const { maxLineLength = 60, maxLines = 3 } = opt;\n const e = _anyToErrorObject(err);\n const lines = [errorObjectToSnippet(e)];\n let { cause } = e;\n while (cause && lines.length < maxLines) {\n lines.push('Caused by ' + errorObjectToSnippet(cause));\n cause = cause.cause; // insert DiCaprio Inception meme\n }\n return lines.map(line => _truncate(line, maxLineLength)).join('\\n');\n function errorObjectToSnippet(e) {\n // Return snippet if it was already prepared\n if (e.data.snippet)\n return e.data.snippet;\n // Code already serves the purpose of the snippet, so we can just return it\n if (e.data.code)\n return e.data.code;\n return [\n !commonErrorClasses.has(e.name) && e.name,\n // replace \"1+ white space characters\" with a single space\n e.message.replaceAll(/\\s+/gm, ' ').trim(),\n ]\n .filter(Boolean)\n .join(': ');\n }\n}\n// These duck-typing checks read properties of an arbitrary object, which may invoke its\n// property getters, which may throw (e.g a stateful getter, a Proxy trap).\n// A type guard should never throw - an object whose properties cannot even be read safely\n// is, by definition, not a well-behaved Error-like - hence try/catch returning false.\n// try/catch is free in V8 unless it actually catches, so there's no performance penalty.\nexport function _isBackendErrorResponseObject(o) {\n try {\n return _isErrorObject(o?.error);\n }\n catch {\n return false;\n }\n}\nexport function _isHttpRequestErrorObject(o) {\n try {\n return !!o && o.name === 'HttpRequestError' && typeof o.data?.requestUrl === 'string';\n }\n catch {\n return false;\n }\n}\n/**\n * Note: any instance of AppError is also automatically an ErrorObject\n */\nexport function _isErrorObject(o) {\n try {\n return (!!o &&\n typeof o === 'object' &&\n typeof o.name === 'string' &&\n typeof o.message === 'string' &&\n typeof o.data === 'object');\n }\n catch {\n return false;\n }\n}\nexport function _isErrorLike(o) {\n try {\n return (!!o && typeof o === 'object' && typeof o.name === 'string' && typeof o.message === 'string');\n }\n catch {\n return false;\n }\n}\n/**\n * Convenience function to safely add properties to Error's `data` object\n * (even if it wasn't previously existing).\n * Mutates err.\n * Returns err for convenience, so you can re-throw it directly.\n *\n * @example\n *\n * try {} catch (err) {\n * throw _errorDataAppend(err, {\n * backendResponseStatusCode: 401,\n * })\n * }\n */\nexport function _errorDataAppend(err, data) {\n if (!data)\n return err;\n return _anyToError(err, undefined, data);\n}\n/**\n * Base class for all our (not system) errors.\n *\n * message - \"technical\" message. Frontend decides to show it or not.\n * data - optional \"any\" payload.\n * data.userFriendly - if present, will be displayed to the User as is.\n *\n * Based on: `https://medium.com/@xpl/javascript-deriving-from-error-properly-8d2f8f315801`\n */\nexport class AppError extends Error {\n data;\n /**\n * `cause` here is normalized to be an ErrorObject\n */\n cause;\n /**\n * Experimental alternative static constructor.\n */\n static of(opt) {\n return new AppError(opt.message, opt.data, {\n name: opt.name,\n cause: opt.cause,\n });\n }\n constructor(message, data = {}, opt = {}) {\n super(message);\n // Here we default to `this.constructor.name` on Node, but to 'AppError' on the Frontend\n // because Frontend tends to minify class names, so `constructor.name` is not reliable\n const { name = isServerSide() ? this.constructor.name : 'AppError', cause } = opt;\n Object.defineProperties(this, {\n name: {\n value: name,\n configurable: true,\n writable: true,\n },\n data: {\n value: data,\n writable: true,\n configurable: true,\n enumerable: false,\n },\n });\n if (cause) {\n Object.defineProperty(this, 'cause', {\n value: _anyToErrorObject(cause),\n writable: true,\n configurable: true,\n enumerable: true, // unlike standard - setting it to true for \"visibility\"\n });\n }\n else {\n delete this.cause; // otherwise it's printed as `cause: undefined`\n }\n // this is to allow changing this.constuctor.name to a non-minified version\n Object.defineProperty(this.constructor, 'name', {\n value: name,\n configurable: true,\n writable: true,\n });\n // todo: check if it's needed at all!\n // if (Error.captureStackTrace) {\n // Error.captureStackTrace(this, this.constructor)\n // } else {\n // Object.defineProperty(this, 'stack', {\n // value: new Error().stack, // eslint-disable-line unicorn/error-message\n // writable: true,\n // configurable: true,\n // })\n // }\n }\n}\n/**\n * Error that is thrown when Http Request was made and returned an error.\n * Thrown by, for example, Fetcher.\n *\n * On the Frontend this Error class represents the error when calling the API,\n * contains all the necessary request and response information.\n *\n * On the Backend, similarly, it represents the error when calling some 3rd-party API\n * (backend-to-backend call).\n * On the Backend it often propagates all the way to the Backend error handler,\n * where it would be wrapped in BackendErrorResponseObject.\n *\n * Please note that `ErrorData.backendResponseStatusCode` is NOT exactly the same as\n * `HttpRequestErrorData.responseStatusCode`.\n * E.g 3rd-party call may return 401, but our Backend will still wrap it into an 500 error\n * (by default).\n */\nexport class HttpRequestError extends AppError {\n constructor(message, data, opt) {\n if (data.response) {\n Object.defineProperty(data, 'response', {\n enumerable: false,\n });\n }\n super(message, data, { ...opt, name: 'HttpRequestError' });\n }\n}\nexport class AssertionError extends AppError {\n constructor(message, data) {\n super(message, data, { name: 'AssertionError' });\n }\n}\nexport class JsonParseError extends AppError {\n constructor(data) {\n const message = ['Failed to parse', data.text && _truncateMiddle(data.text, 200)]\n .filter(Boolean)\n .join(': ');\n super(message, data, { name: 'JsonParseError' });\n }\n}\nexport class TimeoutError extends AppError {\n constructor(message, data, opt) {\n super(message, data, { ...opt, name: 'TimeoutError' });\n }\n}\n/**\n * It is thrown when Error was expected, but didn't happen\n * (\"pass\" happened instead).\n * \"Pass\" means \"no error\".\n */\nexport class UnexpectedPassError extends AppError {\n constructor(message) {\n super(message || 'expected error was not thrown', {}, {\n name: 'UnexpectedPassError',\n });\n }\n}\n","/**\n * JSON.stringify that avoids circular references, prints them as [Circular ~]\n *\n * Based on: https://github.com/moll/json-stringify-safe/\n */\nexport function _safeJsonStringify(obj, replacer, spaces, cycleReplacer) {\n try {\n // Try native first (as it's ~3 times faster)\n return JSON.stringify(obj, replacer, spaces);\n }\n catch {\n // Native failed - resort to the \"safe\" serializer\n return JSON.stringify(obj, serializer(replacer, cycleReplacer), spaces);\n }\n}\nfunction serializer(replacer, cycleReplacer) {\n const stack = [];\n const keys = [];\n cycleReplacer ??= (_key, value) => {\n if (stack[0] === value)\n return '[Circular ~]';\n return '[Circular ~.' + keys.slice(0, stack.indexOf(value)).join('.') + ']';\n };\n return function (key, value) {\n if (stack.length > 0) {\n const thisPos = stack.indexOf(this);\n if (thisPos !== -1) {\n stack.splice(thisPos + 1);\n keys.splice(thisPos, Infinity, key);\n }\n else {\n stack.push(this);\n keys.push(key);\n }\n if (stack.includes(value)) {\n value = cycleReplacer.call(this, key, value);\n }\n }\n else {\n stack.push(value);\n }\n return replacer == null ? value : replacer.call(this, key, value);\n };\n}\n","// oxlint-disable-next-line import/no-cycle -- intentional cycle\nimport { _isBackendErrorResponseObject, _isErrorLike, _isErrorObject } from '../error/error.util.js';\n// oxlint-disable-next-line import/no-cycle -- intentional cycle\nimport { _jsonParseIfPossible } from './json.util.js';\nimport { _safeJsonStringify } from './safeJsonStringify.js';\nimport { _truncateMiddle } from './string.util.js';\nconst supportsAggregateError = typeof globalThis.AggregateError === 'function';\nlet globalStringifyFunction = _safeJsonStringify;\n/**\n * Allows to set Global \"stringifyFunction\" that will be used to \"pretty-print\" objects\n * in various cases.\n *\n * Used, for example, by _stringify() to pretty-print objects/arrays.\n *\n * Defaults to _safeJsonStringify.\n *\n * Node.js project can set it to _inspect, which allows to use `util.inspect`\n * as pretty-printing function.\n *\n * It's recommended that this function is circular-reference-safe.\n */\nexport function setGlobalStringifyFunction(fn) {\n globalStringifyFunction = fn;\n}\nexport function resetGlobalStringifyFunction() {\n globalStringifyFunction = _safeJsonStringify;\n}\n/**\n * Inspired by `_inspect` from nodejs-lib, which is based on util.inpect that is not available in the Browser.\n * Potentially can do this (with extra 2Kb gz size): https://github.com/deecewan/browser-util-inspect\n *\n * Transforms ANY to human-readable string (via JSON.stringify pretty).\n * Safe (no error throwing).\n *\n * Correctly prints Errors, AppErrors, ErrorObjects: error.message + \\n + _stringify(error.data)\n *\n * Enforces max length (default to 1000, pass 0 to skip it).\n *\n * Logs numbers as-is, e.g: `6`.\n * Logs strings as-is (without single quotes around, unlike default util.inspect behavior).\n * Otherwise - just uses JSON.stringify().\n *\n * Returns 'empty_string' if empty string is passed.\n * Returns 'undefined' if undefined is passed (default util.inspect behavior).\n */\nexport function _stringify(obj, opt = {}) {\n if (obj === undefined)\n return 'undefined';\n if (obj === null)\n return 'null';\n if (typeof obj === 'function')\n return 'function';\n if (typeof obj === 'symbol')\n return obj.toString();\n let s;\n // Parse JSON string, if possible\n obj = _jsonParseIfPossible(obj); // in case it's e.g non-pretty JSON, or even a stringified ErrorObject\n //\n // HttpErrorResponse\n //\n if (_isBackendErrorResponseObject(obj)) {\n return _stringify(obj.error, opt);\n }\n if (obj instanceof Error || _isErrorLike(obj)) {\n s = stringifyErrorLike(obj, opt);\n }\n else if (typeof obj === 'string') {\n s = obj.trim() || 'empty_string';\n // todo: think about it more\n // Stringifying it like a JSON would.\n // To highlight that it's a String (and not a Number) - using double-quotes, JSON-like.\n // s = `\"${obj}\"`\n }\n else if (typeof obj === 'number') {\n s = String(obj);\n // todo: support RegExp and Date, when split between Browser and Node stringification is implemented\n // } else if (obj instanceof RegExp) {\n // s = String(obj)\n // } else if (obj instanceof Date) {\n // s = `Date (${obj.toISOString()})`\n }\n else {\n //\n // Other\n //\n if (obj instanceof Map) {\n // todo: double-check it, maybe Node's inspect has good built-in stringification\n obj = Object.fromEntries(obj);\n }\n else if (obj instanceof Set) {\n obj = Array.from(obj);\n }\n try {\n const { stringifyFn = globalStringifyFunction } = opt;\n s = stringifyFn(obj, undefined, 2);\n }\n catch {\n s = String(obj); // fallback\n }\n }\n // Shouldn't happen, but some weird input parameters may return this\n if (s === undefined)\n return 'undefined';\n // Handle maxLen\n const { maxLen = 10_000 } = opt;\n if (maxLen && s.length > maxLen) {\n return _truncateMiddle(s, maxLen, `\\n... ${Math.ceil(s.length / 1024)} Kb message truncated ...\\n`);\n }\n return s;\n}\nfunction stringifyErrorLike(obj, opt) {\n const { includeErrorCause = true } = opt;\n let s = [obj.name, obj.message].filter(Boolean).join(': ');\n if (typeof obj.code === 'string') {\n // Error that has no `data`, but has `code` property\n s += `\\ncode: ${obj.code}`;\n }\n if (opt.includeErrorData && _isErrorObject(obj) && Object.keys(obj.data).length) {\n s += '\\n' + _stringify(obj.data, opt);\n }\n if (opt.includeErrorStack && obj.stack) {\n // Here we're using the previously-generated \"title line\" (e.g \"Error: some_message\"),\n // concatenating it with the Stack (but without the title line of the Stack)\n // This is to fix the rare error (happened with Got) where `err.message` was changed,\n // but err.stack had \"old\" err.message\n // This should \"fix\" that\n const sLines = s.split('\\n').length;\n s = [s, ...obj.stack.split('\\n').slice(sLines)].join('\\n');\n }\n if (supportsAggregateError && obj instanceof AggregateError && obj.errors.length) {\n s = [\n s,\n `${obj.errors.length} error(s):`,\n ...obj.errors.map((err, i) => `${i + 1}. ${_stringify(err, opt)}`),\n ].join('\\n');\n }\n if (obj.cause && includeErrorCause) {\n s = s + '\\nCaused by: ' + _stringify(obj.cause, opt);\n }\n return s;\n}\n","import { _deepEquals } from '../object/deepEquals.js';\nimport { _stringify } from '../string/stringify.js';\nimport { _isBackendErrorResponseObject, _isErrorObject, AssertionError } from './error.util.js';\n/**\n * Evaluates the `condition` (casts it to Boolean).\n * Expects it to be truthy, otherwise throws AppError.\n *\n * Should be used NOT for \"expected\" / user-facing errors, but\n * vice-versa - for completely unexpected and 100% buggy \"should never happen\" cases.\n *\n * It'll result in http 500 on the server (cause that's the right code for \"unexpected\" errors).\n * Pass { backendResponseStatusCode: x } at errorData argument to override the http code (will be picked up by backend-lib).\n *\n * API is similar to Node's assert(), except:\n * 1. Throws js-lib's AppError\n * 2. Has a default message, if not provided\n *\n * Since 2024-07-10 it no longer sets `userFriendly: true` by default.\n */\nexport function _assert(condition, // will be evaluated as Boolean\nmessage, errorData) {\n if (!condition) {\n throw new AssertionError(message || 'condition failed', {\n ...errorData,\n });\n }\n}\n/**\n * Like _assert(), but prints more helpful error message.\n * API is similar to Node's assert.equals().\n *\n * Does SHALLOW, but strict equality (===), use _assertDeepEquals() for deep equality.\n */\nexport function _assertEquals(actual, expected, message, errorData) {\n if (actual !== expected) {\n const msg = message ||\n ['not equal', `expected: ${_stringify(expected)}`, `got : ${_stringify(actual)}`]\n .filter(Boolean)\n .join('\\n');\n throw new AssertionError(msg, {\n ...errorData,\n });\n }\n}\n/**\n * Like _assert(), but prints more helpful error message.\n * API is similar to Node's assert.deepEquals().\n *\n * Does DEEP equality via _deepEquals()\n */\nexport function _assertDeepEquals(actual, expected, message, errorData) {\n if (!_deepEquals(actual, expected)) {\n const msg = message ||\n ['not deeply equal', `expected: ${_stringify(expected)}`, `got : ${_stringify(actual)}`]\n .filter(Boolean)\n .join('\\n');\n throw new AssertionError(msg, {\n ...errorData,\n });\n }\n}\nexport function _assertIsError(err, errorClass = Error) {\n if (!(err instanceof errorClass)) {\n throw new AssertionError(`Expected to be instanceof ${errorClass.name}, actual typeof: ${typeof err}`);\n }\n}\n/**\n * Asserts that passed object is indeed an Error of defined ErrorClass.\n * If yes - returns peacefully (with TypeScript assertion).\n * In not - throws (re-throws) that error up.\n */\nexport function _assertErrorClassOrRethrow(err, errorClass) {\n if (!(err instanceof errorClass)) {\n // re-throw\n throw err;\n }\n}\nexport function _assertIsErrorObject(obj) {\n if (!_isErrorObject(obj)) {\n throw new AssertionError(`Expected to be ErrorObject, actual typeof: ${typeof obj}`);\n }\n}\nexport function _assertIsBackendErrorResponseObject(obj) {\n if (!_isBackendErrorResponseObject(obj)) {\n throw new AssertionError(`Expected to be BackendErrorResponseObject, actual typeof: ${typeof obj}`);\n }\n}\nexport function _assertIsString(v, message) {\n _assertTypeOf(v, 'string', message);\n}\nexport function _assertIsNumber(v, message) {\n _assertTypeOf(v, 'number', message);\n}\nexport function _assertTypeOf(v, expectedType, message) {\n if (typeof v !== expectedType) {\n const msg = message || `Expected typeof ${expectedType}, actual typeof: ${typeof v}`;\n throw new AssertionError(msg);\n }\n}\n/**\n * Casts an arbitrary number as UnixTimestamp.\n * Right now does not perform any validation (unlike `asUnixTimestamp2000`),\n * but only type casting.\n */\nexport function asUnixTimestamp(n) {\n return n;\n}\nconst TS_2500 = 16725225600; // 2500-01-01\nconst TS_2000 = 946684800; // 2000-01-01\n/**\n * Casts an arbitrary number as UnixTimestamp2000.\n * Throws if the number is not inside 2000-01-01 and 2500-01-01 time interval,\n * which would indicate a bug.\n */\nexport function asUnixTimestamp2000(n) {\n if (!n || n < TS_2000 || n > TS_2500) {\n throw new AssertionError(`Number is not a valid UnixTimestamp2000: ${n}`, {\n fingerprint: 'asUnixTimestamp2000',\n });\n }\n return n;\n}\n","import { pDefer } from './pDefer.js';\n/**\n * Promisified version of setTimeout.\n *\n * Can return a value.\n * If value is instanceof Error - rejects the Promise instead of resolving.\n */\nexport async function pDelay(ms = 0, value) {\n return await new Promise((resolve, reject) => setTimeout(value instanceof Error ? reject : resolve, ms, value));\n}\n/**\n * Like pDelay, but also resolves early (without an error) as soon as\n * the passed AbortSignal aborts.\n */\nexport async function pDelaySignal(ms, signal) {\n if (signal?.aborted)\n return;\n await new Promise(resolve => {\n const timer = setTimeout(done, ms);\n function done() {\n clearTimeout(timer);\n signal?.removeEventListener('abort', done);\n resolve();\n }\n signal?.addEventListener('abort', done);\n });\n}\n/* oxlint-disable @typescript-eslint/promise-function-async */\n/**\n * Promisified version of setTimeout.\n *\n * Wraps the passed function with try/catch,\n * catch will propagate to pDelayFn rejection,\n * otherwise pDelayFn will resolve with returned value.\n *\n * On abort() - clears the Timeout and immediately resolves the Promise with void.\n */\nexport function pDelayFn(ms, fn) {\n const p = pDefer();\n const timer = setTimeout(async () => {\n try {\n p.resolve(await fn());\n }\n catch (err) {\n p.reject(err);\n }\n }, ms);\n p.abort = () => {\n clearTimeout(timer);\n // p.rejectAborted(reason) // nope\n p.resolve();\n };\n return p;\n}\n","/**\n * using _ = blockTimer()\n * // will log \"took 1.234 sec\" on dispose\n *\n * using _ = blockTimer('named')\n * // will log \"named took 1.234 sec\" on dispose\n *\n * @experimental\n */\nexport function _blockTimer(name) {\n const started = Date.now();\n return {\n [Symbol.dispose]() {\n console.log(`${name ? name + ' ' : ''}took ${_since(started)}`);\n },\n };\n}\n/**\n * Returns time passed since `from` until `until` (default to Date.now())\n */\nexport function _since(from, until = Date.now()) {\n return _ms(until - from);\n}\n/**\n * Returns, e.g:\n * 125 ms\n * 1.125 sec\n * 11 sec\n * 1m12s\n * 59m2s\n * 1h3m12s\n */\nexport function _ms(millis) {\n // <1 sec\n if (millis < 1000)\n return `${Math.round(millis)} ms`;\n // < 10 sec\n if (millis < 10_000) {\n const s = millis / 1000;\n return `${s.toFixed(2)} sec`;\n }\n const sec = Math.floor(millis / 1000) % 60;\n const min = Math.floor(millis / (60 * 1000)) % 60;\n const hrs = Math.floor(millis / (3600 * 1000));\n // <1 hr\n if (hrs === 0) {\n // <1 min\n if (min === 0)\n return `${sec} sec`;\n return `${min}m${sec}s`;\n }\n if (hrs < 24) {\n return `${hrs}h${min}m`;\n }\n if (hrs < 48) {\n return `${Math.round(hrs + min / 60)}h`;\n }\n // >= 48 hours\n const days = Math.floor(hrs / 24);\n return `${days} days`;\n}\n","export function _randomInt(minIncl, maxIncl) {\n return Math.floor(Math.random() * (maxIncl - minIncl + 1) + minIncl);\n}\n/**\n * Returns random item from an array.\n * Should be used on non-empty arrays! (otherwise will return undefined,\n * which is not reflected in the output type)\n */\nexport function _randomArrayItem(array) {\n return array[_randomInt(0, array.length - 1)];\n}\n/**\n * Convenience function to \"throttle\" some code - run it less often.\n *\n * @example\n *\n * if (_runLessOften(10)) {\n * // this code will run only 10% of the time\n * }\n */\nexport function _runLessOften(percent) {\n return Math.random() * 100 < percent;\n}\n// todo: _.random to support floats\n/**\n * _isBetween(-10, 1, 5) // false\n * _isBetween(1, 1, 5) // true\n * _isBetween(3, 1, 5) // true\n * _isBetween(5, 1, 5) // false\n * _isBetween(7, 1, 5) // false\n *\n * Also works with strings:\n * _isBetween('2020-01-03', '2020-01-01', '2020-01-05') // true\n */\nexport function _isBetween(x, min, max, incl) {\n if (x < min || x > max)\n return false;\n if (x === max && incl === '[)')\n return false;\n return true;\n}\nexport function _clamp(x, minIncl, maxIncl) {\n if (x <= minIncl)\n return minIncl;\n if (x >= maxIncl)\n return maxIncl;\n return x;\n}\n/**\n * Same as .toFixed(), but conveniently casts the output to Number.\n *\n * @example\n *\n * _toFixed(1.2345, 2)\n * // 1.23\n *\n * _toFixed(1.10, 2)\n * // 1.1\n */\nexport function _toFixed(n, fractionDigits) {\n return Number(n.toFixed(fractionDigits));\n}\n/**\n * Same as .toPrecision(), but conveniently casts the output to Number.\n *\n * @example\n *\n * _toPrecision(1634.56, 1)\n * // 2000\n *\n * _toPrecision(1634.56, 2)\n * // 1600\n */\nexport function _toPrecision(n, precision) {\n return Number(n.toPrecision(precision));\n}\n/**\n * @example\n *\n * _round(1634, 1000) // 2000\n * _round(1634, 500) // 1500\n * _round(1634, 100) // 1600\n * _round(1634, 10) // 1630\n * _round(1634, 1) // 1634\n * _round(1634.5678, 0.1) // 1634.6\n * _round(1634.5678, 0.01) // 1634.57\n */\nexport function _round(n, precisionUnit) {\n if (precisionUnit >= 1) {\n return Math.round(n / precisionUnit) * precisionUnit;\n }\n const v = Math.floor(n) + Math.round((n % 1) / precisionUnit) * precisionUnit;\n return Number(v.toFixed(String(precisionUnit).length - 2)); // '0.\n}\n","import { _errorDataAppend, TimeoutError } from '../error/error.util.js';\nimport { _typeCast } from '../types.js';\n/**\n * Decorates a Function with a timeout.\n * Returns a decorated Function.\n *\n * Throws an Error if the Function is not resolved in a certain time.\n * If the Function rejects - passes this rejection further.\n */\nexport function pTimeoutFn(fn, opt) {\n opt.name ||= fn.name;\n if (!opt.timeout) {\n return fn;\n }\n return async function pTimeoutInternalFn(...args) {\n return await pTimeout(() => fn.apply(this, args), opt);\n };\n}\n/**\n * Decorates a Function with a timeout and immediately calls it.\n *\n * Throws an Error if the Function is not resolved in a certain time.\n * If the Function rejects - passes this rejection further.\n */\nexport async function pTimeout(fn, opt) {\n const ac = new AbortController();\n const { signal } = ac;\n if (!opt.timeout) {\n // short-circuit to direct execution if 0 timeout is passed\n return await fn(signal);\n }\n const { timeout, name = fn.name || 'pTimeout function', onTimeout } = opt;\n const fakeError = opt.fakeError || new Error('TimeoutError');\n return await new Promise(async (resolve, reject) => {\n // Prepare the timeout timer\n const timer = setTimeout(() => {\n const err = new TimeoutError(`\"${name}\" timed out after ${timeout} ms`, opt.errorData);\n // keep original stack\n err.stack = fakeError.stack.replace('Error: TimeoutError', 'TimeoutError: ' + err.message);\n if (onTimeout) {\n try {\n resolve(onTimeout(err));\n }\n catch (err) {\n _typeCast(err);\n // keep original stack\n err.stack = fakeError.stack.replace('Error: TimeoutError', err.name + ': ' + err.message);\n // oxlint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject(_errorDataAppend(err, opt.errorData));\n }\n ac.abort(err);\n return;\n }\n reject(err);\n ac.abort(err);\n }, timeout);\n // Execute the Function\n try {\n resolve(await fn(signal));\n }\n catch (err) {\n // oxlint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject(err);\n }\n finally {\n clearTimeout(timer);\n }\n });\n}\n","/**\n * Parses `location.search` string (e.g `?a=1&b=2`) into a StringMap, e.g:\n * `{ a: '1', b: '2' }`\n *\n * Pass `location.search` to it in the Frontend, or any other string on the Backend (where `location.search` is not available).\n *\n * Works both with and without leading `?` character.\n *\n * Yes, there's `URLSearchParams` existing in the Frontend (not in Node yet), but it's API is not\n * as convenient. And the implementation here is super-small.\n *\n * Goal of this function is to produce exactly same output as URLSearchParams would.\n */\nexport function _parseQueryString(search) {\n const qs = {};\n search\n .slice(search.startsWith('?') ? 1 : 0)\n .split('&')\n .forEach(p => {\n const [k, v] = p.split('=');\n if (!k)\n return;\n qs[decodeURIComponent(k)] = decodeURIComponent(v || '');\n });\n return qs;\n}\n/**\n * A wrapper around `new URL(href)`, but it returns `null` instead of throwing an error.\n * While `URL.parse` exists, and behaves similarly, it's not widely supported.\n *\n * `null` was chosen instead of `undefined` in the return type union to make it easier to move to `URL.parse` if it ever becomes widely supported.\n */\nexport function _toUrlOrNull(url, base) {\n if (typeof url !== 'string')\n return null;\n try {\n return new URL(url, base || undefined);\n }\n catch {\n return null;\n }\n}\n","export const HTTP_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD'];\n","/// <reference lib=\"es2023\" preserve=\"true\" />\n/// <reference lib=\"dom\" preserve=\"true\" />\n/// <reference lib=\"dom.iterable\" preserve=\"true\" />\nimport { abortSignalAnyOrUndefined, abortSignalTimeoutOrUndefined } from '../abort.js';\nimport { _ms, _since } from '../datetime/time.util.js';\nimport { isServerSide } from '../env.js';\nimport { _assertErrorClassOrRethrow, _assertIsError } from '../error/assert.js';\nimport { _anyToError, _anyToErrorObject, _errorDataAppend, _errorLikeToErrorObject, HttpRequestError, UnexpectedPassError, } from '../error/error.util.js';\nimport { consoleLogger } from '../log/commonLogger.js';\nimport { _clamp } from '../number/number.util.js';\nimport { _filterFalsyValues, _filterNullishValues, _filterUndefinedValues, _mapKeys, _merge, _omit, _pick, } from '../object/object.util.js';\nimport { pDelaySignal } from '../promise/pDelay.js';\nimport { pTimeout } from '../promise/pTimeout.js';\nimport { _toUrlOrNull } from '../string/index.js';\nimport { _jsonParse, _jsonParseIfPossible } from '../string/json.util.js';\nimport { HTTP_METHODS } from './http.model.js';\n/**\n * Experimental wrapper around Fetch.\n * Works in both Browser and Node, using `globalThis.fetch`.\n */\nexport class Fetcher {\n /**\n * Included in UserAgent when run in Node.\n * In the browser it's not included, as we want \"browser own\" UserAgent to be included instead.\n *\n * Version is to be incremented every time a difference in behaviour (or a bugfix) is done.\n */\n static VERSION = 5;\n /**\n * userAgent is statically exposed as Fetcher.userAgent.\n * It can be modified globally, and will be used (read) at the start of every request.\n */\n static userAgent = isServerSide() ? `fetcher/${this.VERSION}` : undefined;\n constructor(cfg = {}) {\n if (typeof globalThis.fetch !== 'function') {\n throw new TypeError('globalThis.fetch is not available');\n }\n this.cfg = this.normalizeCfg(cfg);\n // Dynamically create all helper methods\n for (const method of HTTP_METHODS) {\n const m = method.toLowerCase();\n this[`${m}Void`] = async (url, opt) => {\n return await this.fetch({\n url,\n method,\n responseType: 'void',\n ...opt,\n });\n };\n if (method === 'HEAD') {\n continue; // responseType=text\n }\n ;\n this[`${m}Text`] = async (url, opt) => {\n return await this.fetch({\n url,\n method,\n responseType: 'text',\n ...opt,\n });\n };\n this[m] = async (url, opt) => {\n return await this.fetch({\n url,\n method,\n responseType: 'json',\n ...opt,\n });\n };\n }\n }\n /**\n * Add BeforeRequest hook at the end of the hooks list.\n */\n onBeforeRequest(hook) {\n ;\n (this.cfg.hooks.beforeRequest ||= []).push(hook);\n return this;\n }\n onAfterResponse(hook) {\n ;\n (this.cfg.hooks.afterResponse ||= []).push(hook);\n return this;\n }\n onBeforeRetry(hook) {\n ;\n (this.cfg.hooks.beforeRetry ||= []).push(hook);\n return this;\n }\n onError(hook) {\n ;\n (this.cfg.hooks.onError ||= []).push(hook);\n return this;\n }\n /**\n * Init hooks run lazily, once per Fetcher instance, before the first request.\n * See FetcherInitHook docs.\n */\n onInit(hook) {\n ;\n (this.cfg.hooks.init ||= []).push(hook);\n return this;\n }\n /**\n * Clears the cached result of the init hooks, so they re-run before the next request.\n * Useful when the state acquired during init (e.g an auth token) becomes stale.\n * See also `cfg.hooks.shouldReinit`, which calls this automatically.\n */\n resetInit() {\n this.initPromise = undefined;\n this.initGeneration++;\n }\n cfg;\n initPromise;\n initGeneration = 0;\n static create(cfg = {}) {\n return new Fetcher(cfg);\n }\n // These methods are generated dynamically in the constructor\n // These default methods use responseType=json\n get;\n post;\n put;\n patch;\n delete;\n // responseType=text\n getText;\n postText;\n putText;\n patchText;\n deleteText;\n // responseType=void (no body fetching/parsing)\n getVoid;\n postVoid;\n putVoid;\n patchVoid;\n deleteVoid;\n headVoid;\n /**\n * Small convenience wrapper that allows to issue GraphQL queries.\n * In practice, all it does is:\n * - Defines convenience `query` input option\n * - Unwraps `response.data`\n * - Unwraps `response.errors` and throws, if it's defined (as GQL famously returns http 200 even for errors)\n *\n * Currently it only unwraps and uses the first error from the `errors` array, for simplicity.\n */\n async queryGraphQL(opt) {\n opt = { ...opt }; // avoid mutating the input options\n opt.method ||= this.cfg.init.method; // defaults to GET\n const payload = _filterFalsyValues({\n query: opt.query,\n variables: opt.variables,\n });\n // Checking the query length, and not allowing to use GET if above 1900\n if (opt.method === 'GET' && opt.query.length > 1900) {\n opt.method = 'POST';\n }\n if (opt.method === 'GET') {\n opt.searchParams = {\n ...opt.searchParams,\n ...payload,\n };\n }\n else {\n opt.json = payload;\n }\n const res = await this.doFetch(opt);\n if (res.err) {\n throw res.err;\n }\n if (res.body.errors) {\n // unwrap errors and throw\n const err = res.body.errors[0];\n // todo: consider creating a new GraphQLError class for this\n throw new HttpRequestError(err.message, {\n ...payload, // query and variables\n errors: res.body.errors, // full errors payload returned\n response: res.fetchResponse,\n responseStatusCode: res.statusCode,\n requestUrl: res.req.fullUrl,\n requestBaseUrl: this.cfg.baseUrl,\n requestMethod: res.req.init.method,\n requestSignature: res.signature,\n requestName: res.req.requestName,\n fetcherName: this.cfg.name,\n requestDuration: Date.now() - res.req.started,\n });\n }\n const { data } = res.body;\n if (opt.unwrapObject) {\n return data[opt.unwrapObject];\n }\n return data;\n }\n // responseType=bytes\n /**\n * Returns response body as Uint8Array.\n */\n async getBytes(url, opt) {\n return await this.fetch({\n url,\n responseType: 'bytes',\n ...opt,\n });\n }\n // responseType=readableStream\n /**\n * Returns raw fetchResponse.body, which is a ReadableStream<Uint8Array>\n *\n * More on streams and Node interop:\n * https://css-tricks.com/web-streams-everywhere-and-fetch-for-node-js/\n */\n async getReadableStream(url, opt) {\n return await this.fetch({\n url,\n responseType: 'readableStream',\n ...opt,\n });\n }\n async fetch(opt) {\n const res = await this.doFetch(opt);\n if (res.err && (res.req.throwHttpErrors || res.fetchResponse?.ok !== false)) {\n // With throwHttpErrors=false only http errors (response received, but !ok) are returned instead of thrown.\n // Other errors (network failure, timeout, body parsing) are still thrown.\n throw res.err;\n }\n return res.body;\n }\n /**\n * Like `fetch`, but returns the whole FetcherSuccessResponse, not just the body.\n * Allows to access response metadata, e.g `fetchResponse.headers` and `statusCode`,\n * while still throwing on errors (unlike `doFetch`).\n *\n * Note: `throwHttpErrors: false` is ignored here, http errors are always thrown -\n * otherwise the returned FetcherSuccessResponse type would lie.\n * Use `doFetch` if you don't want throwing.\n */\n async fetchWithMeta(opt) {\n const res = await this.doFetch(opt);\n if (res.err) {\n throw res.err;\n }\n return res;\n }\n /**\n * Execute fetch and expect/assert it to return an Error (which will be wrapped in\n * HttpRequestError as it normally would).\n * If fetch succeeds, which is unexpected, it'll throw an UnexpectedPass error.\n * Useful in unit testing.\n */\n async expectError(opt) {\n const res = await this.doFetch(opt);\n if (!res.err) {\n throw new UnexpectedPassError('Fetch was expected to error');\n }\n _assertIsError(res.err, HttpRequestError);\n return res.err;\n }\n /**\n * Like pTry - returns a [err, data] tuple (aka ErrorDataTuple).\n * err, if defined, is strictly HttpRequestError.\n * UPD: actually not, err is typed as Error, as it feels unsafe to guarantee error type.\n * UPD: actually yes - it will return HttpRequestError, and throw if there's an error\n * of any other type.\n */\n async tryFetch(opt) {\n const res = await this.doFetch(opt);\n if (res.err) {\n _assertErrorClassOrRethrow(res.err, HttpRequestError);\n return [res.err, null];\n }\n return [null, res.body];\n }\n /**\n * Returns FetcherResponse.\n * Never throws, returns `err` property in the response instead.\n * (Exception: errors thrown from init/beforeRequest hooks are re-thrown as-is.)\n * Use this method instead of `throwHttpErrors: false` or try-catching.\n *\n * Note: responseType defaults to the Fetcher's cfg responseType (`json`, unless overridden).\n */\n async doFetch(opt) {\n let initGeneration = 0;\n if (this.cfg.hooks.init) {\n try {\n await (this.initPromise ??= this.runInitHooks());\n }\n catch (err) {\n // Reset, so init hooks are re-attempted on the next request\n this.resetInit();\n throw err;\n }\n initGeneration = this.initGeneration;\n }\n const req = this.normalizeOptions(opt);\n const { logger } = this.cfg;\n const { init: { method }, } = req;\n const timeoutMillis = req.timeoutSeconds ? req.timeoutSeconds * 1000 : undefined;\n for (const hook of this.cfg.hooks.beforeRequest || []) {\n await hook(req);\n }\n const isFullUrl = req.fullUrl.includes('://');\n const fullUrl = isFullUrl ? new URL(req.fullUrl) : undefined;\n const shortUrl = fullUrl ? this.getShortUrl(fullUrl) : req.fullUrl;\n const signature = [method, shortUrl].join(' ');\n const res = {\n req,\n retryStatus: {\n retryAttempt: 0,\n retryStopped: false,\n retryTimeout: req.retry.timeout,\n },\n signature,\n };\n while (!res.retryStatus.retryStopped) {\n req.started = Date.now();\n res.body = undefined;\n req.init.signal = abortSignalAnyOrUndefined([\n abortSignalTimeoutOrUndefined(timeoutMillis),\n opt.signal,\n ]);\n if (req.logRequest) {\n const { retryAttempt } = res.retryStatus;\n logger.log([' >>', signature, retryAttempt && `try#${retryAttempt + 1}/${req.retry.count + 1}`]\n .filter(Boolean)\n .join(' '));\n if (req.logRequestBody && req.init.body) {\n logger.log({ body: req.init.body }); // todo: check if we can _inspect it\n }\n }\n try {\n res.fetchResponse = await (req.overrideFetchFn || Fetcher.callNativeFetch)(req.fullUrl, req.init, req.fetchFn);\n res.ok = res.fetchResponse.ok;\n // important to set it to undefined, otherwise it can keep the previous value (from previous try)\n res.err = undefined;\n }\n catch (err) {\n // For example, CORS error would result in \"TypeError: failed to fetch\" here\n // or, `fetch failed` with the cause of `unexpected redirect`\n // AbortSignal.timeout() throws a DOMException with name \"TimeoutError\"\n res.err = _anyToError(err);\n res.ok = false;\n // important to set it to undefined, otherwise it can keep the previous value (from previous try)\n res.fetchResponse = undefined;\n }\n res.statusFamily = this.getStatusFamily(res);\n res.statusCode = res.fetchResponse?.status;\n if (res.fetchResponse?.ok) {\n try {\n // We are applying a separate Timeout (as long as original Timeout for now) to \"download and parse the body\"\n await pTimeout(async () => await this.onOkResponse(res), {\n // 0 means \"no timeout\" for pTimeout\n timeout: timeoutMillis ?? 0,\n name: 'Fetcher.downloadBody',\n });\n }\n catch (err) {\n // Important to cancel the original request to not keep it running (and occupying resources)\n // UPD: no, we probably don't need to, because \"request\" has already completed, it's just the \"body\" is pending\n // if (err instanceof TimeoutError) {}\n // onOkResponse can still fail, e.g when loading/parsing json, text or doing other response manipulation\n res.err = _anyToError(err);\n res.ok = false;\n await this.onNotOkResponse(res);\n }\n }\n else {\n // !res.ok\n await this.onNotOkResponse(res);\n }\n }\n if (res.err) {\n _errorDataAppend(res.err, req.errorData);\n req.onError?.(res.err);\n for (const hook of this.cfg.hooks.onError || []) {\n await hook(res.err);\n }\n }\n for (const hook of this.cfg.hooks.afterResponse || []) {\n await hook(res);\n }\n if (res.err && (await this.detectStaleInit(opt, res, initGeneration))) {\n // Stale init (e.g expired auth token) was detected and reset - retry the request once\n return await this.doFetch({ ...opt, [reinitAttempted]: true });\n }\n return res;\n }\n /**\n * Consults cfg.hooks.shouldReinit to detect \"stale init\" (e.g expired auth token).\n * If detected - resets the init (so it re-runs) and returns true,\n * telling the caller to retry the request. At most once per request.\n */\n async detectStaleInit(opt, res, initGeneration) {\n const { shouldReinit, init } = this.cfg.hooks;\n if (!shouldReinit || !init)\n return false;\n if (opt[reinitAttempted])\n return false;\n if (!(await shouldReinit(res)))\n return false;\n // Generation check prevents concurrent stale requests from resetting the already-fresh init\n if (initGeneration === this.initGeneration) {\n this.resetInit();\n }\n return true;\n }\n async runInitHooks() {\n for (const hook of this.cfg.hooks.init || []) {\n await hook(this.cfg);\n }\n }\n async onOkResponse(res) {\n const { req } = res;\n const { responseType } = res.req;\n // This function is subject to a separate timeout to \"download and parse the data\"\n if (responseType === 'json') {\n if (res.fetchResponse.body) {\n const text = await res.fetchResponse.text();\n if (text) {\n res.body = text;\n res.body = _jsonParse(text, req.jsonReviver);\n // Error while parsing json can happen - it'll be handled upstream\n }\n else {\n // Body had a '' (empty string)\n res.body = {};\n }\n }\n else {\n // if no body: set responseBody as {}\n // do not throw a \"cannot parse null as Json\" error\n res.body = {};\n }\n }\n else if (responseType === 'text') {\n res.body = res.fetchResponse.body ? await res.fetchResponse.text() : '';\n }\n else if (responseType === 'arrayBuffer') {\n res.body = res.fetchResponse.body ? await res.fetchResponse.arrayBuffer() : new ArrayBuffer(0);\n }\n else if (responseType === 'bytes') {\n // Not using fetchResponse.bytes(), as it's unavailable in older browsers (e.g Safari <18.4)\n res.body = res.fetchResponse.body\n ? new Uint8Array(await res.fetchResponse.arrayBuffer())\n : new Uint8Array();\n }\n else if (responseType === 'blob') {\n res.body = res.fetchResponse.body ? await res.fetchResponse.blob() : new Blob();\n }\n else if (responseType === 'void') {\n // Cancel the body (without downloading it), to free the underlying connection for reuse\n await res.fetchResponse.body?.cancel();\n }\n else if (responseType === 'readableStream') {\n res.body = res.fetchResponse.body;\n if (res.body === null) {\n // Error is to be handled upstream\n throw new Error('fetchResponse.body is null');\n }\n }\n res.retryStatus.retryStopped = true;\n if (req.logResponse) {\n const { retryAttempt } = res.retryStatus;\n const { logger } = this.cfg;\n logger.log([\n ' <<',\n res.fetchResponse.status,\n res.signature,\n retryAttempt && `try#${retryAttempt + 1}/${req.retry.count + 1}`,\n _since(res.req.started),\n ]\n .filter(Boolean)\n .join(' '));\n if (req.logResponseBody && res.body !== undefined) {\n logger.log({ body: res.body });\n }\n }\n }\n /**\n * This method exists to be able to easily mock it.\n * It is static, so mocking applies to ALL instances (even future ones) of Fetcher at once.\n */\n static async callNativeFetch(url, init, fetchFn) {\n return await (fetchFn || globalThis.fetch)(url, init);\n }\n async onNotOkResponse(res) {\n let cause;\n // Try to fetch body and attach to res.body\n // (but don't fail if it doesn't work)\n if (!res.body && res.fetchResponse) {\n try {\n res.body = _jsonParseIfPossible(await res.fetchResponse.text());\n }\n catch {\n // ignore body fetching/parsing errors at this point\n }\n }\n if (res.err) {\n // This is only possible on JSON.parse error, or CORS error,\n // or `unexpected redirect`\n // This check should go first, to avoid calling .text() twice (which will fail)\n cause = _errorLikeToErrorObject(res.err);\n }\n else if (res.body) {\n cause = _anyToErrorObject(res.body);\n }\n else {\n cause = {\n name: 'Error',\n message: 'Fetch failed',\n data: {},\n };\n }\n let responseStatusCode = res.fetchResponse?.status || 0;\n if (res.statusFamily === 2) {\n // important to reset responseStatusCode to 0 in this case, as status 2xx can be misleading\n res.statusFamily = undefined;\n res.statusCode = undefined;\n responseStatusCode = 0;\n }\n const message = [res.statusCode, res.signature].filter(Boolean).join(' ');\n res.err = new HttpRequestError(message, _filterNullishValues({\n response: res.fetchResponse,\n responseStatusCode,\n // These properties are provided to be used in e.g custom Sentry error grouping\n // Actually, disabled now, to avoid unnecessary error printing when both msg and data are printed\n // Enabled, cause `data` is not printed by default when error is HttpError\n // method: req.method,\n // tryCount: req.tryCount,\n requestUrl: res.req.fullUrl,\n requestBaseUrl: this.cfg.baseUrl || undefined,\n requestMethod: res.req.init.method,\n requestSignature: res.signature,\n requestName: res.req.requestName,\n fetcherName: this.cfg.name,\n requestDuration: Date.now() - res.req.started,\n }), {\n cause,\n });\n await this.processRetry(res);\n }\n async processRetry(res) {\n const { retryStatus } = res;\n if (!this.shouldRetry(res)) {\n retryStatus.retryStopped = true;\n }\n for (const hook of this.cfg.hooks.beforeRetry || []) {\n await hook(res);\n }\n const { count, timeoutMultiplier, timeoutMax } = res.req.retry;\n if (retryStatus.retryAttempt >= count) {\n retryStatus.retryStopped = true;\n }\n // We don't log \"last error\", because it will be thrown and logged by consumer,\n // but we should log all previous errors, otherwise they are lost.\n // Here is the right place where we know it's not the \"last error\".\n // lastError = retryStatus.retryStopped\n // We need to log the response \"anyway\" if logResponse is true\n if (res.err && (!retryStatus.retryStopped || res.req.logResponse)) {\n this.cfg.logger.error({\n msg: [\n ' <<',\n res.fetchResponse?.status || 0,\n res.signature,\n count &&\n (retryStatus.retryAttempt || !retryStatus.retryStopped) &&\n `try#${retryStatus.retryAttempt + 1}/${count + 1}`,\n _since(res.req.started),\n ]\n .filter(Boolean)\n .join(' '),\n err: res.err.cause || res.err,\n });\n }\n if (retryStatus.retryStopped)\n return;\n retryStatus.retryAttempt++;\n const timeout = this.getRetryTimeout(res);\n if (timeout === null) {\n this.cfg.logger.warn(`${res.signature} server-indicated delay exceeds maxRetryAfter, will not retry`);\n retryStatus.retryStopped = true;\n return;\n }\n // Increase the timeout for the next possible retry\n retryStatus.retryTimeout = _clamp(retryStatus.retryTimeout * timeoutMultiplier, 0, timeoutMax);\n if (res.req.debug) {\n this.cfg.logger.log(` .. ${res.signature} waiting ${_ms(timeout)}`);\n }\n await pDelaySignal(timeout, res.req.signal);\n if (res.req.signal?.aborted) {\n // Aborted while waiting for the retry - stop, without issuing another request\n retryStatus.retryStopped = true;\n }\n }\n /**\n * Returns the delay before the next retry attempt.\n * Returns null if the server-indicated delay exceeds `retry.maxRetryAfter`,\n * meaning the retry should not be attempted at all.\n */\n getRetryTimeout(res) {\n let timeout = 0;\n // Handling http 429 with specific retry headers\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After\n if (res.fetchResponse && [429, 503].includes(res.fetchResponse.status)) {\n const retryAfterStr = res.fetchResponse.headers.get('retry-after') ??\n res.fetchResponse.headers.get('x-ratelimit-reset');\n if (retryAfterStr) {\n const retryAfterNumber = Number(retryAfterStr);\n if (retryAfterNumber) {\n if (retryAfterNumber > 10 ** 9) {\n // Value is too large to be a \"seconds from now\" delay,\n // treat it as a UnixTimestamp instead (e.g GitHub sends `x-ratelimit-reset` like that)\n timeout = retryAfterNumber * 1000 - Date.now();\n }\n else {\n timeout = retryAfterNumber * 1000;\n }\n }\n else {\n const date = new Date(retryAfterStr);\n if (!Number.isNaN(date.getTime())) {\n timeout = date.getTime() - Date.now();\n }\n }\n this.cfg.logger.log(`retry-after: ${retryAfterStr}`);\n if (!timeout) {\n this.cfg.logger.warn('retry-after could not be parsed');\n }\n }\n }\n if (timeout) {\n if (timeout > res.req.retry.maxRetryAfter) {\n return null;\n }\n // Server-indicated delay is honored as-is (a negative value means \"retry now\")\n return Math.max(0, timeout);\n }\n const noise = Math.random() * 500;\n return res.retryStatus.retryTimeout + noise;\n }\n /**\n * Default is yes,\n * unless there's reason not to (e.g method is POST).\n *\n * statusCode of 0 (or absense of it) will BE retried.\n */\n shouldRetry(res) {\n // Don't retry if the input AbortSignal was aborted\n if (res.req.signal?.aborted)\n return false;\n const { retryPost, retry3xx, retry4xx, retry5xx } = res.req;\n const { method } = res.req.init;\n if (method === 'POST' && !retryPost)\n return false;\n const { statusFamily } = res;\n const statusCode = res.fetchResponse?.status || 0;\n if (statusFamily === 5 && !retry5xx)\n return false;\n if ([408, 429].includes(statusCode)) {\n // these codes are always retried\n return true;\n }\n if (statusFamily === 4 && !retry4xx)\n return false;\n if (statusFamily === 3 && !retry3xx)\n return false;\n // should not retry on `unexpected redirect` in error.cause.cause\n if (res.err?.cause?.cause?.message?.includes('unexpected redirect')) {\n return false;\n }\n return true; // default is true\n }\n getStatusFamily(res) {\n const status = res.fetchResponse?.status;\n if (!status)\n return;\n if (status >= 500)\n return 5;\n if (status >= 400)\n return 4;\n if (status >= 300)\n return 3;\n if (status >= 200)\n return 2;\n if (status >= 100)\n return 1;\n }\n /**\n * Returns url without baseUrl and before ?queryString\n */\n getShortUrl(url) {\n const { baseUrl } = this.cfg;\n if (url.password) {\n url = new URL(url.toString()); // prevent original url mutation\n url.password = '[redacted]';\n }\n let shortUrl = url.toString();\n if (!this.cfg.logWithSearchParams) {\n shortUrl = shortUrl.split('?')[0];\n }\n if (!this.cfg.logWithBaseUrl && baseUrl && shortUrl.startsWith(baseUrl)) {\n shortUrl = shortUrl.slice(baseUrl.length);\n }\n return shortUrl;\n }\n normalizeCfg(cfg) {\n const { debug = false, logger = consoleLogger } = cfg;\n if (cfg.baseUrl?.endsWith('/')) {\n logger.warn(`Fetcher: baseUrl should not end with slash: ${cfg.baseUrl}`);\n cfg.baseUrl = cfg.baseUrl.slice(0, cfg.baseUrl.length - 1);\n }\n const norm = _merge({\n baseUrl: '',\n name: this.getFetcherName(cfg),\n inputUrl: '',\n responseType: 'json',\n searchParams: {},\n timeoutSeconds: 30,\n retryPost: false,\n retry3xx: false,\n retry4xx: false,\n retry5xx: true,\n logger,\n debug,\n logRequest: debug,\n logRequestBody: debug,\n logResponse: debug,\n logResponseBody: debug,\n logWithBaseUrl: isServerSide(),\n logWithSearchParams: true,\n retry: { ...defaultRetryOptions },\n init: {\n method: cfg.method || 'GET',\n headers: _filterNullishValues({\n 'user-agent': Fetcher.userAgent,\n ...cfg.headers,\n }),\n credentials: cfg.credentials,\n redirect: cfg.redirect,\n dispatcher: cfg.dispatcher,\n keepalive: cfg.keepalive,\n },\n hooks: {},\n throwHttpErrors: true,\n errorData: {},\n }, _omit(cfg, ['method', 'credentials', 'headers', 'redirect', 'logger', 'name', 'keepalive']));\n norm.init.headers = _mapKeys(norm.init.headers, k => k.toLowerCase());\n return norm;\n }\n getFetcherName(cfg) {\n let { name } = cfg;\n if (!name && cfg.baseUrl) {\n // derive FetcherName from baseUrl\n const url = _toUrlOrNull(cfg.baseUrl);\n if (url) {\n name = url.hostname;\n }\n }\n return name;\n }\n normalizeOptions(opt) {\n const req = {\n ..._pick(this.cfg, [\n 'timeoutSeconds',\n 'retryPost',\n 'retry3xx',\n 'retry4xx',\n 'retry5xx',\n 'responseType',\n 'jsonReviver',\n 'logRequest',\n 'logRequestBody',\n 'logResponse',\n 'logResponseBody',\n 'debug',\n 'throwHttpErrors',\n 'errorData',\n 'fetchFn',\n 'overrideFetchFn',\n ]),\n started: Date.now(),\n ..._omit(opt, ['method', 'headers', 'credentials']),\n inputUrl: opt.url || '',\n fullUrl: opt.url || '',\n retry: {\n ...this.cfg.retry,\n ..._filterUndefinedValues(opt.retry || {}),\n },\n init: _merge({\n ...this.cfg.init,\n headers: {\n ...this.cfg.init.headers, // this avoids mutation\n 'user-agent': Fetcher.userAgent, // re-load it here, to support setting it globally post-fetcher-creation\n },\n method: opt.method || this.cfg.init.method,\n credentials: opt.credentials || this.cfg.init.credentials,\n redirect: opt.redirect || this.cfg.init.redirect || 'follow',\n keepalive: opt.keepalive ?? this.cfg.init.keepalive,\n }, {\n headers: _mapKeys(opt.headers || {}, k => k.toLowerCase()),\n }),\n };\n // Because all header values are stringified, so `a: undefined` becomes `undefined` as a string\n _filterNullishValues(req.init.headers, { mutate: true });\n // setup url\n const baseUrl = opt.baseUrl || this.cfg.baseUrl;\n if (baseUrl) {\n let { inputUrl } = req;\n if (inputUrl.startsWith('/')) {\n this.cfg.logger.warn('Fetcher: url should not start with / when baseUrl is specified');\n inputUrl = inputUrl.slice(1);\n }\n req.fullUrl = `${baseUrl}/${inputUrl}`;\n }\n const searchParams = _filterUndefinedValues({\n ...this.cfg.searchParams,\n ...opt.searchParams,\n });\n if (Object.keys(searchParams).length) {\n const qs = new URLSearchParams(searchParams).toString();\n req.fullUrl += (req.fullUrl.includes('?') ? '&' : '?') + qs;\n }\n // setup request body\n // Unless it's a well-defined input type (json, text) - content-type is set automatically by the native fetch\n // Explicitly passed `content-type` header always wins\n if (opt.json !== undefined) {\n req.init.body = JSON.stringify(opt.json);\n req.init.headers['content-type'] ||= 'application/json';\n }\n else if (opt.text !== undefined) {\n req.init.body = opt.text;\n req.init.headers['content-type'] ||= 'text/plain';\n }\n else if (opt.form) {\n if (opt.form instanceof URLSearchParams || opt.form instanceof FormData) {\n req.init.body = opt.form;\n }\n else {\n req.init.body = new URLSearchParams(opt.form);\n req.init.headers['content-type'] ||= 'application/x-www-form-urlencoded';\n }\n }\n else if (opt.body !== undefined) {\n req.init.body = opt.body;\n }\n // Unless `accept` header was already set - set it based on responseType\n req.init.headers['accept'] ||= acceptByResponseType[req.responseType];\n return req;\n }\n}\nexport function getFetcher(cfg = {}) {\n return Fetcher.create(cfg);\n}\n// Marks FetcherOptions of a request that was already retried due to a reinit,\n// to guarantee at most one reinit per request\nconst reinitAttempted = Symbol('reinitAttempted');\nconst acceptByResponseType = {\n text: 'text/plain',\n json: 'application/json',\n void: '*/*',\n readableStream: 'application/octet-stream',\n arrayBuffer: 'application/octet-stream',\n bytes: 'application/octet-stream',\n blob: 'application/octet-stream',\n};\nconst defaultRetryOptions = {\n count: 2,\n timeout: 1000,\n timeoutMax: 30_000,\n timeoutMultiplier: 2,\n maxRetryAfter: 600_000, // 10 minutes\n};\n","import { _substringBefore } from '@naturalcycles/js-lib/string';\n/**\n * Data privacy checklist for quiz-style UX, e.g. onboarding quiz, also applicable to special pages like period calculator.\n * - Does the quiz state or imply sensitive data? If yes, next items?\n * - E.g. Cycle length, medical conditions, contraceptive choice\n * - Do we need marketing pixels on this page?\n * - If it’s not a high-value page, the simplest solution can be to add the page to the exclusion list to disable triggering of pixels altogether. E.g.Most pages in the on-boarding quiz are excluded based on this necessity test.\n * - If it is a high-value page, we need to perform some extra checks to confirm that sensitive data is not being shared\n * - Avoid having title / URL of next page being the answer of the question on the previous page as that is generally shared with pixels\n * - Inspect pixel behavior (e.g. using network tab) to confirm that sensitive data is not sent.\n * - Confirm that clicked button captions (text) is not sent - NC pixels should NOT capture button copy\n */\nexport const domainPathKeywordSuppressionMap = {\n 'https://www.naturalcycles.com/': [\n {\n pathIncludes: 'shop',\n conversionScrubber: pathname => substringThroughOrNull(pathname, '/shop'),\n },\n {\n pathIncludes: 'research-library',\n conversionScrubber: pathname => substringThroughOrNull(pathname, '/research-library'),\n },\n { pathIncludes: 'plan-pregnancy' },\n { pathIncludes: 'postpartum' },\n {\n pathIncludes: 'cyclematters/period-calculator',\n conversionScrubber: pathname => _substringBefore(pathname, '/period-calculator'),\n },\n {\n pathIncludes: 'cyclematters/search',\n conversionScrubber: pathname => substringThroughOrNull(pathname, '/cyclematters/search'),\n },\n {\n pathIncludes: 'cyclematters/perimenopause-quiz',\n conversionScrubber: pathname => _substringBefore(pathname, '/perimenopause-quiz'),\n },\n ],\n 'https://www.naturalcycles.me/': [],\n 'https://signup.naturalcycles.com/': [\n { pathIncludes: 'account' },\n {\n pathIncludes: 'onboarding',\n conversionScrubber: pathname => substringThroughOrNull(pathname, '/onboarding'),\n },\n ],\n 'https://se.naturalcycles.com/': [],\n 'https://br.naturalcycles.com/': [],\n 'https://uk.naturalcycles.com/': [],\n};\n/** `('/en-US/onboarding/goal', '/onboarding')` => `/en-US/onboarding` */\nfunction substringThroughOrNull(s, delimiter) {\n const index = s.indexOf(delimiter);\n if (index === -1)\n return null;\n return s.slice(0, index + delimiter.length);\n}\nexport const debugDomainMap = {\n 'http://localhost:8000': 'https://www.naturalcycles.com/',\n 'http://localhost:8001': 'https://www.naturalcycles.me/',\n 'http://localhost:4200': 'https://signup.naturalcycles.com/',\n};\nexport const allowedDomains = [\n 'https://www.naturalcycles.com/',\n 'https://www.naturalcycles.me/',\n 'https://signup.naturalcycles.com/',\n 'https://se.naturalcycles.com/',\n 'https://br.naturalcycles.com/',\n 'https://uk.naturalcycles.com/',\n];\n","/**\n * Query parameter keys used by WebSignup\n */\nexport var WebSignupQueryParam;\n(function (WebSignupQueryParam) {\n WebSignupQueryParam[\"flow\"] = \"flow\";\n WebSignupQueryParam[\"code\"] = \"code\";\n WebSignupQueryParam[\"refId\"] = \"refId\";\n WebSignupQueryParam[\"referral\"] = \"referral\";\n /**\n * @deprecated Use \"ic\" instead\n */\n WebSignupQueryParam[\"ignoreConfirmation\"] = \"ignoreConfirmation\";\n WebSignupQueryParam[\"ic\"] = \"ic\";\n WebSignupQueryParam[\"measuringDevice\"] = \"measuringDevice\";\n /**\n * Passed by Impact in the URL\n */\n WebSignupQueryParam[\"irclickid\"] = \"irclickid\";\n /**\n * Fertility goal\n */\n WebSignupQueryParam[\"fg\"] = \"fg\";\n /**\n * Skip fertility goal boolean used for the cycle matters fertility goal component AB test\n */\n WebSignupQueryParam[\"sfg\"] = \"sfg\";\n /**\n * Skip entire quiz, go directly to wearable selection.\n */\n WebSignupQueryParam[\"sq\"] = \"sq\";\n /**\n * Clearblue offer\n */\n WebSignupQueryParam[\"cbo\"] = \"cbo\";\n /**\n * The chosen insurance provider option (InsuranceProviderOption enum)\n */\n WebSignupQueryParam[\"ip\"] = \"ip\";\n /**\n * The chosen insurance provider variant\n *\n * For BlueCross BlueShield, this will likely be an item in the list\n * of BCBS variants but can be any inputted string.\n * For other providers, this will likely be an item in the list of other providers,\n * but can also be any inputted string. Just intended for analytics.\n */\n WebSignupQueryParam[\"ipv\"] = \"ipv\";\n /**\n * Added by the apple auth sign in flow\n */\n WebSignupQueryParam[\"appleAuth\"] = \"appleAuth\";\n /**\n * Added by the google auth sign in flow (redirect mode for WebView)\n */\n WebSignupQueryParam[\"googleAuth\"] = \"googleAuth\";\n /**\n * Owns device. Used to determine if the owns the measuring device for flows starting on the plans page.\n * Eg. Email verification on web flow\n */\n WebSignupQueryParam[\"od\"] = \"od\";\n /**\n * Plan\n * The plan which the user has selected.\n * Used in the flow where the user is redirected to WebSignup from the app for payment.\n */\n WebSignupQueryParam[\"pl\"] = \"pl\";\n /**\n * Passed by Snapchat ads in the URL\n */\n WebSignupQueryParam[\"ScCid\"] = \"ScCid\";\n /**\n * Passed by Meta ads in the URL\n */\n WebSignupQueryParam[\"fbclid\"] = \"fbclid\";\n /**\n * Passed by TikTok ads in the URL\n */\n WebSignupQueryParam[\"ttclid\"] = \"ttclid\";\n /**\n * Passed by Reddit ads in the URL\n */\n WebSignupQueryParam[\"rdt_cid\"] = \"rdt_cid\";\n /**\n * Passed by Pinterest ads in the URL\n */\n WebSignupQueryParam[\"epik\"] = \"epik\";\n /**\n * Adjust ID\n * Passed from the app when a user is coming from to the app to the web to pay\n */\n WebSignupQueryParam[\"adid\"] = \"adid\";\n /**\n * Whoop connection failed\n */\n WebSignupQueryParam[\"wcf\"] = \"wcf\";\n /**\n * Whoop eligibility. Value is 'false' when the user is not eligible for the free trial.\n */\n WebSignupQueryParam[\"we\"] = \"we\";\n /**\n * Whoop eligibility rejection reason(s). Only present when `we` is 'false'. Comma-separated\n * `WhoopFreeTrialFailedCriterion` values, e.g. 'NOT_NC_COUNTRY,NOT_COMPATIBLE_DEVICE'.\n */\n WebSignupQueryParam[\"werr\"] = \"werr\";\n /**\n * Whoop device picker modal. Value 'true' signals the destination page\n * to open the WHOOP device picker modal on init.\n */\n WebSignupQueryParam[\"wdpm\"] = \"wdpm\";\n /**\n * Skip Whoop connect flow\n */\n WebSignupQueryParam[\"wsc\"] = \"wsc\";\n /**\n * Redirect after login. Path to navigate to after a successful login.\n * Only paths in loginRedirectAllowedPaths are accepted.\n */\n WebSignupQueryParam[\"ral\"] = \"ral\";\n})(WebSignupQueryParam || (WebSignupQueryParam = {}));\nexport const loginRedirectAllowedPaths = ['account/profile'];\nexport function isLoginRedirectAllowedPath(path) {\n return loginRedirectAllowedPaths.some(allowedPath => allowedPath === path);\n}\n/**\n * Parameters from CAPI platforms and other sources of traffic that identify\n * the click that brought the user here.\n *\n * These should be saved so that we can access these after navigation and\n * pass them to the relevant platform\n */\nexport const clickIdParameters = [\n WebSignupQueryParam.ScCid,\n WebSignupQueryParam.irclickid,\n WebSignupQueryParam.fbclid,\n WebSignupQueryParam.ttclid,\n WebSignupQueryParam.rdt_cid,\n WebSignupQueryParam.epik,\n];\nconst safeToTrackQueryParams = new Set([\n WebSignupQueryParam.flow,\n WebSignupQueryParam.code,\n WebSignupQueryParam.ignoreConfirmation,\n WebSignupQueryParam.ic,\n WebSignupQueryParam.fg,\n WebSignupQueryParam.sfg,\n WebSignupQueryParam.sq,\n WebSignupQueryParam.cbo,\n WebSignupQueryParam.ip,\n WebSignupQueryParam.ipv,\n WebSignupQueryParam.od,\n WebSignupQueryParam.pl,\n WebSignupQueryParam.wcf,\n WebSignupQueryParam.we,\n WebSignupQueryParam.wdpm,\n WebSignupQueryParam.wsc,\n WebSignupQueryParam.ral,\n 'percentage',\n 'asAmount',\n 'includesThermometer',\n 'lead',\n 'lang',\n]);\nfunction isQueryParameterSafeToTrack(key) {\n return safeToTrackQueryParams.has(key) || key.startsWith('utm_');\n}\nconst SCRUBBED_VALUE = '(scrubbed)';\n/**\n * Filters URL query params for forwarding into analytics event properties.\n * Safe-to-track params keep their actual value; everything else has its value\n * replaced with a sentinel string so we know the param was on the URL\n * without leaking its value (click ids, referral codes, unknown params).\n */\nexport function scrubQueryParameters(params) {\n const scrubbed = {};\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined)\n continue;\n if (isQueryParameterSafeToTrack(key)) {\n scrubbed[key] = value;\n }\n else {\n scrubbed[key] = SCRUBBED_VALUE;\n }\n }\n return scrubbed;\n}\nexport var RegistrationFlow;\n(function (RegistrationFlow) {\n RegistrationFlow[RegistrationFlow[\"OURA\"] = 1] = \"OURA\";\n RegistrationFlow[RegistrationFlow[\"APPLE_WATCH\"] = 2] = \"APPLE_WATCH\";\n RegistrationFlow[RegistrationFlow[\"META_LANDING_PAGE\"] = 3] = \"META_LANDING_PAGE\";\n RegistrationFlow[RegistrationFlow[\"PAYMENT_REDIRECT_FROM_APP\"] = 4] = \"PAYMENT_REDIRECT_FROM_APP\";\n RegistrationFlow[RegistrationFlow[\"B1\"] = 5] = \"B1\";\n RegistrationFlow[RegistrationFlow[\"EMAIL_VERIFICATION_REDIRECT\"] = 6] = \"EMAIL_VERIFICATION_REDIRECT\";\n RegistrationFlow[RegistrationFlow[\"WHOOP\"] = 7] = \"WHOOP\";\n})(RegistrationFlow || (RegistrationFlow = {}));\nexport function isRedirectFromAppRegistrationFlow(flow) {\n if (!flow)\n return false;\n return [\n RegistrationFlow.PAYMENT_REDIRECT_FROM_APP,\n RegistrationFlow.EMAIL_VERIFICATION_REDIRECT,\n ].includes(flow);\n}\n","import { allowedDomains, debugDomainMap, domainPathKeywordSuppressionMap, } from '../cnst/privacySettings.js';\nclass ConversionService {\n /**\n * Returns the pathname to report for a page on `origin`, scrubbed, or null when it must not be\n * reported: outside the allowed domains, or on a suppressed path without a conversionScrubber.\n */\n scrubPathname(origin, pathname) {\n const domain = allowedDomains.find(allowedDomain => allowedDomain === `${origin}/`) || debugDomainMap[origin];\n if (!domain)\n return null;\n let scrubbedPathname = pathname;\n for (const rule of domainPathKeywordSuppressionMap[domain]) {\n if (!scrubbedPathname.includes(rule.pathIncludes))\n continue;\n scrubbedPathname = rule.conversionScrubber?.(scrubbedPathname) ?? null;\n if (scrubbedPathname === null)\n return null;\n }\n return scrubbedPathname;\n }\n}\nexport const conversionService = new ConversionService();\n","// oxlint-disable unicorn/no-document-cookie\nclass CookieService {\n getAllCookies() {\n const map = {};\n const cookieStrings = document.cookie.split('; ');\n for (const cookie of cookieStrings) {\n const [name, ...valueParts] = cookie.split('=');\n if (name) {\n // Join back in case value contains '='\n const value = valueParts.join('=');\n const decodedValue = value ? decodeURIComponent(value) : undefined;\n if (decodedValue) {\n map[name] = decodedValue;\n }\n }\n }\n return map;\n }\n getCookie(name) {\n const nameEQ = `${name}=`;\n const cookies = document.cookie.split('; ');\n for (const cookie of cookies) {\n if (cookie.startsWith(nameEQ)) {\n return decodeURIComponent(cookie.slice(nameEQ.length));\n }\n }\n // returns undefined if not found\n }\n setCookie(cname, cvalue, expdays, domain) {\n const d = new Date();\n d.setTime(d.getTime() + expdays * 24 * 60 * 60 * 1000);\n let cookie = `${cname}=${encodeURIComponent(cvalue)};expires=${d.toUTCString()};path=/`;\n if (domain) {\n cookie += `;domain=${domain}`;\n }\n document.cookie = cookie;\n }\n clearAllCookies() {\n const cookies = document.cookie.split('; ');\n for (const cookie of cookies) {\n const [name] = cookie.split('=');\n if (name) {\n document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/`;\n }\n }\n }\n deleteCookie(name) {\n // Set the cookie with an expiration date in the past to delete it\n document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/`;\n }\n}\nexport const cookieService = new CookieService();\n","export function formatMetaClickId(clickId) {\n if (!clickId) {\n return;\n }\n // https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/fbp-and-fbc/\n // fbc = version.subdomainIndex.creationTime.<fbclid>\n if (clickId.startsWith('fb.')) {\n // fbclid is already formatted\n return clickId;\n }\n return `fb.1.${Date.now()}.${clickId}`;\n}\nexport function isFbcValid(fbc) {\n if (!fbc) {\n return false;\n }\n // Facebook _fbc format: fb.{subdomainIndex}.{timestamp}.{fbclid}\n // Example: fb.1.1234567890123.AbC123_dEf-456\n const parts = fbc.split('.');\n // Must have exactly 4 parts\n if (parts.length !== 4) {\n return false;\n }\n const [prefix, subdomainIndex, timestamp, fbclid] = parts;\n // Part 1: Must be 'fb'\n if (prefix !== 'fb') {\n return false;\n }\n // Part 2: Subdomain index must be a number (typically 1 or 2)\n if (!/^\\d+$/.test(subdomainIndex)) {\n return false;\n }\n // Part 3: Timestamp must be a valid 13-digit unix timestamp in milliseconds\n if (!/^\\d{13}$/.test(timestamp)) {\n return false;\n }\n // Validate timestamp is reasonable (after 2000-01-01 and before year 2100)\n const timestampNum = parseInt(timestamp);\n const minTimestamp = 946684800000; // 2000-01-01\n const maxTimestamp = 4102444800000; // 2100-01-01\n if (timestampNum < minTimestamp || timestampNum > maxTimestamp) {\n return false;\n }\n // Part 4: fbclid must exist and contain valid characters\n // Facebook fbclid typically contains alphanumeric, hyphens, and underscores\n if (!fbclid?.length) {\n return false;\n }\n return /^[a-zA-Z0-9_-]+$/.test(fbclid);\n}\n/**\n * Mitigates known Facebook bugs that corrupt the fbclid URL parameter.\n * See: https://nc1.slack.com/archives/C07M5HTABU7/p1770855728868539\n *\n * Pattern A: runaway %25-encoding chain appended after _aem_ suffix\n * Pattern B: double ?fbclid= in URL (Facebook in-app browser re-decoration)\n * Pattern C: prior _fbc value with dots escaped as __DOT__ leaked back into URL\n *\n * todo: remove it after enough time has passed\n */\nexport function sanitizeFbclid(value) {\n if (!value)\n return;\n // Pattern B: strip second ?fbclid= appended with wrong delimiter\n value = value.split('?')[0];\n // Pattern C: decode __DOT__-escaped _fbc value back to dotted format\n if (value.includes('__DOT__')) {\n value = value.replaceAll('__DOT__', '.');\n }\n // Pattern A: strip runaway %-encoding (% is never valid in base64url fbclid)\n value = value.split('%')[0];\n // Pattern E: &\n value = value.split('&')[0];\n // Pattern F: nested fbc - fbclid is itself an fbc value, possibly multiple levels deep\n // fb.1.ts1.fb.1.ts2.fb.1.ts3.clickid → fb.1.ts3.clickid\n const parts = value.split('.');\n const lastFbIdx = parts.lastIndexOf('fb');\n if (lastFbIdx > 0 && parts.length - lastFbIdx >= 4) {\n value = parts.slice(lastFbIdx).join('.');\n }\n return value;\n}\n","import { runInBackground } from '@naturalcycles/js-lib'\nimport { _anyToError } from '@naturalcycles/js-lib/error'\nimport { getFetcher } from '@naturalcycles/js-lib/http'\nimport type { Fetcher } from '@naturalcycles/js-lib/http'\nimport { _filterEmptyValues } from '@naturalcycles/js-lib/object'\nimport { _noop } from '@naturalcycles/js-lib/types'\nimport type { StringMap } from '@naturalcycles/js-lib/types'\nimport type {\n ClientId,\n ConversionHeaders,\n PageViewInput,\n PurchaseInput,\n} from '@naturalcycles/shared'\nimport {\n conversionService,\n clickIdParameters,\n cookieService,\n formatMetaClickId,\n sanitizeFbclid,\n WebSignupQueryParam,\n} from '@naturalcycles/shared'\n\nconst CLICK_ID_COOKIE_DAYS = 30\n// Keeps the click-id cookies well below the browser's per-cookie size limit\nconst MAX_CLICK_ID_LENGTH = 200\n// Shorter values are junk like the literal string `fbclid`, not a real click id\nconst MIN_FBCLID_LENGTH = 20\n\n/**\n * Client for our Conversions API endpoints (`web/p`, `web/purchase`). Captures ad click ids from\n * the URL, stores them in cookies once marketing consent is given and sends them as headers. Nothing\n * is sent without marketing consent. Calls never throw, failures go to `onError`.\n */\nexport class ConversionClient {\n constructor(cfg: ConversionClientCfg) {\n this.cfg = { ...cfg, enabled: cfg.enabled ?? true, onError: cfg.onError ?? _noop }\n this.fetcher = getFetcher({ baseUrl: cfg.url })\n }\n\n private readonly cfg: ConversionClientNormalizedCfg\n private readonly fetcher: Fetcher\n private lastCapturedHref: string | undefined\n // Kept in memory until marketing consent, any browser storage needs consent too (ePrivacy Art. 5(3))\n private pendingClickIds: StringMap = {}\n\n /** Captures ad click ids from the landing URL into memory. Call on page load. */\n init(): void {\n if (!this.cfg.enabled) return\n this.tryOrReport(() => this.captureClickIds(), undefined)\n }\n\n pageView(input: PageViewInput, opt: ConversionRequestOptions = {}): void {\n if (!this.cfg.enabled || !this.hasMarketingConsent(input)) return\n const pathname = conversionService.scrubPathname(globalThis.location.origin, input.pathname)\n if (pathname === null) return\n runInBackground(this.send('p', { ...input, pathname }, opt))\n }\n\n purchase(input: PurchaseInput, opt: ConversionRequestOptions = {}): void {\n if (!this.cfg.enabled || !this.hasMarketingConsent(input)) return\n const pathname = conversionService.scrubPathname(globalThis.location.origin, input.pathname)\n if (pathname === null) return\n runInBackground(this.send('purchase', { ...input, pathname }, opt))\n }\n\n private hasMarketingConsent(input: PageViewInput | PurchaseInput): boolean {\n return (input.marketingConsent ?? input.marketingCookie) === true\n }\n\n private async send(\n path: 'p' | 'purchase',\n json: PageViewInput | PurchaseInput,\n opt: ConversionRequestOptions,\n ): Promise<void> {\n try {\n const res = await this.fetcher.doFetch({\n url: path,\n method: 'POST',\n json,\n headers: {\n ...this.getHeaders({ marketingConsent: json.marketingConsent ?? json.marketingCookie }),\n ...opt.extraHeaders,\n },\n keepalive: true,\n responseType: 'void',\n })\n if (res.err) this.cfg.onError(res.err)\n } catch (err) {\n this.cfg.onError(_anyToError(err))\n }\n }\n\n /** Click ids are only included with marketing consent. */\n getHeaders(input: ConversionHeadersInput): ConversionHeaders {\n const clientId = String(this.cfg.clientId)\n if (!input.marketingConsent) return { clientId }\n return this.tryOrReport<ConversionHeaders>(\n () => {\n if (this.cfg.enabled) this.storeClickIds()\n\n return _filterEmptyValues({\n clientId,\n fbc:\n cookieService.getCookie('_fbc') ||\n formatMetaClickId(cookieService.getCookie(WebSignupQueryParam.fbclid)),\n fbp: cookieService.getCookie('_fbp'),\n scCid: cookieService.getCookie(WebSignupQueryParam.ScCid),\n ttclid: cookieService.getCookie(WebSignupQueryParam.ttclid),\n rdtCid: cookieService.getCookie(WebSignupQueryParam.rdt_cid),\n epik:\n cookieService.getCookie('_epik') || cookieService.getCookie(WebSignupQueryParam.epik),\n uuid_c1: cookieService.getCookie('_scid') || cookieService.getCookie('uuid_c1'),\n })\n },\n { clientId },\n )\n }\n\n private storeClickIds(): void {\n this.captureClickIds()\n for (const [param, value] of Object.entries(this.pendingClickIds)) {\n cookieService.setCookie(param, value!, CLICK_ID_COOKIE_DAYS, this.cfg.cookieDomain)\n }\n this.pendingClickIds = {}\n }\n\n private tryOrReport<T>(fn: () => T, fallback: T): T {\n try {\n return fn()\n } catch (err) {\n this.cfg.onError(_anyToError(err))\n return fallback\n }\n }\n\n private captureClickIds(): void {\n const { href, search } = globalThis.location\n if (href === this.lastCapturedHref) return\n this.lastCapturedHref = href\n\n const searchParams = new URLSearchParams(search)\n for (const param of clickIdParameters) {\n const raw = searchParams.get(param) || searchParams.get(param.toLowerCase())\n if (!raw) continue\n const value =\n param === WebSignupQueryParam.fbclid ? this.toFbc(raw) : raw.slice(0, MAX_CLICK_ID_LENGTH)\n if (value) this.pendingClickIds[param] = value\n }\n }\n\n /** Returns undefined when this click is already captured, so its timestamp is kept. */\n private toFbc(raw: string): string | undefined {\n const fbclid = sanitizeFbclid(raw)\n if (!fbclid || fbclid.length < MIN_FBCLID_LENGTH) return\n const capturedFbc =\n this.pendingClickIds[WebSignupQueryParam.fbclid] ||\n cookieService.getCookie(WebSignupQueryParam.fbclid)\n if (capturedFbc?.endsWith(`.${fbclid}`)) return\n return formatMetaClickId(fbclid)\n }\n}\n\ninterface ConversionClientNormalizedCfg extends ConversionClientCfg {\n enabled: boolean\n onError: (err: Error) => void\n}\n\nexport interface ConversionClientCfg {\n /** Backend base url including `/web`, e.g. `https://api.example.com/web`. */\n url: string\n clientId: ClientId\n /** `Domain` of the click-id cookies, e.g. `.naturalcycles.com`. Host-only when unset. */\n cookieDomain?: string\n /** Pass false to make every call a no-op, e.g. for bots and e2e tests. Defaults to true. */\n enabled?: boolean\n onError?: (err: Error) => void\n}\n\nexport interface ConversionRequestOptions {\n extraHeaders?: StringMap\n}\n\nexport interface ConversionHeadersInput {\n marketingConsent: boolean | undefined\n}\n"],"ignoreList":[0,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21],"mappings":"AAOA,SAAgBA,EAAc,IAAS,IAAI;CACvC,IAAIC,IAAK,IACHC,IAAQ,WAAW,OAAO,gBAAgB,IAAI,WAAWC,CAAM,CAAC;CACtE,OAAO,MAIH,KAAM,mEAAYD,EAAMC,KAAU;CAEtC,OAAOF;AACX;;;ACfA,SAAgBG,IAAoC;CAClD,OAAOJ,EAAc;AACvB;;;ACWA,IAAaK,KAAa,MAAM,CAAC,CAACC;AAOlC,SAAgBC,EAAU,GAAK;CAC3B,OAAQ,OAAOC,KAAQ,cAAYA,KAAgB,CAAC,MAAM,QAAQA,CAAG,KAAM;AAC/E;AA6CA,SAAgBC,EAAS,GAAK;CAC1B,IAAID,KAA6B,MAC7B,OAAO;CACX,IAAI,OAAOA,KAAQ,YAAY,MAAM,QAAQA,CAAG,GAC5C,OAAOA,EAAI,WAAW;CAE1B,IAAIA,aAAe,OAAOA,aAAe,KACrC,OAAOA,EAAI,SAAS;CA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