@orion-js/services 4.0.2 → 4.0.3
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.
- package/dist/index.cjs.map +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +5 -2
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../../helpers/src/sleep.ts","../../helpers/src/hashObject.ts","../../helpers/src/generateId.ts","../../helpers/src/createMap.ts","../../helpers/src/createMapArray.ts","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/type.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/_internals/isArray.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/isType.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/clone.js","../../helpers/src/clone.ts","../../helpers/src/Errors/OrionError.ts","../../helpers/src/Errors/PermissionsError.ts","../../helpers/src/Errors/UserError.ts","../../helpers/src/Errors/index.ts","../../helpers/src/composeMiddlewares.ts","../../helpers/src/retries.ts","../../helpers/src/generateUUID.ts","../../helpers/src/normalize.ts","../../helpers/src/searchTokens.ts","../../helpers/src/shortenMongoId.ts","../src/di.ts"],"sourcesContent":["export * from './di'\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 crypto from 'node:crypto'\n\n/**\n * Receives any javascript object, string, number, boolean, array, or object and returns a hash of it.\n */\nexport default function hashObject(object: any): string {\n const string = objectToString(object)\n return crypto.createHash('sha256').update(string).digest('hex')\n}\n\nfunction objectToString(object: any): string {\n if (object === null || object === undefined) {\n return 'null'\n }\n\n if (typeof object === 'string') {\n return object\n }\n\n if (typeof object === 'number' || typeof object === 'boolean') {\n return String(object)\n }\n\n if (object instanceof Date) {\n return object.toISOString()\n }\n\n if (Array.isArray(object)) {\n const arrayHash = object.map(item => hashObject(item)).join(',')\n return `[${arrayHash}]`\n }\n\n if (typeof object === 'object') {\n const keys = Object.keys(object).sort()\n const objectHash = keys.map(key => `${key}:${hashObject(object[key])}`).join(',')\n return `{${objectHash}}`\n }\n\n // Fallback for functions or other types\n return String(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","export function type(input){\n if (input === null){\n return 'Null'\n } else if (input === undefined){\n return 'Undefined'\n } else if (Number.isNaN(input)){\n return 'NaN'\n }\n const typeResult = Object.prototype.toString.call(input).slice(8, -1)\n\n return typeResult === 'AsyncFunction' ? 'Promise' : typeResult\n}\n","export const { isArray } = Array\n","import { type } from './type.js'\n\nexport function isType(xType, x){\n if (arguments.length === 1){\n return xHolder => isType(xType, xHolder)\n }\n\n return type(x) === xType\n}\n","import { isArray } from './_internals/isArray.js'\n\nexport function clone(input){\n const out = isArray(input) ? Array(input.length) : {}\n if (input && input.getTime) return new Date(input.getTime())\n\n for (const key in input){\n const v = input[ key ]\n out[ key ] =\n typeof v === 'object' && v !== null ?\n v.getTime ?\n new Date(v.getTime()) :\n clone(v) :\n v\n }\n\n return out\n}\n","import {isType, clone as cloneRambdax} from 'rambdax'\n\nexport function clone<T>(value: T): T {\n if (isType('Object', value)) {\n return cloneRambdax(value)\n }\n\n if (Array.isArray(value)) {\n return cloneRambdax(value)\n }\n\n return value\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 {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 (\n 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}\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","import {generateId} from '../../helpers/dist'\n\ntype Token<T> = {new (...args: any[]): T}\n\nconst instances = new Map<Token<any>, any>()\nconst serviceMetadata = new WeakMap<object, {id: string; name: string}>()\nconst injectionMetadata = new WeakMap<object, Record<string | symbol, () => Token<any>>>()\n\nexport function Service() {\n return (_target: Function, context: ClassDecoratorContext) => {\n serviceMetadata.set(context, {\n id: generateId(12),\n name: context.name,\n })\n }\n}\n\nexport function Inject<T>(getDependency: () => Token<T>) {\n return (_: undefined, context: ClassFieldDecoratorContext) => {\n const propertyKey = String(context.name)\n if (!getDependency) {\n throw new Error(\n `Since v4, Inject() requires a function that returns the dependency token. Check the @Inject() of ${propertyKey}`,\n )\n }\n context.addInitializer(function (this: any) {\n const metadata = injectionMetadata.get(this) || {}\n metadata[context.name] = getDependency\n injectionMetadata.set(this, metadata)\n })\n }\n}\n\nexport function setInstance<T extends object>(token: Token<T>, instance: T) {\n instances.set(token, instance)\n}\n\nexport function getInstance<T extends object>(token: Token<T>): T {\n if (!instances.has(token)) {\n const instance = new token()\n instances.set(token, instance)\n\n const injections = injectionMetadata.get(instance)\n if (injections) {\n for (const [propertyKey, getDependency] of Object.entries(injections)) {\n instance[propertyKey] = getInstance(getDependency())\n }\n }\n }\n return instances.get(token)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AGAA,oBAAmB;AAEnB,IAAM,qBAAqB;AAE3B,IAAM,YAAY,SAAU,QAAQ;AAClC,MAAI,WAAW,KAAK,KAAK,SAAS,CAAC;AACnC,MAAI;AAGJ,MAAI;AACF,YAAQA,cAAAA,QAAO,YAAY,QAAQ;EACrC,SAAS,GAAG;AAEV,YAAQA,cAAAA,QAAO,kBAAkB,QAAQ;EAC3C;AACA,MAAI,SAAS,MAAM,SAAS,KAAK;AAGjC,SAAO,OAAO,UAAU,GAAG,MAAM;AACnC;AAEA,IAAM,WAAW,WAAY;AAC3B,MAAI,YAAY,SAAS,UAAU,CAAC,GAAG,EAAE;AACzC,SAAO,YAAY;AACrB;AAEA,IAAM,SAAS,SAAU,eAAe;AACtC,MAAI,QAAQ,KAAK,MAAM,SAAS,IAAI,cAAc,MAAM;AACxD,MAAI,OAAO,kBAAkB,SAAU,QAAO,cAAc,OAAO,OAAO,CAAC;MACtE,QAAO,cAAc,KAAK;AACjC;AAEA,IAAM,eAAe,SAAU,YAAY,UAAU;AACnD,MAAI,SAAS,CAAC;AACd,WAAS,IAAI,GAAG,IAAI,YAAY,KAAK;AACnC,WAAO,CAAC,IAAI,OAAO,QAAQ;EAC7B;AACA,SAAO,OAAO,KAAK,EAAE;AACvB;AAOe,SAAR,WACL,YACA,QAAgB,oBACR;AACR,MAAI,CAAC,YAAY;AACf,iBAAa;EACf;AAEA,SAAO,aAAa,YAAY,KAAK;AACvC;AItDO,IAAM,EAAE,QAAQ,IAAI;;;AcI3B,IAAM,YAAY,oBAAI,IAAqB;AAC3C,IAAM,kBAAkB,oBAAI,QAA4C;AACxE,IAAM,oBAAoB,oBAAI,QAA2D;AAElF,SAAS,UAAU;AACxB,SAAO,CAAC,SAAmB,YAAmC;AAC5D,oBAAgB,IAAI,SAAS;AAAA,MAC3B,IAAI,WAAW,EAAE;AAAA,MACjB,MAAM,QAAQ;AAAA,IAChB,CAAC;AAAA,EACH;AACF;AAEO,SAAS,OAAU,eAA+B;AACvD,SAAO,CAAC,GAAc,YAAwC;AAC5D,UAAM,cAAc,OAAO,QAAQ,IAAI;AACvC,QAAI,CAAC,eAAe;AAClB,YAAM,IAAI;AAAA,QACR,oGAAoG,WAAW;AAAA,MACjH;AAAA,IACF;AACA,YAAQ,eAAe,WAAqB;AAC1C,YAAM,WAAW,kBAAkB,IAAI,IAAI,KAAK,CAAC;AACjD,eAAS,QAAQ,IAAI,IAAI;AACzB,wBAAkB,IAAI,MAAM,QAAQ;AAAA,IACtC,CAAC;AAAA,EACH;AACF;AAEO,SAAS,YAA8B,OAAiB,UAAa;AAC1E,YAAU,IAAI,OAAO,QAAQ;AAC/B;AAEO,SAAS,YAA8B,OAAoB;AAChE,MAAI,CAAC,UAAU,IAAI,KAAK,GAAG;AACzB,UAAM,WAAW,IAAI,MAAM;AAC3B,cAAU,IAAI,OAAO,QAAQ;AAE7B,UAAM,aAAa,kBAAkB,IAAI,QAAQ;AACjD,QAAI,YAAY;AACd,iBAAW,CAAC,aAAa,aAAa,KAAK,OAAO,QAAQ,UAAU,GAAG;AACrE,iBAAS,WAAW,IAAI,YAAY,cAAc,CAAC;AAAA,MACrD;AAAA,IACF;AAAA,EACF;AACA,SAAO,UAAU,IAAI,KAAK;AAC5B;","names":["crypto"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../../helpers/src/sleep.ts","../../helpers/src/hashObject.ts","../../helpers/src/generateId.ts","../../helpers/src/createMap.ts","../../helpers/src/createMapArray.ts","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/type.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/_internals/isArray.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/isType.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/clone.js","../../helpers/src/clone.ts","../../helpers/src/Errors/OrionError.ts","../../helpers/src/Errors/PermissionsError.ts","../../helpers/src/Errors/UserError.ts","../../helpers/src/Errors/index.ts","../../helpers/src/composeMiddlewares.ts","../../helpers/src/retries.ts","../../helpers/src/generateUUID.ts","../../helpers/src/normalize.ts","../../helpers/src/searchTokens.ts","../../helpers/src/shortenMongoId.ts","../src/di.ts"],"sourcesContent":["export * from './di'\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 crypto from 'node:crypto'\n\n/**\n * Receives any javascript object, string, number, boolean, array, or object and returns a hash of it.\n */\nexport default function hashObject(object: any): string {\n const string = objectToString(object)\n return crypto.createHash('sha256').update(string).digest('hex')\n}\n\nfunction objectToString(object: any): string {\n if (object === null || object === undefined) {\n return 'null'\n }\n\n if (typeof object === 'string') {\n return object\n }\n\n if (typeof object === 'number' || typeof object === 'boolean') {\n return String(object)\n }\n\n if (object instanceof Date) {\n return object.toISOString()\n }\n\n if (Array.isArray(object)) {\n const arrayHash = object.map(item => hashObject(item)).join(',')\n return `[${arrayHash}]`\n }\n\n if (typeof object === 'object') {\n const keys = Object.keys(object).sort()\n const objectHash = keys.map(key => `${key}:${hashObject(object[key])}`).join(',')\n return `{${objectHash}}`\n }\n\n // Fallback for functions or other types\n return String(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","export function type(input){\n if (input === null){\n return 'Null'\n } else if (input === undefined){\n return 'Undefined'\n } else if (Number.isNaN(input)){\n return 'NaN'\n }\n const typeResult = Object.prototype.toString.call(input).slice(8, -1)\n\n return typeResult === 'AsyncFunction' ? 'Promise' : typeResult\n}\n","export const { isArray } = Array\n","import { type } from './type.js'\n\nexport function isType(xType, x){\n if (arguments.length === 1){\n return xHolder => isType(xType, xHolder)\n }\n\n return type(x) === xType\n}\n","import { isArray } from './_internals/isArray.js'\n\nexport function clone(input){\n const out = isArray(input) ? Array(input.length) : {}\n if (input && input.getTime) return new Date(input.getTime())\n\n for (const key in input){\n const v = input[ key ]\n out[ key ] =\n typeof v === 'object' && v !== null ?\n v.getTime ?\n new Date(v.getTime()) :\n clone(v) :\n v\n }\n\n return out\n}\n","import {isType, clone as cloneRambdax} from 'rambdax'\n\nexport function clone<T>(value: T): T {\n if (isType('Object', value)) {\n return cloneRambdax(value)\n }\n\n if (Array.isArray(value)) {\n return cloneRambdax(value)\n }\n\n return value\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 {v7 as uuidv7} from 'uuid'\n\nexport function generateUUID() {\n return uuidv7()\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 (\n 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}\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","import {generateId} from '../../helpers/dist'\n\ntype Token<T> = {new (...args: any[]): T}\n\nconst instances = new Map<Token<any>, any>()\nconst serviceMetadata = new WeakMap<object, {id: string; name: string}>()\nconst injectionMetadata = new WeakMap<object, Record<string | symbol, () => Token<any>>>()\n\nexport function Service() {\n return (_target: Function, context: ClassDecoratorContext) => {\n serviceMetadata.set(context, {\n id: generateId(12),\n name: context.name,\n })\n }\n}\n\nexport function Inject<T>(getDependency: () => Token<T>) {\n return (_: undefined, context: ClassFieldDecoratorContext) => {\n const propertyKey = String(context.name)\n if (!getDependency) {\n throw new Error(\n `Since v4, Inject() requires a function that returns the dependency token. Check the @Inject() of ${propertyKey}`,\n )\n }\n context.addInitializer(function (this: any) {\n const metadata = injectionMetadata.get(this) || {}\n metadata[context.name] = getDependency\n injectionMetadata.set(this, metadata)\n })\n }\n}\n\nexport function setInstance<T extends object>(token: Token<T>, instance: T) {\n instances.set(token, instance)\n}\n\nexport function getInstance<T extends object>(token: Token<T>): T {\n if (!instances.has(token)) {\n const instance = new token()\n instances.set(token, instance)\n\n const injections = injectionMetadata.get(instance)\n if (injections) {\n for (const [propertyKey, getDependency] of Object.entries(injections)) {\n instance[propertyKey] = getInstance(getDependency())\n }\n }\n }\n return instances.get(token)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AGAA,oBAAmB;AAEnB,IAAM,qBAAqB;AAE3B,IAAM,YAAY,SAAU,QAAQ;AAClC,MAAI,WAAW,KAAK,KAAK,SAAS,CAAC;AACnC,MAAI;AAGJ,MAAI;AACF,YAAQA,cAAAA,QAAO,YAAY,QAAQ;EACrC,SAAS,GAAG;AAEV,YAAQA,cAAAA,QAAO,kBAAkB,QAAQ;EAC3C;AACA,MAAI,SAAS,MAAM,SAAS,KAAK;AAGjC,SAAO,OAAO,UAAU,GAAG,MAAM;AACnC;AAEA,IAAM,WAAW,WAAY;AAC3B,MAAI,YAAY,SAAS,UAAU,CAAC,GAAG,EAAE;AACzC,SAAO,YAAY;AACrB;AAEA,IAAM,SAAS,SAAU,eAAe;AACtC,MAAI,QAAQ,KAAK,MAAM,SAAS,IAAI,cAAc,MAAM;AACxD,MAAI,OAAO,kBAAkB,SAAU,QAAO,cAAc,OAAO,OAAO,CAAC;MACtE,QAAO,cAAc,KAAK;AACjC;AAEA,IAAM,eAAe,SAAU,YAAY,UAAU;AACnD,MAAI,SAAS,CAAC;AACd,WAAS,IAAI,GAAG,IAAI,YAAY,KAAK;AACnC,WAAO,CAAC,IAAI,OAAO,QAAQ;EAC7B;AACA,SAAO,OAAO,KAAK,EAAE;AACvB;AAOe,SAAR,WACL,YACA,QAAgB,oBACR;AACR,MAAI,CAAC,YAAY;AACf,iBAAa;EACf;AAEA,SAAO,aAAa,YAAY,KAAK;AACvC;AItDO,IAAM,EAAE,QAAQ,IAAI;;;AcI3B,IAAM,YAAY,oBAAI,IAAqB;AAC3C,IAAM,kBAAkB,oBAAI,QAA4C;AACxE,IAAM,oBAAoB,oBAAI,QAA2D;AAElF,SAAS,UAAU;AACxB,SAAO,CAAC,SAAmB,YAAmC;AAC5D,oBAAgB,IAAI,SAAS;AAAA,MAC3B,IAAI,WAAW,EAAE;AAAA,MACjB,MAAM,QAAQ;AAAA,IAChB,CAAC;AAAA,EACH;AACF;AAEO,SAAS,OAAU,eAA+B;AACvD,SAAO,CAAC,GAAc,YAAwC;AAC5D,UAAM,cAAc,OAAO,QAAQ,IAAI;AACvC,QAAI,CAAC,eAAe;AAClB,YAAM,IAAI;AAAA,QACR,oGAAoG,WAAW;AAAA,MACjH;AAAA,IACF;AACA,YAAQ,eAAe,WAAqB;AAC1C,YAAM,WAAW,kBAAkB,IAAI,IAAI,KAAK,CAAC;AACjD,eAAS,QAAQ,IAAI,IAAI;AACzB,wBAAkB,IAAI,MAAM,QAAQ;AAAA,IACtC,CAAC;AAAA,EACH;AACF;AAEO,SAAS,YAA8B,OAAiB,UAAa;AAC1E,YAAU,IAAI,OAAO,QAAQ;AAC/B;AAEO,SAAS,YAA8B,OAAoB;AAChE,MAAI,CAAC,UAAU,IAAI,KAAK,GAAG;AACzB,UAAM,WAAW,IAAI,MAAM;AAC3B,cAAU,IAAI,OAAO,QAAQ;AAE7B,UAAM,aAAa,kBAAkB,IAAI,QAAQ;AACjD,QAAI,YAAY;AACd,iBAAW,CAAC,aAAa,aAAa,KAAK,OAAO,QAAQ,UAAU,GAAG;AACrE,iBAAS,WAAW,IAAI,YAAY,cAAc,CAAC;AAAA,MACrD;AAAA,IACF;AAAA,EACF;AACA,SAAO,UAAU,IAAI,KAAK;AAC5B;","names":["crypto"]}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../helpers/src/sleep.ts","../../helpers/src/hashObject.ts","../../helpers/src/generateId.ts","../../helpers/src/createMap.ts","../../helpers/src/createMapArray.ts","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/type.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/_internals/isArray.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/isType.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/clone.js","../../helpers/src/clone.ts","../../helpers/src/Errors/OrionError.ts","../../helpers/src/Errors/PermissionsError.ts","../../helpers/src/Errors/UserError.ts","../../helpers/src/Errors/index.ts","../../helpers/src/composeMiddlewares.ts","../../helpers/src/retries.ts","../../helpers/src/generateUUID.ts","../../helpers/src/normalize.ts","../../helpers/src/searchTokens.ts","../../helpers/src/shortenMongoId.ts","../src/di.ts"],"sourcesContent":["/**\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 crypto from 'node:crypto'\n\n/**\n * Receives any javascript object, string, number, boolean, array, or object and returns a hash of it.\n */\nexport default function hashObject(object: any): string {\n const string = objectToString(object)\n return crypto.createHash('sha256').update(string).digest('hex')\n}\n\nfunction objectToString(object: any): string {\n if (object === null || object === undefined) {\n return 'null'\n }\n\n if (typeof object === 'string') {\n return object\n }\n\n if (typeof object === 'number' || typeof object === 'boolean') {\n return String(object)\n }\n\n if (object instanceof Date) {\n return object.toISOString()\n }\n\n if (Array.isArray(object)) {\n const arrayHash = object.map(item => hashObject(item)).join(',')\n return `[${arrayHash}]`\n }\n\n if (typeof object === 'object') {\n const keys = Object.keys(object).sort()\n const objectHash = keys.map(key => `${key}:${hashObject(object[key])}`).join(',')\n return `{${objectHash}}`\n }\n\n // Fallback for functions or other types\n return String(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","export function type(input){\n if (input === null){\n return 'Null'\n } else if (input === undefined){\n return 'Undefined'\n } else if (Number.isNaN(input)){\n return 'NaN'\n }\n const typeResult = Object.prototype.toString.call(input).slice(8, -1)\n\n return typeResult === 'AsyncFunction' ? 'Promise' : typeResult\n}\n","export const { isArray } = Array\n","import { type } from './type.js'\n\nexport function isType(xType, x){\n if (arguments.length === 1){\n return xHolder => isType(xType, xHolder)\n }\n\n return type(x) === xType\n}\n","import { isArray } from './_internals/isArray.js'\n\nexport function clone(input){\n const out = isArray(input) ? Array(input.length) : {}\n if (input && input.getTime) return new Date(input.getTime())\n\n for (const key in input){\n const v = input[ key ]\n out[ key ] =\n typeof v === 'object' && v !== null ?\n v.getTime ?\n new Date(v.getTime()) :\n clone(v) :\n v\n }\n\n return out\n}\n","import {isType, clone as cloneRambdax} from 'rambdax'\n\nexport function clone<T>(value: T): T {\n if (isType('Object', value)) {\n return cloneRambdax(value)\n }\n\n if (Array.isArray(value)) {\n return cloneRambdax(value)\n }\n\n return value\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 {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 (\n 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}\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","import {generateId} from '../../helpers/dist'\n\ntype Token<T> = {new (...args: any[]): T}\n\nconst instances = new Map<Token<any>, any>()\nconst serviceMetadata = new WeakMap<object, {id: string; name: string}>()\nconst injectionMetadata = new WeakMap<object, Record<string | symbol, () => Token<any>>>()\n\nexport function Service() {\n return (_target: Function, context: ClassDecoratorContext) => {\n serviceMetadata.set(context, {\n id: generateId(12),\n name: context.name,\n })\n }\n}\n\nexport function Inject<T>(getDependency: () => Token<T>) {\n return (_: undefined, context: ClassFieldDecoratorContext) => {\n const propertyKey = String(context.name)\n if (!getDependency) {\n throw new Error(\n `Since v4, Inject() requires a function that returns the dependency token. Check the @Inject() of ${propertyKey}`,\n )\n }\n context.addInitializer(function (this: any) {\n const metadata = injectionMetadata.get(this) || {}\n metadata[context.name] = getDependency\n injectionMetadata.set(this, metadata)\n })\n }\n}\n\nexport function setInstance<T extends object>(token: Token<T>, instance: T) {\n instances.set(token, instance)\n}\n\nexport function getInstance<T extends object>(token: Token<T>): T {\n if (!instances.has(token)) {\n const instance = new token()\n instances.set(token, instance)\n\n const injections = injectionMetadata.get(instance)\n if (injections) {\n for (const [propertyKey, getDependency] of Object.entries(injections)) {\n instance[propertyKey] = getInstance(getDependency())\n }\n }\n }\n return instances.get(token)\n}\n"],"mappings":";AEAA,OAAOA,aAAY;AAEnB,IAAM,qBAAqB;AAE3B,IAAM,YAAY,SAAU,QAAQ;AAClC,MAAI,WAAW,KAAK,KAAK,SAAS,CAAC;AACnC,MAAI;AAGJ,MAAI;AACF,YAAQC,QAAO,YAAY,QAAQ;EACrC,SAAS,GAAG;AAEV,YAAQA,QAAO,kBAAkB,QAAQ;EAC3C;AACA,MAAI,SAAS,MAAM,SAAS,KAAK;AAGjC,SAAO,OAAO,UAAU,GAAG,MAAM;AACnC;AAEA,IAAM,WAAW,WAAY;AAC3B,MAAI,YAAY,SAAS,UAAU,CAAC,GAAG,EAAE;AACzC,SAAO,YAAY;AACrB;AAEA,IAAM,SAAS,SAAU,eAAe;AACtC,MAAI,QAAQ,KAAK,MAAM,SAAS,IAAI,cAAc,MAAM;AACxD,MAAI,OAAO,kBAAkB,SAAU,QAAO,cAAc,OAAO,OAAO,CAAC;MACtE,QAAO,cAAc,KAAK;AACjC;AAEA,IAAM,eAAe,SAAU,YAAY,UAAU;AACnD,MAAI,SAAS,CAAC;AACd,WAAS,IAAI,GAAG,IAAI,YAAY,KAAK;AACnC,WAAO,CAAC,IAAI,OAAO,QAAQ;EAC7B;AACA,SAAO,OAAO,KAAK,EAAE;AACvB;AAOe,SAAR,WACL,YACA,QAAgB,oBACR;AACR,MAAI,CAAC,YAAY;AACf,iBAAa;EACf;AAEA,SAAO,aAAa,YAAY,KAAK;AACvC;AItDO,IAAM,EAAE,QAAQ,IAAI;;;AcI3B,IAAM,YAAY,oBAAI,IAAqB;AAC3C,IAAM,kBAAkB,oBAAI,QAA4C;AACxE,IAAM,oBAAoB,oBAAI,QAA2D;AAElF,SAAS,UAAU;AACxB,SAAO,CAAC,SAAmB,YAAmC;AAC5D,oBAAgB,IAAI,SAAS;AAAA,MAC3B,IAAI,WAAW,EAAE;AAAA,MACjB,MAAM,QAAQ;AAAA,IAChB,CAAC;AAAA,EACH;AACF;AAEO,SAAS,OAAU,eAA+B;AACvD,SAAO,CAAC,GAAc,YAAwC;AAC5D,UAAM,cAAc,OAAO,QAAQ,IAAI;AACvC,QAAI,CAAC,eAAe;AAClB,YAAM,IAAI;AAAA,QACR,oGAAoG,WAAW;AAAA,MACjH;AAAA,IACF;AACA,YAAQ,eAAe,WAAqB;AAC1C,YAAM,WAAW,kBAAkB,IAAI,IAAI,KAAK,CAAC;AACjD,eAAS,QAAQ,IAAI,IAAI;AACzB,wBAAkB,IAAI,MAAM,QAAQ;AAAA,IACtC,CAAC;AAAA,EACH;AACF;AAEO,SAAS,YAA8B,OAAiB,UAAa;AAC1E,YAAU,IAAI,OAAO,QAAQ;AAC/B;AAEO,SAAS,YAA8B,OAAoB;AAChE,MAAI,CAAC,UAAU,IAAI,KAAK,GAAG;AACzB,UAAM,WAAW,IAAI,MAAM;AAC3B,cAAU,IAAI,OAAO,QAAQ;AAE7B,UAAM,aAAa,kBAAkB,IAAI,QAAQ;AACjD,QAAI,YAAY;AACd,iBAAW,CAAC,aAAa,aAAa,KAAK,OAAO,QAAQ,UAAU,GAAG;AACrE,iBAAS,WAAW,IAAI,YAAY,cAAc,CAAC;AAAA,MACrD;AAAA,IACF;AAAA,EACF;AACA,SAAO,UAAU,IAAI,KAAK;AAC5B;","names":["crypto","crypto"]}
|
|
1
|
+
{"version":3,"sources":["../../helpers/src/sleep.ts","../../helpers/src/hashObject.ts","../../helpers/src/generateId.ts","../../helpers/src/createMap.ts","../../helpers/src/createMapArray.ts","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/type.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/_internals/isArray.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/isType.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/clone.js","../../helpers/src/clone.ts","../../helpers/src/Errors/OrionError.ts","../../helpers/src/Errors/PermissionsError.ts","../../helpers/src/Errors/UserError.ts","../../helpers/src/Errors/index.ts","../../helpers/src/composeMiddlewares.ts","../../helpers/src/retries.ts","../../helpers/src/generateUUID.ts","../../helpers/src/normalize.ts","../../helpers/src/searchTokens.ts","../../helpers/src/shortenMongoId.ts","../src/di.ts"],"sourcesContent":["/**\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 crypto from 'node:crypto'\n\n/**\n * Receives any javascript object, string, number, boolean, array, or object and returns a hash of it.\n */\nexport default function hashObject(object: any): string {\n const string = objectToString(object)\n return crypto.createHash('sha256').update(string).digest('hex')\n}\n\nfunction objectToString(object: any): string {\n if (object === null || object === undefined) {\n return 'null'\n }\n\n if (typeof object === 'string') {\n return object\n }\n\n if (typeof object === 'number' || typeof object === 'boolean') {\n return String(object)\n }\n\n if (object instanceof Date) {\n return object.toISOString()\n }\n\n if (Array.isArray(object)) {\n const arrayHash = object.map(item => hashObject(item)).join(',')\n return `[${arrayHash}]`\n }\n\n if (typeof object === 'object') {\n const keys = Object.keys(object).sort()\n const objectHash = keys.map(key => `${key}:${hashObject(object[key])}`).join(',')\n return `{${objectHash}}`\n }\n\n // Fallback for functions or other types\n return String(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","export function type(input){\n if (input === null){\n return 'Null'\n } else if (input === undefined){\n return 'Undefined'\n } else if (Number.isNaN(input)){\n return 'NaN'\n }\n const typeResult = Object.prototype.toString.call(input).slice(8, -1)\n\n return typeResult === 'AsyncFunction' ? 'Promise' : typeResult\n}\n","export const { isArray } = Array\n","import { type } from './type.js'\n\nexport function isType(xType, x){\n if (arguments.length === 1){\n return xHolder => isType(xType, xHolder)\n }\n\n return type(x) === xType\n}\n","import { isArray } from './_internals/isArray.js'\n\nexport function clone(input){\n const out = isArray(input) ? Array(input.length) : {}\n if (input && input.getTime) return new Date(input.getTime())\n\n for (const key in input){\n const v = input[ key ]\n out[ key ] =\n typeof v === 'object' && v !== null ?\n v.getTime ?\n new Date(v.getTime()) :\n clone(v) :\n v\n }\n\n return out\n}\n","import {isType, clone as cloneRambdax} from 'rambdax'\n\nexport function clone<T>(value: T): T {\n if (isType('Object', value)) {\n return cloneRambdax(value)\n }\n\n if (Array.isArray(value)) {\n return cloneRambdax(value)\n }\n\n return value\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 {v7 as uuidv7} from 'uuid'\n\nexport function generateUUID() {\n return uuidv7()\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 (\n 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}\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","import {generateId} from '../../helpers/dist'\n\ntype Token<T> = {new (...args: any[]): T}\n\nconst instances = new Map<Token<any>, any>()\nconst serviceMetadata = new WeakMap<object, {id: string; name: string}>()\nconst injectionMetadata = new WeakMap<object, Record<string | symbol, () => Token<any>>>()\n\nexport function Service() {\n return (_target: Function, context: ClassDecoratorContext) => {\n serviceMetadata.set(context, {\n id: generateId(12),\n name: context.name,\n })\n }\n}\n\nexport function Inject<T>(getDependency: () => Token<T>) {\n return (_: undefined, context: ClassFieldDecoratorContext) => {\n const propertyKey = String(context.name)\n if (!getDependency) {\n throw new Error(\n `Since v4, Inject() requires a function that returns the dependency token. Check the @Inject() of ${propertyKey}`,\n )\n }\n context.addInitializer(function (this: any) {\n const metadata = injectionMetadata.get(this) || {}\n metadata[context.name] = getDependency\n injectionMetadata.set(this, metadata)\n })\n }\n}\n\nexport function setInstance<T extends object>(token: Token<T>, instance: T) {\n instances.set(token, instance)\n}\n\nexport function getInstance<T extends object>(token: Token<T>): T {\n if (!instances.has(token)) {\n const instance = new token()\n instances.set(token, instance)\n\n const injections = injectionMetadata.get(instance)\n if (injections) {\n for (const [propertyKey, getDependency] of Object.entries(injections)) {\n instance[propertyKey] = getInstance(getDependency())\n }\n }\n }\n return instances.get(token)\n}\n"],"mappings":";AEAA,OAAOA,aAAY;AAEnB,IAAM,qBAAqB;AAE3B,IAAM,YAAY,SAAU,QAAQ;AAClC,MAAI,WAAW,KAAK,KAAK,SAAS,CAAC;AACnC,MAAI;AAGJ,MAAI;AACF,YAAQC,QAAO,YAAY,QAAQ;EACrC,SAAS,GAAG;AAEV,YAAQA,QAAO,kBAAkB,QAAQ;EAC3C;AACA,MAAI,SAAS,MAAM,SAAS,KAAK;AAGjC,SAAO,OAAO,UAAU,GAAG,MAAM;AACnC;AAEA,IAAM,WAAW,WAAY;AAC3B,MAAI,YAAY,SAAS,UAAU,CAAC,GAAG,EAAE;AACzC,SAAO,YAAY;AACrB;AAEA,IAAM,SAAS,SAAU,eAAe;AACtC,MAAI,QAAQ,KAAK,MAAM,SAAS,IAAI,cAAc,MAAM;AACxD,MAAI,OAAO,kBAAkB,SAAU,QAAO,cAAc,OAAO,OAAO,CAAC;MACtE,QAAO,cAAc,KAAK;AACjC;AAEA,IAAM,eAAe,SAAU,YAAY,UAAU;AACnD,MAAI,SAAS,CAAC;AACd,WAAS,IAAI,GAAG,IAAI,YAAY,KAAK;AACnC,WAAO,CAAC,IAAI,OAAO,QAAQ;EAC7B;AACA,SAAO,OAAO,KAAK,EAAE;AACvB;AAOe,SAAR,WACL,YACA,QAAgB,oBACR;AACR,MAAI,CAAC,YAAY;AACf,iBAAa;EACf;AAEA,SAAO,aAAa,YAAY,KAAK;AACvC;AItDO,IAAM,EAAE,QAAQ,IAAI;;;AcI3B,IAAM,YAAY,oBAAI,IAAqB;AAC3C,IAAM,kBAAkB,oBAAI,QAA4C;AACxE,IAAM,oBAAoB,oBAAI,QAA2D;AAElF,SAAS,UAAU;AACxB,SAAO,CAAC,SAAmB,YAAmC;AAC5D,oBAAgB,IAAI,SAAS;AAAA,MAC3B,IAAI,WAAW,EAAE;AAAA,MACjB,MAAM,QAAQ;AAAA,IAChB,CAAC;AAAA,EACH;AACF;AAEO,SAAS,OAAU,eAA+B;AACvD,SAAO,CAAC,GAAc,YAAwC;AAC5D,UAAM,cAAc,OAAO,QAAQ,IAAI;AACvC,QAAI,CAAC,eAAe;AAClB,YAAM,IAAI;AAAA,QACR,oGAAoG,WAAW;AAAA,MACjH;AAAA,IACF;AACA,YAAQ,eAAe,WAAqB;AAC1C,YAAM,WAAW,kBAAkB,IAAI,IAAI,KAAK,CAAC;AACjD,eAAS,QAAQ,IAAI,IAAI;AACzB,wBAAkB,IAAI,MAAM,QAAQ;AAAA,IACtC,CAAC;AAAA,EACH;AACF;AAEO,SAAS,YAA8B,OAAiB,UAAa;AAC1E,YAAU,IAAI,OAAO,QAAQ;AAC/B;AAEO,SAAS,YAA8B,OAAoB;AAChE,MAAI,CAAC,UAAU,IAAI,KAAK,GAAG;AACzB,UAAM,WAAW,IAAI,MAAM;AAC3B,cAAU,IAAI,OAAO,QAAQ;AAE7B,UAAM,aAAa,kBAAkB,IAAI,QAAQ;AACjD,QAAI,YAAY;AACd,iBAAW,CAAC,aAAa,aAAa,KAAK,OAAO,QAAQ,UAAU,GAAG;AACrE,iBAAS,WAAW,IAAI,YAAY,cAAc,CAAC;AAAA,MACrD;AAAA,IACF;AAAA,EACF;AACA,SAAO,UAAU,IAAI,KAAK;AAC5B;","names":["crypto","crypto"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@orion-js/services",
|
|
3
|
-
"version": "4.0.
|
|
3
|
+
"version": "4.0.3",
|
|
4
4
|
"main": "./dist/index.cjs",
|
|
5
5
|
"types": "./dist/index.d.ts",
|
|
6
6
|
"files": [
|
|
@@ -10,7 +10,10 @@
|
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"typedi": "^0.10.0",
|
|
13
|
-
"@orion-js/helpers": "4.0.
|
|
13
|
+
"@orion-js/helpers": "4.0.2"
|
|
14
|
+
},
|
|
15
|
+
"peerDependencies": {
|
|
16
|
+
"@orion-js/logger": "4.0.5"
|
|
14
17
|
},
|
|
15
18
|
"devDependencies": {
|
|
16
19
|
"typescript": "^5.4.5",
|