@orion-js/helpers 4.0.0-next.0 → 4.0.0-next.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/sleep.ts","../src/hashObject.ts","../src/generateId.ts","../src/createMap.ts","../src/createMapArray.ts","../src/Errors/OrionError.ts","../src/Errors/PermissionsError.ts","../src/Errors/UserError.ts","../src/Errors/index.ts","../src/composeMiddlewares.ts","../src/retries.ts","../../../node_modules/uuid/dist/esm-node/rng.js","../../../node_modules/uuid/dist/esm-node/regex.js","../../../node_modules/uuid/dist/esm-node/validate.js","../../../node_modules/uuid/dist/esm-node/stringify.js","../../../node_modules/uuid/dist/esm-node/v4.js","../src/generateUUID.ts","../src/normalize.ts","../src/searchTokens.ts","../src/shortenMongoId.ts"],"sourcesContent":["import sleep from './sleep'\nimport hashObject from './hashObject'\nimport generateId from './generateId'\nimport createMap from './createMap'\nimport createMapArray from './createMapArray'\n\n// Import all error-related exports from the Errors module\nimport {\n OrionError,\n PermissionsError,\n UserError,\n isOrionError,\n isUserError,\n isPermissionsError\n} from './Errors'\nimport type {OrionErrorInformation} from './Errors'\n\nexport * from './composeMiddlewares'\nexport * from './retries'\nexport * from './generateUUID'\nexport * from './normalize'\nexport * from './searchTokens'\nexport * from './shortenMongoId'\nexport {\n // Utility functions\n createMap,\n createMapArray,\n generateId,\n hashObject,\n sleep,\n\n // Error classes\n OrionError,\n PermissionsError,\n UserError,\n\n // Error type guards\n isOrionError,\n isUserError,\n isPermissionsError\n}\n\nexport type {OrionErrorInformation}\n","/**\n * Creates a timeout with a promise\n */\nexport default (time: number): Promise<void> => {\n return new Promise(resolve => setTimeout(resolve, time))\n}\n","import hash from 'object-hash'\n\nexport default function (object: any): string {\n return hash(object)\n}\n","import crypto from 'crypto'\n\nconst UNMISTAKABLE_CHARS = '23456789ABCDEFGHJKLMNPQRSTWXYZabcdefghjkmnopqrstuvwxyz'\n\nconst hexString = function (digits) {\n var numBytes = Math.ceil(digits / 2)\n var bytes\n // Try to get cryptographically strong randomness. Fall back to\n // non-cryptographically strong if not available.\n try {\n bytes = crypto.randomBytes(numBytes)\n } catch (e) {\n // XXX should re-throw any error except insufficient entropy\n bytes = crypto.pseudoRandomBytes(numBytes)\n }\n var result = bytes.toString('hex')\n // If the number of digits is odd, we'll have generated an extra 4 bits\n // of randomness, so we need to trim the last digit.\n return result.substring(0, digits)\n}\n\nconst fraction = function () {\n var numerator = parseInt(hexString(8), 16)\n return numerator * 2.3283064365386963e-10 // 2^-32\n}\n\nconst choice = function (arrayOrString) {\n var index = Math.floor(fraction() * arrayOrString.length)\n if (typeof arrayOrString === 'string') return arrayOrString.substr(index, 1)\n else return arrayOrString[index]\n}\n\nconst randomString = function (charsCount, alphabet) {\n var digits = []\n for (var i = 0; i < charsCount; i++) {\n digits[i] = choice(alphabet)\n }\n return digits.join('')\n}\n\n/**\n * Returns a random ID\n * @param charsCount length of the ID\n * @param chars characters used to generate the ID\n */\nexport default function generateId(\n charsCount?: number,\n chars: string = UNMISTAKABLE_CHARS\n): string {\n if (!charsCount) {\n charsCount = 17\n }\n\n return randomString(charsCount, chars)\n}\n","/**\n * Creates a map (object) from an array of items, using a specified property as the key.\n * \n * This utility transforms an array of objects into a lookup object/dictionary where\n * each item in the array becomes a value in the map, indexed by the specified property.\n * If multiple items have the same key value, only the last one will be preserved.\n * \n * @template T The type of items in the input array\n * @param array - The input array of items to transform into a map\n * @param key - The property name to use as keys in the resulting map (defaults to '_id')\n * @returns A record object where keys are values of the specified property and values are the original items\n * \n * @example\n * // Returns { '1': { id: 1, name: 'Item 1' }, '2': { id: 2, name: 'Item 2' } }\n * createMap([{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }], 'id')\n */\nexport default function createMap<T>(array: Array<T>, key: string = '_id'): Record<string, T> {\n const map = {}\n\n for (const item of array) {\n map[item[key]] = item\n }\n\n return map\n}\n","/**\n * Creates a grouped map from an array of items, using a specified property as the key.\n * \n * This utility transforms an array of objects into a lookup object/dictionary where\n * each value is an array of items sharing the same key value. Unlike createMap,\n * this function preserves all items with the same key by grouping them in arrays.\n * \n * @template T The type of items in the input array\n * @param array - The input array of items to transform into a grouped map\n * @param key - The property name to use as keys in the resulting map (defaults to '_id')\n * @returns A record object where keys are values of the specified property and values are arrays of items\n * \n * @example\n * // Returns { 'category1': [{ id: 1, category: 'category1' }, { id: 3, category: 'category1' }], \n * // 'category2': [{ id: 2, category: 'category2' }] }\n * createMapArray([\n * { id: 1, category: 'category1' }, \n * { id: 2, category: 'category2' }, \n * { id: 3, category: 'category1' }\n * ], 'category')\n */\nexport default function createMapArray<T>(\n array: Array<T>,\n key: string = '_id'\n): Record<string, Array<T>> {\n const map = {}\n\n for (const item of array) {\n map[item[key]] = map[item[key]] || []\n map[item[key]].push(item)\n }\n\n return map\n}\n","/**\n * Interface representing the standardized error information structure for Orion errors.\n * This is used by the getInfo method to provide consistent error reporting.\n */\nexport interface OrionErrorInformation {\n /** The error code or identifier */\n error: string\n /** Human-readable error message */\n message: string\n /** Additional error metadata or context */\n extra: any\n /** The sub-type of error. For example for permissions errors it could be 'read', 'write', 'admin' */\n type?: string\n}\n\n/**\n * Base error class for all Orion-specific errors.\n * \n * This abstract class provides common properties and methods for all error types\n * used in the Orion framework. It's extended by more specific error classes\n * like UserError and PermissionsError.\n * \n * @property isOrionError - Flag indicating this is an Orion error (always true)\n * @property isUserError - Flag indicating if this is a user-facing error\n * @property isPermissionsError - Flag indicating if this is a permissions-related error\n * @property code - Error code for identifying the error type\n * @property extra - Additional error context or metadata\n */\nexport class OrionError extends Error {\n isOrionError = true\n\n isUserError: boolean\n isPermissionsError: boolean\n code: string\n extra: any\n\n /**\n * Returns a standardized representation of the error information.\n * @returns An object containing error details in a consistent format\n */\n getInfo: () => OrionErrorInformation\n}\n","import { OrionError } from './OrionError'\n\n/**\n * Error class for permission-related errors in the Orion framework.\n * \n * PermissionsError represents authorization failures where a user or client \n * attempts to perform an action they don't have permission to execute.\n * This is used to distinguish security/permissions errors from other types\n * of errors for proper error handling and user feedback.\n * \n * @extends OrionError\n */\nexport default class PermissionsError extends OrionError {\n /**\n * Creates a new PermissionsError instance.\n * \n * @param permissionErrorType - Identifies the specific permission that was violated\n * (e.g., 'read', 'write', 'admin')\n * @param extra - Additional error context or metadata. Can include a custom message\n * via the message property.\n * \n * @example\n * // Basic usage\n * throw new PermissionsError('delete_document')\n * \n * @example\n * // With custom message\n * throw new PermissionsError('access_admin', { message: 'Admin access required' })\n * \n * @example\n * // With additional context\n * throw new PermissionsError('edit_user', { \n * userId: 'user123',\n * requiredRole: 'admin'\n * })\n */\n constructor(permissionErrorType, extra: any = {}) {\n // Calling parent constructor of base Error class.\n const message =\n extra.message || `Client is not allowed to perform this action [${permissionErrorType}]`\n\n super(message)\n Error.captureStackTrace(this, this.constructor)\n\n this.isOrionError = true\n this.isPermissionsError = true\n this.code = 'PermissionsError'\n this.extra = extra\n\n this.getInfo = () => {\n return {\n ...extra,\n error: 'PermissionsError',\n message,\n type: permissionErrorType\n }\n }\n }\n}\n","import { OrionError } from './OrionError'\n\n/**\n * Error class for user-facing errors in the Orion framework.\n * \n * UserError is designed to represent errors that should be displayed to end users,\n * as opposed to system errors or unexpected failures. These errors typically represent\n * validation issues, business rule violations, or other expected error conditions.\n * \n * @extends OrionError\n */\nexport default class UserError extends OrionError {\n /**\n * Creates a new UserError instance.\n * \n * @param code - Error code identifier. If only one parameter is provided,\n * this will be used as the message and code will default to 'error'.\n * @param message - Human-readable error message. Optional if code is provided.\n * @param extra - Additional error context or metadata.\n * \n * @example\n * // Basic usage\n * throw new UserError('invalid_input', 'The provided email is invalid')\n * \n * @example\n * // Using only a message (code will be 'error')\n * throw new UserError('Input validation failed')\n * \n * @example\n * // With extra metadata\n * throw new UserError('rate_limit', 'Too many requests', { maxRequests: 100 })\n */\n constructor(code: string, message?: string, extra?: any) {\n if (!message && code) {\n message = code\n code = 'error'\n }\n\n super(message)\n Error.captureStackTrace(this, this.constructor)\n\n this.isOrionError = true\n this.isUserError = true\n this.code = code\n this.extra = extra\n\n this.getInfo = () => {\n return {\n error: code,\n message,\n extra\n }\n }\n }\n}\n","/**\n * @file Exports all error classes used in the Orion framework\n */\n\nimport {OrionError} from './OrionError'\nimport type {OrionErrorInformation} from './OrionError'\nimport PermissionsError from './PermissionsError'\nimport UserError from './UserError'\n\n/**\n * Re-export all error types for convenient importing\n */\nexport {OrionError, PermissionsError, UserError}\nexport type {OrionErrorInformation}\n\n/**\n * Type guard to check if an error is an OrionError\n *\n * @param error - Any error object to test\n * @returns True if the error is an OrionError instance\n *\n * @example\n * try {\n * // some code that might throw\n * } catch (error) {\n * if (isOrionError(error)) {\n * // Handle Orion-specific error\n * console.log(error.code, error.getInfo())\n * } else {\n * // Handle general error\n * }\n * }\n */\nexport function isOrionError(error: any): error is OrionError {\n return Boolean(error && typeof error === 'object' && error.isOrionError === true)\n}\n\n/**\n * Type guard to check if an error is a UserError\n *\n * @param error - Any error object to test\n * @returns True if the error is a UserError instance\n */\nexport function isUserError(error: any): error is UserError {\n return Boolean(\n error && typeof error === 'object' && error.isOrionError === true && error.isUserError === true,\n )\n}\n\n/**\n * Type guard to check if an error is a PermissionsError\n *\n * @param error - Any error object to test\n * @returns True if the error is a PermissionsError instance\n */\nexport function isPermissionsError(error: any): error is PermissionsError {\n return Boolean(\n error &&\n typeof error === 'object' &&\n error.isOrionError === true &&\n error.isPermissionsError === true,\n )\n}\n","// from https://github.com/koajs/compose/blob/master/index.js\n\n/**\n * Compose `middleware` returning\n * a fully valid middleware comprised\n * of all those which are passed.\n */\nexport function composeMiddlewares(middleware) {\n if (!Array.isArray(middleware)) throw new TypeError('Middleware stack must be an array!')\n for (const fn of middleware) {\n if (typeof fn !== 'function') throw new TypeError('Middleware must be composed of functions!')\n }\n\n /**\n * @param {Object} context\n * @return {Promise}\n * @api public\n */\n\n return function (context, next?) {\n // last called middleware #\n let index = -1\n return dispatch(0)\n function dispatch(i) {\n if (i <= index) return Promise.reject(new Error('next() called multiple times'))\n index = i\n let fn = middleware[i]\n if (i === middleware.length) fn = next\n if (!fn) return Promise.resolve()\n try {\n return Promise.resolve(fn(context, dispatch.bind(null, i + 1)))\n } catch (err) {\n return Promise.reject(err)\n }\n }\n }\n}\n","/**\n * Executes an asynchronous function with automatic retries on failure.\n * \n * This utility attempts to execute the provided function and automatically\n * retries if it fails, with a specified delay between attempts. It will\n * continue retrying until either the function succeeds or the maximum\n * number of retries is reached.\n * \n * @template TFunc Type of the function to execute (must return a Promise)\n * @param fn - The asynchronous function to execute\n * @param retries - The maximum number of retry attempts after the initial attempt\n * @param timeout - The delay in milliseconds between retry attempts\n * @returns A promise that resolves with the result of the function or rejects with the last error\n * \n * @example\n * // Retry an API call up to 3 times with 1 second between attempts\n * const result = await executeWithRetries(\n * () => fetchDataFromApi(),\n * 3,\n * 1000\n * );\n */\nexport function executeWithRetries<TFunc extends () => Promise<any>>(\n fn: TFunc,\n retries: number,\n timeout: number\n): Promise<ReturnType<TFunc>> {\n return new Promise((resolve, reject) => {\n const retry = async (retries: number) => {\n try {\n const result = await fn()\n resolve(result)\n } catch (error) {\n if (retries > 0) {\n setTimeout(() => retry(retries - 1), timeout)\n } else {\n reject(error)\n }\n }\n }\n retry(retries)\n })\n}\n","import crypto from 'crypto';\nconst rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate\n\nlet poolPtr = rnds8Pool.length;\nexport default function rng() {\n if (poolPtr > rnds8Pool.length - 16) {\n crypto.randomFillSync(rnds8Pool);\n poolPtr = 0;\n }\n\n return rnds8Pool.slice(poolPtr, poolPtr += 16);\n}","export default /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;","import REGEX from './regex.js';\n\nfunction validate(uuid) {\n return typeof uuid === 'string' && REGEX.test(uuid);\n}\n\nexport default validate;","import validate from './validate.js';\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\n\nconst byteToHex = [];\n\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).substr(1));\n}\n\nfunction stringify(arr, offset = 0) {\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n const uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n\n return uuid;\n}\n\nexport default stringify;","import rng from './rng.js';\nimport stringify from './stringify.js';\n\nfunction v4(options, buf, offset) {\n options = options || {};\n const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided\n\n if (buf) {\n offset = offset || 0;\n\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n\n return buf;\n }\n\n return stringify(rnds);\n}\n\nexport default v4;","import { v4 as uuidv4 } from 'uuid'\n\nexport function generateUUID() {\n return uuidv4()\n}\n\nexport function generateUUIDWithPrefix(prefix: string) {\n return `${prefix}-${generateUUID()}`\n}\n","/**\n * Removes diacritical marks (accents) from text without any other modifications.\n * This is the most basic normalization function that others build upon.\n * \n * @param text - The input string to process\n * @returns String with accents removed but otherwise unchanged\n */\nexport function removeAccentsOnly(text: string) {\n if (!text) return ''\n // biome-ignore lint/suspicious/noMisleadingCharacterClass: Removes diacritical marks (accents)\n return text.normalize('NFD').replace(/[\\u0300-\\u036f]/g, '')\n}\n\n/**\n * Normalizes text by removing diacritical marks (accents) and trimming whitespace.\n * Builds on removeAccentsOnly and adds whitespace trimming.\n * \n * @param text - The input string to normalize\n * @returns Normalized string with accents removed and whitespace trimmed\n */\nexport function removeAccentsAndTrim(text: string) {\n if (!text) return ''\n return removeAccentsOnly(text).trim()\n}\n\n/**\n * Normalizes text for search purposes by:\n * - Removing diacritical marks (accents)\n * - Converting to lowercase\n * - Trimming whitespace\n * \n * Builds on removeAccentsAndTrim and adds lowercase conversion.\n * Useful for case-insensitive and accent-insensitive text searching.\n * \n * @param text - The input string to normalize for search\n * @returns Search-optimized string in lowercase with accents removed\n */\nexport function normalizeForSearch(text: string) {\n if (!text) return ''\n return removeAccentsAndTrim(text).toLowerCase()\n}\n\n/**\n * Normalizes text for search purposes by:\n * - Removing diacritical marks (accents)\n * - Converting to lowercase\n * - Trimming whitespace\n * - Removing all spaces\n * \n * Builds on normalizeForSearch and removes all whitespace.\n * Useful for compact search indexes or when spaces should be ignored in searches.\n * \n * @param text - The input string to normalize for compact search\n * @returns Compact search-optimized string with no spaces\n */\nexport function normalizeForCompactSearch(text: string) {\n if (!text) return ''\n return normalizeForSearch(text).replace(/\\s/g, '')\n}\n\n/**\n * Normalizes text for search token processing by:\n * - Removing diacritical marks (accents)\n * - Converting to lowercase\n * - Trimming whitespace\n * - Replacing all non-alphanumeric characters with spaces\n * \n * Builds on normalizeForSearch and replaces non-alphanumeric characters with spaces.\n * Useful for tokenizing search terms where special characters should be treated as word separators.\n * \n * @param text - The input string to normalize for tokenized search\n * @returns Search token string with only alphanumeric characters and spaces\n */\nexport function normalizeForSearchToken(text: string) {\n if (!text) return ''\n return normalizeForSearch(text).replace(/[^0-9a-z]/gi, ' ')\n}\n\n/**\n * Normalizes a string specifically for use as a file key (e.g., in S3 or other storage systems).\n * Performs the following transformations:\n * - Removes accents/diacritical marks\n * - Replaces special characters with hyphens\n * - Ensures only alphanumeric characters, hyphens, periods, and underscores remain\n * - Replaces multiple consecutive hyphens with a single hyphen\n * - Removes leading/trailing hyphens\n * \n * @param text - The input string to normalize for file key usage\n * @returns A storage-safe string suitable for use as a file key\n */\nexport function normalizeForFileKey(text: string) {\n if (!text) return ''\n return removeAccentsOnly(text)\n // Replace spaces and unwanted characters with hyphens\n .replace(/[^a-zA-Z0-9-._]/g, '-')\n // Replace multiple consecutive hyphens with single hyphen\n .replace(/-+/g, '-')\n // Remove leading/trailing hyphens\n .trim()\n .replace(/^-+|-+$/g, '')\n}\n","import { normalizeForSearchToken } from './normalize'\n\n/**\n * Generates an array of search tokens from input text and optional metadata.\n * \n * This function processes text by:\n * 1. Converting it to an array of strings (if not already)\n * 2. Filtering out falsy values\n * 3. Normalizing each string (removing accents, special characters)\n * 4. Splitting by spaces to create individual tokens\n * 5. Optionally adding metadata tokens in the format \"_key:value\"\n * \n * @param text - String or array of strings to tokenize\n * @param meta - Optional metadata object where each key-value pair becomes a token\n * @returns Array of normalized search tokens\n * \n * @example\n * // Returns ['hello', 'world']\n * getSearchTokens('Hello, World!') \n * \n * @example\n * // Returns ['hello', 'world', '_id:123']\n * getSearchTokens('Hello, World!', { id: '123' })\n */\nexport function getSearchTokens(text: string[] | string, meta?: Record<string, string>) {\n const stringArray = Array.isArray(text) ? text : [text]\n const tokens = stringArray\n .filter(Boolean)\n .map(text => String(text))\n .flatMap(word => {\n return normalizeForSearchToken(word).split(' ').filter(Boolean)\n })\n\n if (meta) {\n for (const key in meta) {\n tokens.push(`_${key}:${meta[key]}`)\n }\n }\n\n return tokens\n}\n\n/**\n * Interface for parameters used in generating search queries from tokens.\n * \n * @property filter - Optional string to filter search results\n * @property [key: string] - Additional key-value pairs for metadata filtering\n */\nexport interface SearchQueryForTokensParams {\n filter?: string\n [key: string]: string\n}\n\n/**\n * Options for customizing the search query generation behavior.\n * Currently empty but provided for future extensibility.\n */\nexport type SearchQueryForTokensOptions = {}\n\n/**\n * Generates a MongoDB-compatible query object based on the provided parameters.\n * \n * This function:\n * 1. Processes any filter text into RegExp tokens for prefix matching\n * 2. Adds metadata filters based on additional properties in the params object\n * 3. Returns a query object with the $all operator for MongoDB queries\n * \n * @param params - Parameters for generating the search query\n * @param _options - Options for customizing search behavior (reserved for future use)\n * @returns A MongoDB-compatible query object with format { $all: [...tokens] }\n * \n * @example\n * // Returns { $all: [/^hello/, /^world/] }\n * getSearchQueryForTokens({ filter: 'Hello World' })\n * \n * @example\n * // Returns { $all: [/^search/, '_category:books'] }\n * getSearchQueryForTokens({ filter: 'search', category: 'books' })\n */\nexport function getSearchQueryForTokens(\n params: SearchQueryForTokensParams = {},\n _options: SearchQueryForTokensOptions = {},\n) {\n const searchTokens: (string | RegExp)[] = []\n\n if (params.filter) {\n const filterTokens = getSearchTokens(params.filter).map(token => new RegExp(`^${token}`))\n searchTokens.push(...filterTokens)\n }\n\n for (const key in params) {\n if (key === 'filter') continue\n if (!params[key]) continue\n searchTokens.push(`_${key}:${params[key]}`)\n }\n\n return { $all: searchTokens }\n}\n","function lastOfString(string: string, last: number) {\n return string.substring(string.length - last, string.length)\n}\n\nexport function shortenMongoId(string: string) {\n return lastOfString(string, 5).toUpperCase()\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACGA,IAAA,gBAAe,wBAACA,SAAAA;AACd,SAAO,IAAIC,QAAQC,CAAAA,YAAWC,WAAWD,SAASF,IAAAA,CAAAA;AACpD,GAFe;;;ACHf,yBAAiB;AAEF,SAAf,mBAAyBI,QAAW;AAClC,aAAOC,mBAAAA,S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,OAAOX,MAAM,EAAEE,IAAIa,CAAAA,UAAS,IAAIC,OAAO,IAAID,KAAAA,EAAO,CAAA;AACvFF,iBAAaJ,KAAI,GAAIK,YAAAA;EACvB;AAEA,aAAWN,OAAOG,QAAQ;AACxB,QAAIH,QAAQ,SAAU;AACtB,QAAI,CAACG,OAAOH,GAAAA,EAAM;AAClBK,iBAAaJ,KAAK,IAAID,GAAAA,IAAOG,OAAOH,GAAAA,CAAI,EAAE;EAC5C;AAEA,SAAO;IAAES,MAAMJ;EAAa;AAC9B;AAlBgBH;;;AC/EhB,SAASQ,aAAaC,QAAgBC,MAAY;AAChD,SAAOD,OAAOE,UAAUF,OAAOG,SAASF,MAAMD,OAAOG,MAAM;AAC7D;AAFSJ;AAIF,SAASK,eAAeJ,QAAc;AAC3C,SAAOD,aAAaC,QAAQ,CAAA,EAAGK,YAAW;AAC5C;AAFgBD;","names":["time","Promise","resolve","setTimeout","object","hash","UNMISTAKABLE_CHARS","hexString","digits","numBytes","Math","ceil","bytes","crypto","randomBytes","e","pseudoRandomBytes","result","toString","substring","fraction","numerator","parseInt","choice","arrayOrString","index","floor","length","substr","randomString","charsCount","alphabet","i","join","chars","generateId","array","key","map","item","createMap","array","key","map","item","push","createMapArray","OrionError","Error","isOrionError","isUserError","isPermissionsError","code","extra","getInfo","PermissionsError","OrionError","constructor","permissionErrorType","extra","message","Error","captureStackTrace","isOrionError","isPermissionsError","code","getInfo","error","type","UserError","OrionError","constructor","code","message","extra","Error","captureStackTrace","isOrionError","isUserError","getInfo","error","isOrionError","error","Boolean","isUserError","isPermissionsError","composeMiddlewares","middleware","Array","isArray","TypeError","fn","context","next","index","dispatch","i","Promise","reject","Error","length","resolve","bind","err","executeWithRetries","fn","retries","timeout","Promise","resolve","reject","retry","result","error","setTimeout","import_crypto","rnds8Pool","Uint8Array","poolPtr","length","rng","crypto","randomFillSync","slice","validate","uuid","REGEX","test","byteToHex","i","push","toString","substr","stringify","arr","offset","uuid","toLowerCase","validate","TypeError","v4","options","buf","offset","rnds","random","rng","i","stringify","generateUUID","uuidv4","generateUUIDWithPrefix","prefix","removeAccentsOnly","text","normalize","replace","removeAccentsAndTrim","trim","normalizeForSearch","toLowerCase","normalizeForCompactSearch","normalizeForSearchToken","normalizeForFileKey","getSearchTokens","text","meta","stringArray","Array","isArray","tokens","filter","Boolean","map","String","flatMap","word","normalizeForSearchToken","split","key","push","getSearchQueryForTokens","params","_options","searchTokens","filterTokens","token","RegExp","$all","lastOfString","string","last","substring","length","shortenMongoId","toUpperCase"]}
@@ -0,0 +1,373 @@
1
+ /**
2
+ * Creates a timeout with a promise
3
+ */
4
+ declare const _default: (time: number) => Promise<void>;
5
+
6
+ declare function export_default(object: any): string;
7
+
8
+ /**
9
+ * Returns a random ID
10
+ * @param charsCount length of the ID
11
+ * @param chars characters used to generate the ID
12
+ */
13
+ declare function generateId(charsCount?: number, chars?: string): string;
14
+
15
+ /**
16
+ * Creates a map (object) from an array of items, using a specified property as the key.
17
+ *
18
+ * This utility transforms an array of objects into a lookup object/dictionary where
19
+ * each item in the array becomes a value in the map, indexed by the specified property.
20
+ * If multiple items have the same key value, only the last one will be preserved.
21
+ *
22
+ * @template T The type of items in the input array
23
+ * @param array - The input array of items to transform into a map
24
+ * @param key - The property name to use as keys in the resulting map (defaults to '_id')
25
+ * @returns A record object where keys are values of the specified property and values are the original items
26
+ *
27
+ * @example
28
+ * // Returns { '1': { id: 1, name: 'Item 1' }, '2': { id: 2, name: 'Item 2' } }
29
+ * createMap([{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }], 'id')
30
+ */
31
+ declare function createMap<T>(array: Array<T>, key?: string): Record<string, T>;
32
+
33
+ /**
34
+ * Creates a grouped map from an array of items, using a specified property as the key.
35
+ *
36
+ * This utility transforms an array of objects into a lookup object/dictionary where
37
+ * each value is an array of items sharing the same key value. Unlike createMap,
38
+ * this function preserves all items with the same key by grouping them in arrays.
39
+ *
40
+ * @template T The type of items in the input array
41
+ * @param array - The input array of items to transform into a grouped map
42
+ * @param key - The property name to use as keys in the resulting map (defaults to '_id')
43
+ * @returns A record object where keys are values of the specified property and values are arrays of items
44
+ *
45
+ * @example
46
+ * // Returns { 'category1': [{ id: 1, category: 'category1' }, { id: 3, category: 'category1' }],
47
+ * // 'category2': [{ id: 2, category: 'category2' }] }
48
+ * createMapArray([
49
+ * { id: 1, category: 'category1' },
50
+ * { id: 2, category: 'category2' },
51
+ * { id: 3, category: 'category1' }
52
+ * ], 'category')
53
+ */
54
+ declare function createMapArray<T>(array: Array<T>, key?: string): Record<string, Array<T>>;
55
+
56
+ /**
57
+ * Interface representing the standardized error information structure for Orion errors.
58
+ * This is used by the getInfo method to provide consistent error reporting.
59
+ */
60
+ interface OrionErrorInformation {
61
+ /** The error code or identifier */
62
+ error: string;
63
+ /** Human-readable error message */
64
+ message: string;
65
+ /** Additional error metadata or context */
66
+ extra: any;
67
+ /** The sub-type of error. For example for permissions errors it could be 'read', 'write', 'admin' */
68
+ type?: string;
69
+ }
70
+ /**
71
+ * Base error class for all Orion-specific errors.
72
+ *
73
+ * This abstract class provides common properties and methods for all error types
74
+ * used in the Orion framework. It's extended by more specific error classes
75
+ * like UserError and PermissionsError.
76
+ *
77
+ * @property isOrionError - Flag indicating this is an Orion error (always true)
78
+ * @property isUserError - Flag indicating if this is a user-facing error
79
+ * @property isPermissionsError - Flag indicating if this is a permissions-related error
80
+ * @property code - Error code for identifying the error type
81
+ * @property extra - Additional error context or metadata
82
+ */
83
+ declare class OrionError extends Error {
84
+ isOrionError: boolean;
85
+ isUserError: boolean;
86
+ isPermissionsError: boolean;
87
+ code: string;
88
+ extra: any;
89
+ /**
90
+ * Returns a standardized representation of the error information.
91
+ * @returns An object containing error details in a consistent format
92
+ */
93
+ getInfo: () => OrionErrorInformation;
94
+ }
95
+
96
+ /**
97
+ * Error class for permission-related errors in the Orion framework.
98
+ *
99
+ * PermissionsError represents authorization failures where a user or client
100
+ * attempts to perform an action they don't have permission to execute.
101
+ * This is used to distinguish security/permissions errors from other types
102
+ * of errors for proper error handling and user feedback.
103
+ *
104
+ * @extends OrionError
105
+ */
106
+ declare class PermissionsError extends OrionError {
107
+ /**
108
+ * Creates a new PermissionsError instance.
109
+ *
110
+ * @param permissionErrorType - Identifies the specific permission that was violated
111
+ * (e.g., 'read', 'write', 'admin')
112
+ * @param extra - Additional error context or metadata. Can include a custom message
113
+ * via the message property.
114
+ *
115
+ * @example
116
+ * // Basic usage
117
+ * throw new PermissionsError('delete_document')
118
+ *
119
+ * @example
120
+ * // With custom message
121
+ * throw new PermissionsError('access_admin', { message: 'Admin access required' })
122
+ *
123
+ * @example
124
+ * // With additional context
125
+ * throw new PermissionsError('edit_user', {
126
+ * userId: 'user123',
127
+ * requiredRole: 'admin'
128
+ * })
129
+ */
130
+ constructor(permissionErrorType: any, extra?: any);
131
+ }
132
+
133
+ /**
134
+ * Error class for user-facing errors in the Orion framework.
135
+ *
136
+ * UserError is designed to represent errors that should be displayed to end users,
137
+ * as opposed to system errors or unexpected failures. These errors typically represent
138
+ * validation issues, business rule violations, or other expected error conditions.
139
+ *
140
+ * @extends OrionError
141
+ */
142
+ declare class UserError extends OrionError {
143
+ /**
144
+ * Creates a new UserError instance.
145
+ *
146
+ * @param code - Error code identifier. If only one parameter is provided,
147
+ * this will be used as the message and code will default to 'error'.
148
+ * @param message - Human-readable error message. Optional if code is provided.
149
+ * @param extra - Additional error context or metadata.
150
+ *
151
+ * @example
152
+ * // Basic usage
153
+ * throw new UserError('invalid_input', 'The provided email is invalid')
154
+ *
155
+ * @example
156
+ * // Using only a message (code will be 'error')
157
+ * throw new UserError('Input validation failed')
158
+ *
159
+ * @example
160
+ * // With extra metadata
161
+ * throw new UserError('rate_limit', 'Too many requests', { maxRequests: 100 })
162
+ */
163
+ constructor(code: string, message?: string, extra?: any);
164
+ }
165
+
166
+ /**
167
+ * @file Exports all error classes used in the Orion framework
168
+ */
169
+
170
+ /**
171
+ * Type guard to check if an error is an OrionError
172
+ *
173
+ * @param error - Any error object to test
174
+ * @returns True if the error is an OrionError instance
175
+ *
176
+ * @example
177
+ * try {
178
+ * // some code that might throw
179
+ * } catch (error) {
180
+ * if (isOrionError(error)) {
181
+ * // Handle Orion-specific error
182
+ * console.log(error.code, error.getInfo())
183
+ * } else {
184
+ * // Handle general error
185
+ * }
186
+ * }
187
+ */
188
+ declare function isOrionError(error: any): error is OrionError;
189
+ /**
190
+ * Type guard to check if an error is a UserError
191
+ *
192
+ * @param error - Any error object to test
193
+ * @returns True if the error is a UserError instance
194
+ */
195
+ declare function isUserError(error: any): error is UserError;
196
+ /**
197
+ * Type guard to check if an error is a PermissionsError
198
+ *
199
+ * @param error - Any error object to test
200
+ * @returns True if the error is a PermissionsError instance
201
+ */
202
+ declare function isPermissionsError(error: any): error is PermissionsError;
203
+
204
+ /**
205
+ * Compose `middleware` returning
206
+ * a fully valid middleware comprised
207
+ * of all those which are passed.
208
+ */
209
+ declare function composeMiddlewares(middleware: any): (context: any, next?: any) => Promise<any>;
210
+
211
+ /**
212
+ * Executes an asynchronous function with automatic retries on failure.
213
+ *
214
+ * This utility attempts to execute the provided function and automatically
215
+ * retries if it fails, with a specified delay between attempts. It will
216
+ * continue retrying until either the function succeeds or the maximum
217
+ * number of retries is reached.
218
+ *
219
+ * @template TFunc Type of the function to execute (must return a Promise)
220
+ * @param fn - The asynchronous function to execute
221
+ * @param retries - The maximum number of retry attempts after the initial attempt
222
+ * @param timeout - The delay in milliseconds between retry attempts
223
+ * @returns A promise that resolves with the result of the function or rejects with the last error
224
+ *
225
+ * @example
226
+ * // Retry an API call up to 3 times with 1 second between attempts
227
+ * const result = await executeWithRetries(
228
+ * () => fetchDataFromApi(),
229
+ * 3,
230
+ * 1000
231
+ * );
232
+ */
233
+ declare function executeWithRetries<TFunc extends () => Promise<any>>(fn: TFunc, retries: number, timeout: number): Promise<ReturnType<TFunc>>;
234
+
235
+ declare function generateUUID(): any;
236
+ declare function generateUUIDWithPrefix(prefix: string): string;
237
+
238
+ /**
239
+ * Removes diacritical marks (accents) from text without any other modifications.
240
+ * This is the most basic normalization function that others build upon.
241
+ *
242
+ * @param text - The input string to process
243
+ * @returns String with accents removed but otherwise unchanged
244
+ */
245
+ declare function removeAccentsOnly(text: string): string;
246
+ /**
247
+ * Normalizes text by removing diacritical marks (accents) and trimming whitespace.
248
+ * Builds on removeAccentsOnly and adds whitespace trimming.
249
+ *
250
+ * @param text - The input string to normalize
251
+ * @returns Normalized string with accents removed and whitespace trimmed
252
+ */
253
+ declare function removeAccentsAndTrim(text: string): string;
254
+ /**
255
+ * Normalizes text for search purposes by:
256
+ * - Removing diacritical marks (accents)
257
+ * - Converting to lowercase
258
+ * - Trimming whitespace
259
+ *
260
+ * Builds on removeAccentsAndTrim and adds lowercase conversion.
261
+ * Useful for case-insensitive and accent-insensitive text searching.
262
+ *
263
+ * @param text - The input string to normalize for search
264
+ * @returns Search-optimized string in lowercase with accents removed
265
+ */
266
+ declare function normalizeForSearch(text: string): string;
267
+ /**
268
+ * Normalizes text for search purposes by:
269
+ * - Removing diacritical marks (accents)
270
+ * - Converting to lowercase
271
+ * - Trimming whitespace
272
+ * - Removing all spaces
273
+ *
274
+ * Builds on normalizeForSearch and removes all whitespace.
275
+ * Useful for compact search indexes or when spaces should be ignored in searches.
276
+ *
277
+ * @param text - The input string to normalize for compact search
278
+ * @returns Compact search-optimized string with no spaces
279
+ */
280
+ declare function normalizeForCompactSearch(text: string): string;
281
+ /**
282
+ * Normalizes text for search token processing by:
283
+ * - Removing diacritical marks (accents)
284
+ * - Converting to lowercase
285
+ * - Trimming whitespace
286
+ * - Replacing all non-alphanumeric characters with spaces
287
+ *
288
+ * Builds on normalizeForSearch and replaces non-alphanumeric characters with spaces.
289
+ * Useful for tokenizing search terms where special characters should be treated as word separators.
290
+ *
291
+ * @param text - The input string to normalize for tokenized search
292
+ * @returns Search token string with only alphanumeric characters and spaces
293
+ */
294
+ declare function normalizeForSearchToken(text: string): string;
295
+ /**
296
+ * Normalizes a string specifically for use as a file key (e.g., in S3 or other storage systems).
297
+ * Performs the following transformations:
298
+ * - Removes accents/diacritical marks
299
+ * - Replaces special characters with hyphens
300
+ * - Ensures only alphanumeric characters, hyphens, periods, and underscores remain
301
+ * - Replaces multiple consecutive hyphens with a single hyphen
302
+ * - Removes leading/trailing hyphens
303
+ *
304
+ * @param text - The input string to normalize for file key usage
305
+ * @returns A storage-safe string suitable for use as a file key
306
+ */
307
+ declare function normalizeForFileKey(text: string): string;
308
+
309
+ /**
310
+ * Generates an array of search tokens from input text and optional metadata.
311
+ *
312
+ * This function processes text by:
313
+ * 1. Converting it to an array of strings (if not already)
314
+ * 2. Filtering out falsy values
315
+ * 3. Normalizing each string (removing accents, special characters)
316
+ * 4. Splitting by spaces to create individual tokens
317
+ * 5. Optionally adding metadata tokens in the format "_key:value"
318
+ *
319
+ * @param text - String or array of strings to tokenize
320
+ * @param meta - Optional metadata object where each key-value pair becomes a token
321
+ * @returns Array of normalized search tokens
322
+ *
323
+ * @example
324
+ * // Returns ['hello', 'world']
325
+ * getSearchTokens('Hello, World!')
326
+ *
327
+ * @example
328
+ * // Returns ['hello', 'world', '_id:123']
329
+ * getSearchTokens('Hello, World!', { id: '123' })
330
+ */
331
+ declare function getSearchTokens(text: string[] | string, meta?: Record<string, string>): string[];
332
+ /**
333
+ * Interface for parameters used in generating search queries from tokens.
334
+ *
335
+ * @property filter - Optional string to filter search results
336
+ * @property [key: string] - Additional key-value pairs for metadata filtering
337
+ */
338
+ interface SearchQueryForTokensParams {
339
+ filter?: string;
340
+ [key: string]: string;
341
+ }
342
+ /**
343
+ * Options for customizing the search query generation behavior.
344
+ * Currently empty but provided for future extensibility.
345
+ */
346
+ type SearchQueryForTokensOptions = {};
347
+ /**
348
+ * Generates a MongoDB-compatible query object based on the provided parameters.
349
+ *
350
+ * This function:
351
+ * 1. Processes any filter text into RegExp tokens for prefix matching
352
+ * 2. Adds metadata filters based on additional properties in the params object
353
+ * 3. Returns a query object with the $all operator for MongoDB queries
354
+ *
355
+ * @param params - Parameters for generating the search query
356
+ * @param _options - Options for customizing search behavior (reserved for future use)
357
+ * @returns A MongoDB-compatible query object with format { $all: [...tokens] }
358
+ *
359
+ * @example
360
+ * // Returns { $all: [/^hello/, /^world/] }
361
+ * getSearchQueryForTokens({ filter: 'Hello World' })
362
+ *
363
+ * @example
364
+ * // Returns { $all: [/^search/, '_category:books'] }
365
+ * getSearchQueryForTokens({ filter: 'search', category: 'books' })
366
+ */
367
+ declare function getSearchQueryForTokens(params?: SearchQueryForTokensParams, _options?: SearchQueryForTokensOptions): {
368
+ $all: (string | RegExp)[];
369
+ };
370
+
371
+ declare function shortenMongoId(string: string): string;
372
+
373
+ export { OrionError, type OrionErrorInformation, PermissionsError, type SearchQueryForTokensOptions, type SearchQueryForTokensParams, UserError, composeMiddlewares, createMap, createMapArray, executeWithRetries, generateId, generateUUID, generateUUIDWithPrefix, getSearchQueryForTokens, getSearchTokens, export_default as hashObject, isOrionError, isPermissionsError, isUserError, normalizeForCompactSearch, normalizeForFileKey, normalizeForSearch, normalizeForSearchToken, removeAccentsAndTrim, removeAccentsOnly, shortenMongoId, _default as sleep };