@homer0/object-utils 4.0.0 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/fns/merge.ts","../src/fns/copy.ts","../src/fns/formatKeys.ts","../src/fns/dashToLowerCamelKeys.ts","../src/fns/dashToSnakeKeys.ts","../src/fns/get.ts","../src/fns/set.ts","../src/fns/extract.ts","../src/fns/flat.ts","../src/fns/lowerCamelToDashKeys.ts","../src/fns/lowerCamelToSnakeKeys.ts","../src/fns/remove.ts","../src/fns/snakeToDashKeys.ts","../src/fns/snakeToLowerCamelKeys.ts","../src/fns/unflat.ts"],"sourcesContent":["export * from './fns/copy';\nexport * from './fns/dashToLowerCamelKeys';\nexport * from './fns/dashToSnakeKeys';\nexport * from './fns/extract';\nexport * from './fns/flat';\nexport * from './fns/formatKeys';\nexport * from './fns/get';\nexport * from './fns/lowerCamelToDashKeys';\nexport * from './fns/lowerCamelToSnakeKeys';\nexport * from './fns/merge';\nexport * from './fns/remove';\nexport * from './fns/set';\nexport * from './fns/snakeToDashKeys';\nexport * from './fns/snakeToLowerCamelKeys';\nexport * from './fns/unflat';\n","import extend from 'extend';\n\n/**\n * This method makes a deep merge of a list of objects into a new one. The method also\n * supports arrays: if the first element is an array, it will be merged into an array,\n * otherwise, it will be an object.\n *\n * @param targets The list of objects to merge.\n * @template T The type of the merged object that will be returned.\n * @example\n *\n * const objA = { a: 'first' };\n * const objB = { b: 'second' };\n * console.log(merge(objA, objB));\n * // Will output { a: 'first', b: 'second' }\n *\n * @example\n *\n * const arrA = [{ a: 'first' }];\n * const arrB = [{ b: 'second' }];\n * console.log(merge(objA, objB));\n * // Will output [{ a: 'first', b: 'second' }]\n *\n */\nexport const merge = <T = unknown>(...targets: unknown[]): T => {\n const [firstTarget] = targets;\n const base = Array.isArray(firstTarget) ? [] : {};\n return extend(true, base, ...targets) as T;\n};\n","import { merge } from './merge';\n\n/**\n * Creates a deep copy of a given object.\n *\n * @param target The object to copy.\n * @template T The type of the input object, which will be the same as the one\n * returned.\n */\nexport const copy = <T>(target: T): T => merge(target);\n","/**\n * The callback that will be used to replace a key.\n *\n * @param substring The captured string to replace.\n * @param args The list of groups captured by the expression.\n */\nexport type FormatKeysReplaceFn = (substring: string, ...args: string[]) => string;\n\nexport type FormatKeysOptions = {\n /**\n * The object to transform.\n */\n target: unknown;\n /**\n * A regular expression to match the keys to transform.\n */\n search: RegExp;\n /**\n * The callback that will be used to replace the matched substring. Think of `search` and\n * `replace` as the parameters of `String.replace`.\n */\n replace: FormatKeysReplaceFn;\n /**\n * A list of keys or paths where the transformation will be made. If not specified, the\n * function will use all the keys from the object.\n */\n include?: string[];\n /**\n * A list of keys or paths where the transformation won't be made.\n */\n exclude?: string[];\n /**\n * The delimiter that will separate the path components for both `include` and `exclude`.\n */\n pathDelimiter?: string;\n};\n\nexport type FormatKeysExtensionOptions = Omit<FormatKeysOptions, 'search' | 'replace'>;\n\n/**\n * Formats all the keys on an object using a way similar to `.replace(regexp, ...)` but\n * that also works recursively and with _\"object paths\"_.\n *\n * @param options The set of options to customize the transformation.\n * @template T The type of the returned object.\n * @example\n *\n * const target = {\n * prop_one: 'Charito!',\n * };\n * console.log(\n * formatKeys({\n * target,\n * // Find all the keys with snake case.\n * search: /([a-z])_([a-z])/g,\n * // Using the same .replace style callback, replace it with lower camel case.\n * replace: (_, firstLetter, secondLetter) => {\n * const newSecondLetter = secondLetter.toUpperCase();\n * return `${firstLetter}${newSecondLetter}`;\n * },\n * }),\n * );\n * // Will output { propOne: 'Charito!}.\n *\n */\nexport const formatKeys = <T = Record<string, unknown>>(\n options: FormatKeysOptions,\n): T => {\n const {\n target,\n search,\n replace,\n include = [],\n exclude = [],\n pathDelimiter = '.',\n } = options;\n // Re-case target.\n const useTarget = target as Record<string, unknown>;\n // First of all, get all the keys from the target.\n const keys = Object.keys(target as Record<string, unknown>);\n /**\n * Then, check which keys are parent to other objects.\n * This is saved on a dictionary not only because it makes it easier to check if the\n * method should make a recursive call for a key, but also because when parsing the\n * `exclude`\n * parameter, if one of items is a key (and not an specific path), the method won't make\n * the recursive call.\n *\n * @ignore\n */\n const hasChildrenByKey: Record<string, unknown> = {};\n keys.forEach((key) => {\n const value = useTarget[key];\n hasChildrenByKey[key] = !!(\n value &&\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n Object.keys(value)\n );\n });\n /**\n * Escape the path delimiter and create two regular expression: One that removes the path\n * delimiter from the start of a path and one that removes it from the end.\n * They are later used to normalize paths in order to avoid \"incomplete paths\" (paths that\n * end or start with the delimiter).\n */\n const escapedPathDelimiter = pathDelimiter.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&');\n const cleanPathStartExpression = new RegExp(`^${escapedPathDelimiter}`, 'i');\n const cleanPathEndExpression = new RegExp(`${escapedPathDelimiter}$`, 'i');\n /**\n * This dictionary will be used to save the `include` parameter that will be sent for specific\n * keys on recursive calls.\n * If `include` has a path like `myKey.mySubKey`, `myKey` is not transformed, but `mySubKey`\n * is saved on this dictionary (`{ myKey: ['mySubKey']}`) and when the method applies the\n * formatting to the object, if `myKey` has an object, it will make a recursive all and\n * send `['mySubKey]` as its `include` parameter.\n */\n const subIncludeByKey: Record<string, string[]> = {};\n /**\n * This will be an array containing the final list of `keys` that should be tranformed.\n * To be clear, these keys will be from the top level, so, they won't be paths.\n * Thd following blocks will parse `include` and `exclude` in order to extract the real keys,\n * prepare the `include` and `exclude` for recursive calls, and save the actual keys\n * from the object \"at the current level of this call\" (no, it's not thinking about the\n * children :P).\n */\n let keysToFormat: string[];\n // If the `include` parameter has paths/keys...\n if (include.length) {\n keysToFormat = include\n .map((includePath) => {\n // Normalize the path/key.\n const useIncludePath = includePath\n .replace(cleanPathStartExpression, '')\n .replace(cleanPathEndExpression, '');\n // Define the variable that will, eventually, have the real key.\n let key;\n // If the value is a path...\n if (useIncludePath.includes(pathDelimiter)) {\n // Split all its components.\n const pathParts = useIncludePath.split(pathDelimiter);\n // Get the first component, a.k.a. the real key.\n const pathKey = pathParts.shift()!;\n /**\n * This is very important: Since the path was specified with sub components\n * (like `myProp.mySubProp`), the method won't format the key, but the sub\n * key(s)\n * (`mySubProp`).\n * The `key` is set to `''` so it will be later removed using `.filter`.\n *\n * @ignore\n */\n key = '';\n /**\n * If there's no array for the key on the \"`include` dictionary for recursive calls\",\n * create an empty one.\n */\n if (!subIncludeByKey[pathKey]) {\n subIncludeByKey[pathKey] = [];\n }\n // Save the rest of the path to be sent on the recursive call as `include`.\n subIncludeByKey[pathKey]!.push(pathParts.join(pathDelimiter));\n } else {\n // If the value wasn't a path, assume it's a key, and set it to be returned.\n key = useIncludePath;\n }\n\n return key;\n })\n // Remove any _empty keys_.\n .filter((key) => key);\n } else {\n // There's nothing on the `include` parameter, so use all the keys.\n keysToFormat = keys;\n }\n /**\n * Similar to `subIncludeByKey`, this dictionary will be used to save the `exclude` parameter\n * that will be sent for specific keys on recursive calls.\n * If `exclude` has a path like `myKey.mySubKey`, `myKey` will be transformed, but `mySubKey`\n * is saved on this dictionary (`{ myKey: ['mySubKey']}`) and when the method applies the\n * formatting to the object, if `myKey` has an object, it will make a recursive all and\n * send `['mySubKey]` as its `exclude` parameter.\n */\n const subExcludeByKey: Record<string, string[]> = {};\n // If the `include` parameter has paths/keys...\n if (exclude.length) {\n /**\n * Create a dictionary of keys that should be removed from `keysToFormat`.\n * It's easier to have them on a list and use `.filter` than actually call `.splice` for\n * every key that should be removed.\n */\n const keysToRemove: string[] = [];\n exclude.forEach((excludePath) => {\n // Normalize the path/key.\n const useExcludePath = excludePath\n .replace(cleanPathStartExpression, '')\n .replace(cleanPathEndExpression, '');\n // If the value is a path...\n if (useExcludePath.includes(pathDelimiter)) {\n // Split all its components.\n const pathParts = useExcludePath.split(pathDelimiter);\n // Get the first component, a.k.a. the real key.\n const pathKey = pathParts.shift()!;\n /**\n * If there's no array for the key on the \"`exclude` dictionary for recursive calls\",\n * create an empty one.\n */\n if (!subExcludeByKey[pathKey]) {\n subExcludeByKey[pathKey] = [];\n }\n // Save the rest of the path to be sent on the recursive call as `exclude`.\n subExcludeByKey[pathKey]!.push(pathParts.join(pathDelimiter));\n } else {\n /**\n * If the value wasn't a path, assume it's a key, turn the flag on the \"children\n * dictionary\" to `false`, to prevent recursive calls, and add the key to the list\n * of keys that will be removed from `keysToFormat`.\n * Basically: If it's a key, don't format it and don't make recursive calls for\n * it.\n *\n * @ignore\n */\n hasChildrenByKey[useExcludePath] = false;\n keysToRemove.push(useExcludePath);\n }\n });\n // Remove keys that should be excluded.\n keysToFormat = keysToFormat.filter((key) => key && !keysToRemove.includes(key));\n }\n // \"Finally\", reduce all the keys from the object and create the new one...\n return keys.reduce<Record<string, unknown>>((newObj, key) => {\n /**\n * Define the new key and value for the object property. Depending on the validations,\n * they may be replaced with formatted ones.\n */\n let newKey;\n let newValue;\n /**\n * Get the current value for the key, in case it's needed for a recursive call or just\n * to send it back because it didn't need any change.\n */\n const value = useTarget[key];\n // If the key should be formatted, apply the formatting; otherwise, keep the original.\n if (keysToFormat.includes(key)) {\n newKey = key.replace(search, replace);\n } else {\n newKey = key;\n }\n /**\n * If the paths/keys on `exclude` didn't modify the \"children dictionary\" for the key and\n * the value is another object, make a recursive call; otherwise, just use the original\n * value.\n */\n if (hasChildrenByKey[key]) {\n newValue = formatKeys({\n target: value,\n search,\n replace,\n include: subIncludeByKey[key] || [],\n exclude: subExcludeByKey[key] || [],\n pathDelimiter,\n });\n } else {\n newValue = value;\n }\n // \"Done\", return the new object with the \"new key\" and the \"new value\".\n return { ...newObj, [newKey]: newValue };\n }, {}) as T;\n};\n","import { formatKeys, type FormatKeysExtensionOptions } from './formatKeys';\n\n/**\n * A shorthand method for {@link formatKeys} that transforms the keys from `dash-case`\n * to `lowerCamelCase`.\n *\n * @param options The options to use.\n * @template T The type of the returned object.\n */\nexport const dashToLowerCamelKeys = <T>(options: FormatKeysExtensionOptions): T =>\n formatKeys<T>({\n ...options,\n search: /([a-z])-([a-z])/g,\n replace: (_, firstLetter, secondLetter) => {\n const newSecondLetter = secondLetter.toUpperCase();\n return `${firstLetter}${newSecondLetter}`;\n },\n });\n","import { formatKeys, type FormatKeysExtensionOptions } from './formatKeys';\n\n/**\n * A shorthand method for {@link formatKeys} that transforms the keys from `dash-case`\n * to `snake_case`.\n *\n * @param options The options to use.\n * @template T The type of the returned object.\n */\nexport const dashToSnakeKeys = <T>(options: FormatKeysExtensionOptions): T =>\n formatKeys<T>({\n ...options,\n search: /([a-z])-([a-z])/g,\n replace: (_, firstLetter, secondLetter) => `${firstLetter}_${secondLetter}`,\n });\n","export type GetOptions = {\n /**\n * The object from where the property will be read.\n */\n target: unknown;\n /**\n * The path to the property.\n */\n path: string;\n /**\n * The delimiter that will separate the path components.\n */\n pathDelimiter?: string;\n /**\n * Whether or not to throw an error when the path is invalid. If this is `false`,\n * the method will silently fail and return `undefined`.\n */\n failWithError?: boolean;\n};\n\n/**\n * Returns the value of an object property using a path.\n *\n * @param options The options to use.\n * @template T The type of the returned object.\n * @throws {Error} If the path is invalid and `failWithError` is set to `true`.\n * @example\n *\n * const obj = {\n * propOne: {\n * propOneSub: 'Charito!',\n * },\n * propTwo: '!!!',\n * };\n * console.log(get({ target: obj, path: 'propOne.propOneSub' }));\n * // Will output 'Charito!'\n *\n */\nfunction get<T>(options: GetOptions): T | undefined;\nfunction get<T>(options: unknown, path: string): T | undefined;\nfunction get<T>(options: GetOptions | unknown, path?: string): T | undefined {\n let useOptions: GetOptions;\n if (typeof path === 'string') {\n useOptions = {\n target: options,\n path,\n };\n } else {\n useOptions = options as GetOptions;\n }\n\n const {\n target,\n path: usePath,\n pathDelimiter = '.',\n failWithError = false,\n } = useOptions;\n const useTarget = target as Record<string, unknown>;\n const parts = usePath.split(pathDelimiter);\n const first = parts.shift()!;\n let currentElement = useTarget[first] as Record<string, unknown>;\n if (typeof currentElement === 'undefined') {\n if (failWithError) {\n throw new Error(`There's nothing on '${usePath}'`);\n }\n\n return undefined;\n }\n\n if (!parts.length) {\n return currentElement as T;\n }\n\n let currentPath = first;\n parts.some((currentPart) => {\n let breakLoop = false;\n currentPath += `${pathDelimiter}${currentPart}`;\n currentElement = currentElement[currentPart] as Record<string, unknown>;\n if (typeof currentElement === 'undefined') {\n if (failWithError) {\n throw new Error(`There's nothing on '${currentPath}'`);\n } else {\n breakLoop = true;\n }\n }\n\n return breakLoop;\n });\n\n return currentElement as T;\n}\n\nexport { get };\n","import { copy } from './copy';\n\n/**\n * List of paths that are forbidden to use on the `set` function, as they could lead to\n * security issues.\n *\n * @access protected\n */\nconst FORBIDDEN_PATHS = ['__proto__', 'prototype', 'constructor'];\n\nexport type SetOptions = {\n /**\n * The object where the property will be set.\n */\n target: unknown;\n /**\n * The path for the property.\n */\n path: string;\n /**\n * The value to set on the property.\n */\n value: unknown;\n /**\n * The delimiter that will separate the path components.\n */\n pathDelimiter?: string;\n /**\n * Whether or not to throw an error when the path is invalid. If this is `false`, the method\n * will silently fail and return `undefined`.\n */\n failWithError?: boolean;\n};\n/**\n * Sets a property on an object using a path. If the path doesn't exist, it will be\n * created.\n *\n * @param options The options to use.\n * @template T The type of the returned object.\n * @throws {Error} If one of the path components is for a non-object property and\n * `failWithError` is set to `true`.\n * @example\n *\n * const target = {};\n * console.log(set({ target, path: 'some.prop.path', value: 'some-value' }));\n * // Will output { some: { prop: { path: 'some-value' } } }\n *\n */\nfunction set<T = Record<string, unknown>>(options: SetOptions): T | undefined;\nfunction set<T = Record<string, unknown>>(\n options: SetOptions | unknown,\n path: string,\n value: unknown,\n): T | undefined;\nfunction set<T = Record<string, unknown>>(\n options: SetOptions | unknown,\n path?: string,\n value?: unknown,\n): T | undefined {\n let useOptions: SetOptions;\n if (typeof path === 'string') {\n useOptions = {\n target: options,\n path,\n value,\n };\n } else {\n useOptions = options as SetOptions;\n }\n\n const {\n target,\n path: usePath,\n value: useValue,\n pathDelimiter = '.',\n failWithError = false,\n } = useOptions;\n const result = copy(target) as Record<string, unknown>;\n if (!usePath.includes(pathDelimiter)) {\n if (!usePath || FORBIDDEN_PATHS.includes(usePath.toLowerCase())) {\n return undefined;\n }\n\n result[usePath] = useValue;\n return result as T;\n }\n\n const parts = usePath.split(pathDelimiter);\n const isInvalid = parts.some(\n (part) => !part || FORBIDDEN_PATHS.includes(part.toLowerCase()),\n );\n\n if (isInvalid) {\n return undefined;\n }\n\n const last = parts.pop();\n let currentElement = result;\n let currentPath = '';\n let foundInvalid = false;\n parts.forEach((part) => {\n currentPath += `${pathDelimiter}${part}`;\n const element = currentElement[part];\n const elementType = typeof element;\n if (elementType === 'undefined') {\n currentElement[part] = {};\n currentElement = currentElement[part] as Record<string, unknown>;\n } else if (elementType === 'object') {\n currentElement = currentElement[part] as Record<string, unknown>;\n } else {\n const errorPath = currentPath.substring(pathDelimiter.length);\n if (failWithError) {\n throw new Error(\n `There's already an element of type '${elementType}' on '${errorPath}'`,\n );\n } else {\n foundInvalid = true;\n }\n }\n });\n\n if (foundInvalid) return undefined;\n\n if (result && last) {\n currentElement[last] = useValue;\n }\n\n return result as T | undefined;\n}\n\nexport { set };\n","import { get } from './get';\nimport { set } from './set';\nimport { copy } from './copy';\n/**\n * Used in the {@link extract} function to specify a path for a property, or an \"origin path\"\n * and an \"extraction path\".\n */\nexport type extractionPath = string | Record<string, string>;\n\nexport type ExtractOptions = {\n /**\n * The object from where the property/properties will be extracted.\n */\n target: unknown;\n /**\n * This can be a single path or a list of them. And for this method, the paths are not\n * only strings but can also be an object with a single key, that would be the path to\n * where to \"do the extraction\", and the value the path on the target object.\n */\n paths: extractionPath | extractionPath[];\n /**\n * The delimiter that will separate the path components.\n */\n pathDelimiter?: string;\n /**\n * Whether or not to throw an error when the path is invalid. If this is `false`, the\n * method will silently fail an empty object.\n */\n failWithError?: boolean;\n};\n/**\n * Extracts a property or properties from an object in order to create a new one.\n *\n * @param options The options to use.\n * @template T The type of the returned object.\n * @example\n *\n * const target = {\n * name: {\n * first: 'Pilar',\n * },\n * age: 3,\n * address: {\n * planet: 'earth',\n * something: 'else',\n * },\n * };\n * console.log(\n * extract({\n * target: obj,\n * paths: [{ name: 'name.first' }, 'age', 'address.planet'],\n * }),\n * );\n * // Will output { name: 'Pilar', age: 3, address: { planet: 'earth' } }\n *\n */\nexport const extract = <T = Record<string, unknown>>(\n options: ExtractOptions,\n): T | undefined => {\n const { target, paths, pathDelimiter = '.', failWithError = false } = options;\n const copied = copy(target) as Record<string, unknown>;\n let result: Record<string, unknown> = {};\n let failed = false;\n (Array.isArray(paths) ? paths : [paths])\n .reduce<Array<{ origin: string; customDest: boolean; dest: string }>>(\n (acc, objPath) => {\n let destPath: string;\n let originPath: string;\n if (typeof objPath === 'string') {\n destPath = objPath;\n originPath = objPath;\n } else {\n const [firstKey] = Object.keys(objPath);\n destPath = firstKey!;\n originPath = objPath[destPath]!;\n }\n\n acc.push({\n origin: originPath,\n customDest: destPath.includes(pathDelimiter),\n dest: destPath,\n });\n return acc;\n },\n [],\n )\n .some((pathInfo) => {\n let breakLoop = false;\n const value = get({\n target: copied,\n path: pathInfo.origin,\n pathDelimiter,\n failWithError,\n });\n if (typeof value !== 'undefined') {\n if (pathInfo.customDest) {\n const withCustomProp = set({\n target: result,\n path: pathInfo.dest,\n value,\n pathDelimiter,\n failWithError,\n });\n if (typeof withCustomProp === 'undefined') {\n breakLoop = true;\n failed = true;\n } else {\n result = withCustomProp;\n }\n } else {\n result[pathInfo.dest] = value;\n }\n }\n\n return breakLoop;\n });\n\n if (failed) return undefined;\n return result as T;\n};\n","import { copy } from './copy';\nimport { merge } from './merge';\n\n/**\n * Checks whether a key for an array or an Object should be flattened.\n *\n * @param key The key to check inside its parent.\n * @param value The value of the key.\n */\nexport type ShouldFlattenFn = (key: string, value: unknown) => boolean;\n\nexport type FlatOptions = {\n /**\n * The object to transform.\n */\n target: unknown;\n /**\n * A custom prefix to be added before the name of the properties. This can be used on\n * custom cases and it's also used when the method calls itself in order to flatten a\n * sub object.\n */\n prefix?: string;\n /**\n * The delimiter that will separate the path components.\n */\n pathDelimiter?: string;\n /**\n * A custom function that can be used in order to tell the function whether an Object or\n * an Array property should be flatten or not.\n */\n shouldFlatten?: ShouldFlattenFn;\n};\n/**\n * Flattens an object properties into a single level dictionary.\n *\n * @param options The options to use.\n * @template T The type of the returned object.\n * @example\n *\n * const target = {\n * propOne: {\n * propOneSub: 'Charito!',\n * },\n * propTwo: '!!!',\n * };\n * console.log(flat({ target });\n * // Will output { 'propOne.propOneSub': 'Charito!', propTwo: '!!!' }\n *\n */\nexport const flat = <T = Record<string, unknown>>(options: FlatOptions): T => {\n const { target, shouldFlatten, pathDelimiter = '.', prefix = '' } = options;\n const useTarget = target as Record<string, unknown>;\n let result: Record<string, unknown> = {};\n const namePrefix = prefix ? `${prefix}${pathDelimiter}` : '';\n Object.keys(useTarget).forEach((key) => {\n const name = `${namePrefix}${key}`;\n const value = useTarget[key] as unknown;\n const valueType = typeof value;\n const isObject = valueType === 'object' && value !== null;\n if (isObject && (!shouldFlatten || shouldFlatten(key, value))) {\n result = merge(\n result,\n flat({ target: value, pathDelimiter, prefix: name, shouldFlatten }),\n );\n } else {\n result[name] = isObject ? copy(value) : value;\n }\n });\n\n return result as T;\n};\n","import { formatKeys, type FormatKeysExtensionOptions } from './formatKeys';\n\n/**\n * A shorthand method for {@link formatKeys} that transforms the keys from\n * `lowerCamelCase` to `dash-case`.\n *\n * @param options The options to use.\n * @template T The type of the returned object.\n */\nexport const lowerCamelToDashKeys = <T>(options: FormatKeysExtensionOptions): T =>\n formatKeys<T>({\n ...options,\n search: /([a-z])([A-Z])/g,\n replace: (_, firstLetter, secondLetter) => {\n const newSecondLetter = secondLetter.toLowerCase();\n return `${firstLetter}-${newSecondLetter}`;\n },\n });\n","import { formatKeys, type FormatKeysExtensionOptions } from './formatKeys';\n\n/**\n * A shorthand method for {@link formatKeys} that transforms the keys from\n * `lowerCamelCase` to `snake_case`.\n *\n * @param options The options to use.\n * @template T The type of the returned object.\n */\nexport const lowerCamelToSnakeKeys = <T>(options: FormatKeysExtensionOptions): T =>\n formatKeys<T>({\n ...options,\n search: /([a-z])([A-Z])/g,\n replace: (_, firstLetter, secondLetter) => {\n const newSecondLetter = secondLetter.toLowerCase();\n return `${firstLetter}_${newSecondLetter}`;\n },\n });\n","import { copy } from './copy';\nimport { get } from './get';\n\nexport type RemoveOptions = {\n /**\n * The object from where the property will be removed.\n */\n target: unknown;\n /**\n * The path to the property.\n */\n path: string;\n /**\n * The delimiter that will separate the path components.\n */\n pathDelimiter?: string;\n /**\n * Whether or not to throw an error when the path is invalid. If this is `false`, the\n * function will silently fail.\n */\n failWithError?: boolean;\n /**\n * If this flag is `true` and after removing the property the parent object is empty,\n * it will remove it recursively until a non empty parent object is found.\n */\n cleanEmptyProperties?: boolean;\n};\n/**\n * Deletes a property of an object using a path.\n *\n * @param options The options to use.\n * @template T The type of the returned object.\n * @example\n *\n * const target = {\n * propOne: {\n * propOneSub: 'Charito!',\n * },\n * propTwo: '!!!',\n * };\n * console.log(remove({ target, path: 'propOne.propOneSub' }));\n * // Will output { propTwo: '!!!' }\n *\n */\nfunction remove<T = unknown>(options: RemoveOptions): T | undefined;\nfunction remove<T = unknown>(options: unknown, path: string): T | undefined;\nfunction remove<T = unknown>(\n options: RemoveOptions | unknown,\n path?: string,\n): T | undefined {\n let useOptions: RemoveOptions;\n if (typeof path === 'string') {\n useOptions = {\n target: options,\n path,\n };\n } else {\n useOptions = options as RemoveOptions;\n }\n\n const {\n target,\n path: usePath,\n pathDelimiter = '.',\n cleanEmptyProperties = true,\n failWithError = false,\n } = useOptions;\n\n const parts = usePath.split(pathDelimiter);\n const last = parts.pop()!;\n const result = copy(target) as Record<string, unknown>;\n if (!parts.length) {\n delete result[last];\n return result as T;\n }\n const parentPath = parts.join(pathDelimiter);\n const parentObj = get<Record<string, unknown>>({\n target: result,\n path: parentPath,\n pathDelimiter,\n failWithError,\n });\n\n if (typeof parentObj === 'undefined') {\n return undefined;\n }\n\n delete parentObj[last];\n if (cleanEmptyProperties && !Object.keys(parentObj).length) {\n return remove({\n target: result,\n path: parentPath,\n pathDelimiter,\n failWithError,\n cleanEmptyProperties,\n }) as T;\n }\n\n return result as T;\n}\n\nexport { remove };\n","import { formatKeys, type FormatKeysExtensionOptions } from './formatKeys';\n\n/**\n * A shorthand method for {@link formatKeys} that transforms the keys from `snake_case` to\n * `dash-case`.\n *\n * @param options The options to use.\n * @template T The type of the returned object.\n */\nexport const snakeToDashKeys = <T>(options: FormatKeysExtensionOptions): T =>\n formatKeys<T>({\n ...options,\n search: /([a-z])_([a-z])/g,\n replace: (_, firstLetter, secondLetter) => `${firstLetter}-${secondLetter}`,\n });\n","import { formatKeys, type FormatKeysExtensionOptions } from './formatKeys';\n\n/**\n * A shorthand method for {@link formatKeys} that transforms the keys from `snake_case` to\n * `lowerCamelCase`.\n *\n * @param options The options to use.\n * @template T The type of the returned object.\n */\nexport const snakeToLowerCamelKeys = <T>(options: FormatKeysExtensionOptions): T =>\n formatKeys<T>({\n ...options,\n search: /([a-z])_([a-z])/g,\n replace: (_, firstLetter, secondLetter) => {\n const newSecondLetter = secondLetter.toUpperCase();\n return `${firstLetter}${newSecondLetter}`;\n },\n });\n","import { set } from './set';\n\nexport type UnflatOptions = {\n /**\n * The object to transform.\n */\n target: unknown;\n /**\n * The delimiter that will separate the path components.\n */\n pathDelimiter?: string;\n};\n/**\n * This method does the exact opposite from `flat`: It takes an already flatten object and\n * restores it structure.\n *\n * @param options The options to use.\n * @template T The type of the returned object.\n * @example\n *\n * const target = {\n * 'propOne.propOneSub': 'Charito!',\n * propTwo: '!!!',\n * };\n * console.log(unflat({ target }));\n * // Will output { propOne: { propOneSub: 'Charito!' }, 'propTwo': '!!!' }\n *\n */\nexport const unflat = <T = Record<string, unknown>>(options: UnflatOptions): T => {\n const { target, pathDelimiter = '.' } = options;\n const useTarget = target as Record<string, unknown>;\n return Object.keys(useTarget).reduce<Record<string, unknown>>(\n (current, key) =>\n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;AAAA,IACF,CAAC;AAAA,EACH;AAEA,SAAO;AACT;;;AC1FO,IAAM,kBAAkB,CAAI,YACjC,WAAc;AAAA,EACZ,GAAG;AAAA,EACH,QAAQ;AAAA,EACR,SAAS,CAAC,GAAG,aAAa,iBAAiB,GAAG,WAAW,IAAI,YAAY;AAC3E,CAAC;;;ACLI,IAAM,wBAAwB,CAAI,YACvC,WAAc;AAAA,EACZ,GAAG;AAAA,EACH,QAAQ;AAAA,EACR,SAAS,CAAC,GAAG,aAAa,iBAAiB;AACzC,UAAM,kBAAkB,aAAa,YAAY;AACjD,WAAO,GAAG,WAAW,GAAG,eAAe;AAAA,EACzC;AACF,CAAC;;;ACWI,IAAM,SAAS,CAA8B,YAA8B;AAChF,QAAM,EAAE,QAAQ,gBAAgB,IAAI,IAAI;AACxC,QAAM,YAAY;AAClB,SAAO,OAAO,KAAK,SAAS,EAAE;AAAA,IAC5B,CAAC,SAAS,QACR,IAAI,EAAE,QAAQ,SAAS,MAAM,KAAK,OAAO,UAAU,GAAG,GAAG,cAAc,CAAC;AAAA,IAC1E,CAAC;AAAA,EACH;AACF;","names":["extend"]}
1
+ {"version":3,"sources":["../src/fns/merge.ts","../src/fns/copy.ts","../src/fns/formatKeys.ts","../src/fns/dashToLowerCamelKeys.ts","../src/fns/dashToSnakeKeys.ts","../src/fns/get.ts","../src/fns/set.ts","../src/fns/extract.ts","../src/fns/flat.ts","../src/fns/lowerCamelToDashKeys.ts","../src/fns/lowerCamelToSnakeKeys.ts","../src/fns/remove.ts","../src/fns/snakeToDashKeys.ts","../src/fns/snakeToLowerCamelKeys.ts","../src/fns/unflat.ts"],"sourcesContent":["import extend from 'extend';\n\n/**\n * This method makes a deep merge of a list of objects into a new one. The method also\n * supports arrays: if the first element is an array, it will be merged into an array,\n * otherwise, it will be an object.\n *\n * @param targets The list of objects to merge.\n * @template T The type of the merged object that will be returned.\n * @example\n *\n * const objA = { a: 'first' };\n * const objB = { b: 'second' };\n * console.log(merge(objA, objB));\n * // Will output { a: 'first', b: 'second' }\n *\n * @example\n *\n * const arrA = [{ a: 'first' }];\n * const arrB = [{ b: 'second' }];\n * console.log(merge(objA, objB));\n * // Will output [{ a: 'first', b: 'second' }]\n *\n */\nexport const merge = <T = unknown>(...targets: unknown[]): T => {\n const [firstTarget] = targets;\n const base = Array.isArray(firstTarget) ? [] : {};\n return extend(true, base, ...targets) as T;\n};\n","import { merge } from './merge.js';\n\n/**\n * Creates a deep copy of a given object.\n *\n * @param target The object to copy.\n * @template T The type of the input object, which will be the same as the one\n * returned.\n */\nexport const copy = <T>(target: T): T => merge(target);\n","/**\n * The callback that will be used to replace a key.\n *\n * @param substring The captured string to replace.\n * @param args The list of groups captured by the expression.\n */\nexport type FormatKeysReplaceFn = (substring: string, ...args: string[]) => string;\n\nexport type FormatKeysOptions = {\n /**\n * The object to transform.\n */\n target: unknown;\n /**\n * A regular expression to match the keys to transform.\n */\n search: RegExp;\n /**\n * The callback that will be used to replace the matched substring. Think of `search` and\n * `replace` as the parameters of `String.replace`.\n */\n replace: FormatKeysReplaceFn;\n /**\n * A list of keys or paths where the transformation will be made. If not specified, the\n * function will use all the keys from the object.\n */\n include?: string[];\n /**\n * A list of keys or paths where the transformation won't be made.\n */\n exclude?: string[];\n /**\n * The delimiter that will separate the path components for both `include` and `exclude`.\n */\n pathDelimiter?: string;\n};\n\nexport type FormatKeysExtensionOptions = Omit<FormatKeysOptions, 'search' | 'replace'>;\n\n/**\n * Formats all the keys on an object using a way similar to `.replace(regexp, ...)` but\n * that also works recursively and with _\"object paths\"_.\n *\n * @param options The set of options to customize the transformation.\n * @template T The type of the returned object.\n * @example\n *\n * const target = {\n * prop_one: 'Charito!',\n * };\n * console.log(\n * formatKeys({\n * target,\n * // Find all the keys with snake case.\n * search: /([a-z])_([a-z])/g,\n * // Using the same .replace style callback, replace it with lower camel case.\n * replace: (_, firstLetter, secondLetter) => {\n * const newSecondLetter = secondLetter.toUpperCase();\n * return `${firstLetter}${newSecondLetter}`;\n * },\n * }),\n * );\n * // Will output { propOne: 'Charito!}.\n *\n */\nexport const formatKeys = <T = Record<string, unknown>>(\n options: FormatKeysOptions,\n): T => {\n const {\n target,\n search,\n replace,\n include = [],\n exclude = [],\n pathDelimiter = '.',\n } = options;\n // Re-case target.\n const useTarget = target as Record<string, unknown>;\n // First of all, get all the keys from the target.\n const keys = Object.keys(target as Record<string, unknown>);\n /**\n * Then, check which keys are parent to other objects.\n * This is saved on a dictionary not only because it makes it easier to check if the\n * method should make a recursive call for a key, but also because when parsing the\n * `exclude`\n * parameter, if one of items is a key (and not an specific path), the method won't make\n * the recursive call.\n *\n * @ignore\n */\n const hasChildrenByKey: Record<string, unknown> = {};\n keys.forEach((key) => {\n const value = useTarget[key];\n hasChildrenByKey[key] = !!(\n value &&\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n Object.keys(value)\n );\n });\n /**\n * Escape the path delimiter and create two regular expression: One that removes the path\n * delimiter from the start of a path and one that removes it from the end.\n * They are later used to normalize paths in order to avoid \"incomplete paths\" (paths that\n * end or start with the delimiter).\n */\n const escapedPathDelimiter = pathDelimiter.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&');\n const cleanPathStartExpression = new RegExp(`^${escapedPathDelimiter}`, 'i');\n const cleanPathEndExpression = new RegExp(`${escapedPathDelimiter}$`, 'i');\n /**\n * This dictionary will be used to save the `include` parameter that will be sent for specific\n * keys on recursive calls.\n * If `include` has a path like `myKey.mySubKey`, `myKey` is not transformed, but `mySubKey`\n * is saved on this dictionary (`{ myKey: ['mySubKey']}`) and when the method applies the\n * formatting to the object, if `myKey` has an object, it will make a recursive all and\n * send `['mySubKey]` as its `include` parameter.\n */\n const subIncludeByKey: Record<string, string[]> = {};\n /**\n * This will be an array containing the final list of `keys` that should be tranformed.\n * To be clear, these keys will be from the top level, so, they won't be paths.\n * Thd following blocks will parse `include` and `exclude` in order to extract the real keys,\n * prepare the `include` and `exclude` for recursive calls, and save the actual keys\n * from the object \"at the current level of this call\" (no, it's not thinking about the\n * children :P).\n */\n let keysToFormat: string[];\n // If the `include` parameter has paths/keys...\n if (include.length) {\n keysToFormat = include\n .map((includePath) => {\n // Normalize the path/key.\n const useIncludePath = includePath\n .replace(cleanPathStartExpression, '')\n .replace(cleanPathEndExpression, '');\n // Define the variable that will, eventually, have the real key.\n let key;\n // If the value is a path...\n if (useIncludePath.includes(pathDelimiter)) {\n // Split all its components.\n const pathParts = useIncludePath.split(pathDelimiter);\n // Get the first component, a.k.a. the real key.\n const pathKey = pathParts.shift()!;\n /**\n * This is very important: Since the path was specified with sub components\n * (like `myProp.mySubProp`), the method won't format the key, but the sub\n * key(s)\n * (`mySubProp`).\n * The `key` is set to `''` so it will be later removed using `.filter`.\n *\n * @ignore\n */\n key = '';\n /**\n * If there's no array for the key on the \"`include` dictionary for recursive calls\",\n * create an empty one.\n */\n if (!subIncludeByKey[pathKey]) {\n subIncludeByKey[pathKey] = [];\n }\n // Save the rest of the path to be sent on the recursive call as `include`.\n subIncludeByKey[pathKey]!.push(pathParts.join(pathDelimiter));\n } else {\n // If the value wasn't a path, assume it's a key, and set it to be returned.\n key = useIncludePath;\n }\n\n return key;\n })\n // Remove any _empty keys_.\n .filter((key) => key);\n } else {\n // There's nothing on the `include` parameter, so use all the keys.\n keysToFormat = keys;\n }\n /**\n * Similar to `subIncludeByKey`, this dictionary will be used to save the `exclude` parameter\n * that will be sent for specific keys on recursive calls.\n * If `exclude` has a path like `myKey.mySubKey`, `myKey` will be transformed, but `mySubKey`\n * is saved on this dictionary (`{ myKey: ['mySubKey']}`) and when the method applies the\n * formatting to the object, if `myKey` has an object, it will make a recursive all and\n * send `['mySubKey]` as its `exclude` parameter.\n */\n const subExcludeByKey: Record<string, string[]> = {};\n // If the `include` parameter has paths/keys...\n if (exclude.length) {\n /**\n * Create a dictionary of keys that should be removed from `keysToFormat`.\n * It's easier to have them on a list and use `.filter` than actually call `.splice` for\n * every key that should be removed.\n */\n const keysToRemove: string[] = [];\n exclude.forEach((excludePath) => {\n // Normalize the path/key.\n const useExcludePath = excludePath\n .replace(cleanPathStartExpression, '')\n .replace(cleanPathEndExpression, '');\n // If the value is a path...\n if (useExcludePath.includes(pathDelimiter)) {\n // Split all its components.\n const pathParts = useExcludePath.split(pathDelimiter);\n // Get the first component, a.k.a. the real key.\n const pathKey = pathParts.shift()!;\n /**\n * If there's no array for the key on the \"`exclude` dictionary for recursive calls\",\n * create an empty one.\n */\n if (!subExcludeByKey[pathKey]) {\n subExcludeByKey[pathKey] = [];\n }\n // Save the rest of the path to be sent on the recursive call as `exclude`.\n subExcludeByKey[pathKey]!.push(pathParts.join(pathDelimiter));\n } else {\n /**\n * If the value wasn't a path, assume it's a key, turn the flag on the \"children\n * dictionary\" to `false`, to prevent recursive calls, and add the key to the list\n * of keys that will be removed from `keysToFormat`.\n * Basically: If it's a key, don't format it and don't make recursive calls for\n * it.\n *\n * @ignore\n */\n hasChildrenByKey[useExcludePath] = false;\n keysToRemove.push(useExcludePath);\n }\n });\n // Remove keys that should be excluded.\n keysToFormat = keysToFormat.filter((key) => key && !keysToRemove.includes(key));\n }\n // \"Finally\", reduce all the keys from the object and create the new one...\n return keys.reduce<Record<string, unknown>>((newObj, key) => {\n /**\n * Define the new key and value for the object property. Depending on the validations,\n * they may be replaced with formatted ones.\n */\n let newKey;\n let newValue;\n /**\n * Get the current value for the key, in case it's needed for a recursive call or just\n * to send it back because it didn't need any change.\n */\n const value = useTarget[key];\n // If the key should be formatted, apply the formatting; otherwise, keep the original.\n if (keysToFormat.includes(key)) {\n newKey = key.replace(search, replace);\n } else {\n newKey = key;\n }\n /**\n * If the paths/keys on `exclude` didn't modify the \"children dictionary\" for the key and\n * the value is another object, make a recursive call; otherwise, just use the original\n * value.\n */\n if (hasChildrenByKey[key]) {\n newValue = formatKeys({\n target: value,\n search,\n replace,\n include: subIncludeByKey[key] || [],\n exclude: subExcludeByKey[key] || [],\n pathDelimiter,\n });\n } else {\n newValue = value;\n }\n // \"Done\", return the new object with the \"new key\" and the \"new value\".\n return { ...newObj, [newKey]: newValue };\n }, {}) as T;\n};\n","import { formatKeys, type FormatKeysExtensionOptions } from './formatKeys.js';\n\n/**\n * A shorthand method for {@link formatKeys} that transforms the keys from `dash-case`\n * to `lowerCamelCase`.\n *\n * @param options The options to use.\n * @template T The type of the returned object.\n */\nexport const dashToLowerCamelKeys = <T>(options: FormatKeysExtensionOptions): T =>\n formatKeys<T>({\n ...options,\n search: /([a-z])-([a-z])/g,\n replace: (_, firstLetter, secondLetter) => {\n const newSecondLetter = secondLetter.toUpperCase();\n return `${firstLetter}${newSecondLetter}`;\n },\n });\n","import { formatKeys, type FormatKeysExtensionOptions } from './formatKeys.js';\n\n/**\n * A shorthand method for {@link formatKeys} that transforms the keys from `dash-case`\n * to `snake_case`.\n *\n * @param options The options to use.\n * @template T The type of the returned object.\n */\nexport const dashToSnakeKeys = <T>(options: FormatKeysExtensionOptions): T =>\n formatKeys<T>({\n ...options,\n search: /([a-z])-([a-z])/g,\n replace: (_, firstLetter, secondLetter) => `${firstLetter}_${secondLetter}`,\n });\n","export type GetOptions = {\n /**\n * The object from where the property will be read.\n */\n target: unknown;\n /**\n * The path to the property.\n */\n path: string;\n /**\n * The delimiter that will separate the path components.\n */\n pathDelimiter?: string;\n /**\n * Whether or not to throw an error when the path is invalid. If this is `false`,\n * the method will silently fail and return `undefined`.\n */\n failWithError?: boolean;\n};\n\n/**\n * Returns the value of an object property using a path.\n *\n * @param options The options to use.\n * @template T The type of the returned object.\n * @throws {Error} If the path is invalid and `failWithError` is set to `true`.\n * @example\n *\n * const obj = {\n * propOne: {\n * propOneSub: 'Charito!',\n * },\n * propTwo: '!!!',\n * };\n * console.log(get({ target: obj, path: 'propOne.propOneSub' }));\n * // Will output 'Charito!'\n *\n */\nfunction get<T>(options: GetOptions): T | undefined;\nfunction get<T>(options: unknown, path: string): T | undefined;\nfunction get<T>(options: GetOptions | unknown, path?: string): T | undefined {\n let useOptions: GetOptions;\n if (typeof path === 'string') {\n useOptions = {\n target: options,\n path,\n };\n } else {\n useOptions = options as GetOptions;\n }\n\n const {\n target,\n path: usePath,\n pathDelimiter = '.',\n failWithError = false,\n } = useOptions;\n const useTarget = target as Record<string, unknown>;\n const parts = usePath.split(pathDelimiter);\n const first = parts.shift()!;\n let currentElement = useTarget[first] as Record<string, unknown>;\n if (typeof currentElement === 'undefined') {\n if (failWithError) {\n throw new Error(`There's nothing on '${usePath}'`);\n }\n\n return undefined;\n }\n\n if (!parts.length) {\n return currentElement as T;\n }\n\n let currentPath = first;\n parts.some((currentPart) => {\n let breakLoop = false;\n currentPath += `${pathDelimiter}${currentPart}`;\n currentElement = currentElement[currentPart] as Record<string, unknown>;\n if (typeof currentElement === 'undefined') {\n if (failWithError) {\n throw new Error(`There's nothing on '${currentPath}'`);\n } else {\n breakLoop = true;\n }\n }\n\n return breakLoop;\n });\n\n return currentElement as T;\n}\n\nexport { get };\n","import { copy } from './copy.js';\n\n/**\n * List of paths that are forbidden to use on the `set` function, as they could lead to\n * security issues.\n *\n * @access protected\n */\nconst FORBIDDEN_PATHS = ['__proto__', 'prototype', 'constructor'];\n\nexport type SetOptions = {\n /**\n * The object where the property will be set.\n */\n target: unknown;\n /**\n * The path for the property.\n */\n path: string;\n /**\n * The value to set on the property.\n */\n value: unknown;\n /**\n * The delimiter that will separate the path components.\n */\n pathDelimiter?: string;\n /**\n * Whether or not to throw an error when the path is invalid. If this is `false`, the method\n * will silently fail and return `undefined`.\n */\n failWithError?: boolean;\n};\n/**\n * Sets a property on an object using a path. If the path doesn't exist, it will be\n * created.\n *\n * @param options The options to use.\n * @template T The type of the returned object.\n * @throws {Error} If one of the path components is for a non-object property and\n * `failWithError` is set to `true`.\n * @example\n *\n * const target = {};\n * console.log(set({ target, path: 'some.prop.path', value: 'some-value' }));\n * // Will output { some: { prop: { path: 'some-value' } } }\n *\n */\nfunction set<T = Record<string, unknown>>(options: SetOptions): T | undefined;\nfunction set<T = Record<string, unknown>>(\n options: SetOptions | unknown,\n path: string,\n value: unknown,\n): T | undefined;\nfunction set<T = Record<string, unknown>>(\n options: SetOptions | unknown,\n path?: string,\n value?: unknown,\n): T | undefined {\n let useOptions: SetOptions;\n if (typeof path === 'string') {\n useOptions = {\n target: options,\n path,\n value,\n };\n } else {\n useOptions = options as SetOptions;\n }\n\n const {\n target,\n path: usePath,\n value: useValue,\n pathDelimiter = '.',\n failWithError = false,\n } = useOptions;\n const result = copy(target) as Record<string, unknown>;\n if (!usePath.includes(pathDelimiter)) {\n if (!usePath || FORBIDDEN_PATHS.includes(usePath.toLowerCase())) {\n return undefined;\n }\n\n result[usePath] = useValue;\n return result as T;\n }\n\n const parts = usePath.split(pathDelimiter);\n const isInvalid = parts.some(\n (part) => !part || FORBIDDEN_PATHS.includes(part.toLowerCase()),\n );\n\n if (isInvalid) {\n return undefined;\n }\n\n const last = parts.pop();\n let currentElement = result;\n let currentPath = '';\n let foundInvalid = false;\n parts.forEach((part) => {\n currentPath += `${pathDelimiter}${part}`;\n const element = currentElement[part];\n const elementType = typeof element;\n if (elementType === 'undefined') {\n currentElement[part] = {};\n currentElement = currentElement[part] as Record<string, unknown>;\n } else if (elementType === 'object') {\n currentElement = currentElement[part] as Record<string, unknown>;\n } else {\n const errorPath = currentPath.substring(pathDelimiter.length);\n if (failWithError) {\n throw new Error(\n `There's already an element of type '${elementType}' on '${errorPath}'`,\n );\n } else {\n foundInvalid = true;\n }\n }\n });\n\n if (foundInvalid) return undefined;\n\n if (result && last) {\n currentElement[last] = useValue;\n }\n\n return result as T | undefined;\n}\n\nexport { set };\n","import { get } from './get.js';\nimport { set } from './set.js';\nimport { copy } from './copy.js';\n/**\n * Used in the {@link extract} function to specify a path for a property, or an \"origin path\"\n * and an \"extraction path\".\n */\nexport type extractionPath = string | Record<string, string>;\n\nexport type ExtractOptions = {\n /**\n * The object from where the property/properties will be extracted.\n */\n target: unknown;\n /**\n * This can be a single path or a list of them. And for this method, the paths are not\n * only strings but can also be an object with a single key, that would be the path to\n * where to \"do the extraction\", and the value the path on the target object.\n */\n paths: extractionPath | extractionPath[];\n /**\n * The delimiter that will separate the path components.\n */\n pathDelimiter?: string;\n /**\n * Whether or not to throw an error when the path is invalid. If this is `false`, the\n * method will silently fail an empty object.\n */\n failWithError?: boolean;\n};\n/**\n * Extracts a property or properties from an object in order to create a new one.\n *\n * @param options The options to use.\n * @template T The type of the returned object.\n * @example\n *\n * const target = {\n * name: {\n * first: 'Pilar',\n * },\n * age: 3,\n * address: {\n * planet: 'earth',\n * something: 'else',\n * },\n * };\n * console.log(\n * extract({\n * target: obj,\n * paths: [{ name: 'name.first' }, 'age', 'address.planet'],\n * }),\n * );\n * // Will output { name: 'Pilar', age: 3, address: { planet: 'earth' } }\n *\n */\nexport const extract = <T = Record<string, unknown>>(\n options: ExtractOptions,\n): T | undefined => {\n const { target, paths, pathDelimiter = '.', failWithError = false } = options;\n const copied = copy(target) as Record<string, unknown>;\n let result: Record<string, unknown> = {};\n let failed = false;\n (Array.isArray(paths) ? paths : [paths])\n .reduce<Array<{ origin: string; customDest: boolean; dest: string }>>(\n (acc, objPath) => {\n let destPath: string;\n let originPath: string;\n if (typeof objPath === 'string') {\n destPath = objPath;\n originPath = objPath;\n } else {\n const [firstKey] = Object.keys(objPath);\n destPath = firstKey!;\n originPath = objPath[destPath]!;\n }\n\n acc.push({\n origin: originPath,\n customDest: destPath.includes(pathDelimiter),\n dest: destPath,\n });\n return acc;\n },\n [],\n )\n .some((pathInfo) => {\n let breakLoop = false;\n const value = get({\n target: copied,\n path: pathInfo.origin,\n pathDelimiter,\n failWithError,\n });\n if (typeof value !== 'undefined') {\n if (pathInfo.customDest) {\n const withCustomProp = set({\n target: result,\n path: pathInfo.dest,\n value,\n pathDelimiter,\n failWithError,\n });\n if (typeof withCustomProp === 'undefined') {\n breakLoop = true;\n failed = true;\n } else {\n result = withCustomProp;\n }\n } else {\n result[pathInfo.dest] = value;\n }\n }\n\n return breakLoop;\n });\n\n if (failed) return undefined;\n return result as T;\n};\n","import { copy } from './copy.js';\nimport { merge } from './merge.js';\n\n/**\n * Checks whether a key for an array or an Object should be flattened.\n *\n * @param key The key to check inside its parent.\n * @param value The value of the key.\n */\nexport type ShouldFlattenFn = (key: string, value: unknown) => boolean;\n\nexport type FlatOptions = {\n /**\n * The object to transform.\n */\n target: unknown;\n /**\n * A custom prefix to be added before the name of the properties. This can be used on\n * custom cases and it's also used when the method calls itself in order to flatten a\n * sub object.\n */\n prefix?: string;\n /**\n * The delimiter that will separate the path components.\n */\n pathDelimiter?: string;\n /**\n * A custom function that can be used in order to tell the function whether an Object or\n * an Array property should be flatten or not.\n */\n shouldFlatten?: ShouldFlattenFn;\n};\n/**\n * Flattens an object properties into a single level dictionary.\n *\n * @param options The options to use.\n * @template T The type of the returned object.\n * @example\n *\n * const target = {\n * propOne: {\n * propOneSub: 'Charito!',\n * },\n * propTwo: '!!!',\n * };\n * console.log(flat({ target });\n * // Will output { 'propOne.propOneSub': 'Charito!', propTwo: '!!!' }\n *\n */\nexport const flat = <T = Record<string, unknown>>(options: FlatOptions): T => {\n const { target, shouldFlatten, pathDelimiter = '.', prefix = '' } = options;\n const useTarget = target as Record<string, unknown>;\n let result: Record<string, unknown> = {};\n const namePrefix = prefix ? `${prefix}${pathDelimiter}` : '';\n Object.keys(useTarget).forEach((key) => {\n const name = `${namePrefix}${key}`;\n const value = useTarget[key] as unknown;\n const valueType = typeof value;\n const isObject = valueType === 'object' && value !== null;\n if (isObject && (!shouldFlatten || shouldFlatten(key, value))) {\n result = merge(\n result,\n flat({ target: value, pathDelimiter, prefix: name, shouldFlatten }),\n );\n } else {\n result[name] = isObject ? copy(value) : value;\n }\n });\n\n return result as T;\n};\n","import { formatKeys, type FormatKeysExtensionOptions } from './formatKeys.js';\n\n/**\n * A shorthand method for {@link formatKeys} that transforms the keys from\n * `lowerCamelCase` to `dash-case`.\n *\n * @param options The options to use.\n * @template T The type of the returned object.\n */\nexport const lowerCamelToDashKeys = <T>(options: FormatKeysExtensionOptions): T =>\n formatKeys<T>({\n ...options,\n search: /([a-z])([A-Z])/g,\n replace: (_, firstLetter, secondLetter) => {\n const newSecondLetter = secondLetter.toLowerCase();\n return `${firstLetter}-${newSecondLetter}`;\n },\n });\n","import { formatKeys, type FormatKeysExtensionOptions } from './formatKeys.js';\n\n/**\n * A shorthand method for {@link formatKeys} that transforms the keys from\n * `lowerCamelCase` to `snake_case`.\n *\n * @param options The options to use.\n * @template T The type of the returned object.\n */\nexport const lowerCamelToSnakeKeys = <T>(options: FormatKeysExtensionOptions): T =>\n formatKeys<T>({\n ...options,\n search: /([a-z])([A-Z])/g,\n replace: (_, firstLetter, secondLetter) => {\n const newSecondLetter = secondLetter.toLowerCase();\n return `${firstLetter}_${newSecondLetter}`;\n },\n });\n","import { copy } from './copy.js';\nimport { get } from './get.js';\n\nexport type RemoveOptions = {\n /**\n * The object from where the property will be removed.\n */\n target: unknown;\n /**\n * The path to the property.\n */\n path: string;\n /**\n * The delimiter that will separate the path components.\n */\n pathDelimiter?: string;\n /**\n * Whether or not to throw an error when the path is invalid. If this is `false`, the\n * function will silently fail.\n */\n failWithError?: boolean;\n /**\n * If this flag is `true` and after removing the property the parent object is empty,\n * it will remove it recursively until a non empty parent object is found.\n */\n cleanEmptyProperties?: boolean;\n};\n/**\n * Deletes a property of an object using a path.\n *\n * @param options The options to use.\n * @template T The type of the returned object.\n * @example\n *\n * const target = {\n * propOne: {\n * propOneSub: 'Charito!',\n * },\n * propTwo: '!!!',\n * };\n * console.log(remove({ target, path: 'propOne.propOneSub' }));\n * // Will output { propTwo: '!!!' }\n *\n */\nfunction remove<T = unknown>(options: RemoveOptions): T | undefined;\nfunction remove<T = unknown>(options: unknown, path: string): T | undefined;\nfunction remove<T = unknown>(\n options: RemoveOptions | unknown,\n path?: string,\n): T | undefined {\n let useOptions: RemoveOptions;\n if (typeof path === 'string') {\n useOptions = {\n target: options,\n path,\n };\n } else {\n useOptions = options as RemoveOptions;\n }\n\n const {\n target,\n path: usePath,\n pathDelimiter = '.',\n cleanEmptyProperties = true,\n failWithError = false,\n } = useOptions;\n\n const parts = usePath.split(pathDelimiter);\n const last = parts.pop()!;\n const result = copy(target) as Record<string, unknown>;\n if (!parts.length) {\n delete result[last];\n return result as T;\n }\n const parentPath = parts.join(pathDelimiter);\n const parentObj = get<Record<string, unknown>>({\n target: result,\n path: parentPath,\n pathDelimiter,\n failWithError,\n });\n\n if (typeof parentObj === 'undefined') {\n return undefined;\n }\n\n delete parentObj[last];\n if (cleanEmptyProperties && !Object.keys(parentObj).length) {\n return remove({\n target: result,\n path: parentPath,\n pathDelimiter,\n failWithError,\n cleanEmptyProperties,\n }) as T;\n }\n\n return result as T;\n}\n\nexport { remove };\n","import { formatKeys, type FormatKeysExtensionOptions } from './formatKeys.js';\n\n/**\n * A shorthand method for {@link formatKeys} that transforms the keys from `snake_case` to\n * `dash-case`.\n *\n * @param options The options to use.\n * @template T The type of the returned object.\n */\nexport const snakeToDashKeys = <T>(options: FormatKeysExtensionOptions): T =>\n formatKeys<T>({\n ...options,\n search: /([a-z])_([a-z])/g,\n replace: (_, firstLetter, secondLetter) => `${firstLetter}-${secondLetter}`,\n });\n","import { formatKeys, type FormatKeysExtensionOptions } from './formatKeys.js';\n\n/**\n * A shorthand method for {@link formatKeys} that transforms the keys from `snake_case` to\n * `lowerCamelCase`.\n *\n * @param options The options to use.\n * @template T The type of the returned object.\n */\nexport const snakeToLowerCamelKeys = <T>(options: FormatKeysExtensionOptions): T =>\n formatKeys<T>({\n ...options,\n search: /([a-z])_([a-z])/g,\n replace: (_, firstLetter, secondLetter) => {\n const newSecondLetter = secondLetter.toUpperCase();\n return `${firstLetter}${newSecondLetter}`;\n },\n });\n","import { set } from './set.js';\n\nexport type UnflatOptions = {\n /**\n * The object to transform.\n */\n target: unknown;\n /**\n * The delimiter that will separate the path components.\n */\n pathDelimiter?: string;\n};\n/**\n * This method does the exact opposite from `flat`: It takes an already flatten object and\n * restores it structure.\n *\n * @param options The options to use.\n * @template T The type of the returned object.\n * @example\n *\n * const target = {\n * 'propOne.propOneSub': 'Charito!',\n * propTwo: '!!!',\n * };\n * console.log(unflat({ target }));\n * // Will output { propOne: { propOneSub: 'Charito!' }, 'propTwo': '!!!' }\n *\n */\nexport const unflat = <T = Record<string, unknown>>(options: UnflatOptions): T => {\n const { target, pathDelimiter = '.' } = options;\n const useTarget = target as Record<string, unknown>;\n return Object.keys(useTarget).reduce<Record<string, unknown>>(\n (current, key) =>\n set({ target: current, path: key, value: useTarget[key], pathDelimiter })!,\n {},\n ) as T;\n};\n"],"mappings":"AAAA,OAAOA,MAAY,SAwBZ,IAAMC,EAAQ,IAAiBC,IAA0B,CAC9D,GAAM,CAACC,CAAW,EAAID,EAChBE,EAAO,MAAM,QAAQD,CAAW,EAAI,CAAC,EAAI,CAAC,EAChD,OAAOH,EAAO,GAAMI,EAAM,GAAGF,CAAO,CACtC,ECnBO,IAAMG,EAAWC,GAAiBC,EAAMD,CAAM,ECwD9C,IAAME,EACXC,GACM,CACN,GAAM,CACJ,OAAAC,EACA,OAAAC,EACA,QAAAC,EACA,QAAAC,EAAU,CAAC,EACX,QAAAC,EAAU,CAAC,EACX,cAAAC,EAAgB,GAClB,EAAIN,EAEEO,EAAYN,EAEZO,EAAO,OAAO,KAAKP,CAAiC,EAWpDQ,EAA4C,CAAC,EACnDD,EAAK,QAASE,GAAQ,CACpB,IAAMC,EAAQJ,EAAUG,CAAG,EAC3BD,EAAiBC,CAAG,EAAI,CAAC,EACvBC,GACA,OAAOA,GAAU,UACjBA,IAAU,MACV,CAAC,MAAM,QAAQA,CAAK,GACpB,OAAO,KAAKA,CAAK,EAErB,CAAC,EAOD,IAAMC,EAAuBN,EAAc,QAAQ,2BAA4B,MAAM,EAC/EO,EAA2B,IAAI,OAAO,IAAID,CAAoB,GAAI,GAAG,EACrEE,EAAyB,IAAI,OAAO,GAAGF,CAAoB,IAAK,GAAG,EASnEG,EAA4C,CAAC,EAS/CC,EAEAZ,EAAQ,OACVY,EAAeZ,EACZ,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F,CAAC,EAED,GAAI,SAAOM,EAAc,KAKzB,OADA,OAAOA,EAAUJ,CAAI,EACjBH,GAAwB,CAAC,OAAO,KAAKO,CAAS,EAAE,OAC3Cd,EAAO,CACZ,OAAQW,EACR,KAAME,EACN,cAAAP,EACA,cAAAE,EACA,qBAAAD,CACF,CAAC,EAGII,CACT,CC1FO,IAAMK,GAAsBC,GACjCC,EAAc,CACZ,GAAGD,EACH,OAAQ,mBACR,QAAS,CAACE,EAAGC,EAAaC,IAAiB,GAAGD,CAAW,IAAIC,CAAY,EAC3E,CAAC,ECLI,IAAMC,GAA4BC,GACvCC,EAAc,CACZ,GAAGD,EACH,OAAQ,mBACR,QAAS,CAACE,EAAGC,EAAaC,IAAiB,CACzC,IAAMC,EAAkBD,EAAa,YAAY,EACjD,MAAO,GAAGD,CAAW,GAAGE,CAAe,EACzC,CACF,CAAC,ECWI,IAAMC,GAAuCC,GAA8B,CAChF,GAAM,CAAE,OAAAC,EAAQ,cAAAC,EAAgB,GAAI,EAAIF,EAClCG,EAAYF,EAClB,OAAO,OAAO,KAAKE,CAAS,EAAE,OAC5B,CAACC,EAASC,IACRC,EAAI,CAAE,OAAQF,EAAS,KAAMC,EAAK,MAAOF,EAAUE,CAAG,EAAG,cAAAH,CAAc,CAAC,EAC1E,CAAC,CACH,CACF","names":["extend","merge","targets","firstTarget","base","copy","target","merge","formatKeys","options","target","search","replace","include","exclude","pathDelimiter","useTarget","keys","hasChildrenByKey","key","value","escapedPathDelimiter","cleanPathStartExpression","cleanPathEndExpression","subIncludeByKey","keysToFormat","includePath","useIncludePath","pathParts","pathKey","subExcludeByKey","keysToRemove","excludePath","useExcludePath","newObj","newKey","newValue","dashToLowerCamelKeys","options","formatKeys","_","firstLetter","secondLetter","newSecondLetter","dashToSnakeKeys","options","formatKeys","_","firstLetter","secondLetter","get","options","path","useOptions","target","usePath","pathDelimiter","failWithError","useTarget","parts","first","currentElement","currentPath","currentPart","breakLoop","FORBIDDEN_PATHS","set","options","path","value","useOptions","target","usePath","useValue","pathDelimiter","failWithError","result","copy","parts","part","last","currentElement","currentPath","foundInvalid","elementType","errorPath","extract","options","target","paths","pathDelimiter","failWithError","copied","copy","result","failed","acc","objPath","destPath","originPath","firstKey","pathInfo","breakLoop","value","get","withCustomProp","set","flat","options","target","shouldFlatten","pathDelimiter","prefix","useTarget","result","namePrefix","key","name","value","isObject","merge","copy","lowerCamelToDashKeys","options","formatKeys","_","firstLetter","secondLetter","newSecondLetter","lowerCamelToSnakeKeys","options","formatKeys","_","firstLetter","secondLetter","newSecondLetter","remove","options","path","useOptions","target","usePath","pathDelimiter","cleanEmptyProperties","failWithError","parts","last","result","copy","parentPath","parentObj","get","snakeToDashKeys","options","formatKeys","_","firstLetter","secondLetter","snakeToLowerCamelKeys","options","formatKeys","_","firstLetter","secondLetter","newSecondLetter","unflat","options","target","pathDelimiter","useTarget","current","key","set"]}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@homer0/object-utils",
3
3
  "description": "A small collection of utility methods to work with objects.",
4
- "version": "4.0.0",
4
+ "version": "5.0.0",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "https://github.com/homer0/packages.git",
@@ -19,34 +19,46 @@
19
19
  "publishConfig": {
20
20
  "access": "public"
21
21
  },
22
+ "type": "module",
23
+ "main": "./dist/index.js",
24
+ "types": "./dist/index.d.ts",
25
+ "exports": {
26
+ ".": {
27
+ "import": "./dist/index.js",
28
+ "types": "./src/index.ts"
29
+ },
30
+ "./package.json": "./package.json"
31
+ },
22
32
  "files": [
23
- "dist/"
33
+ "dist/",
34
+ "src/"
24
35
  ],
25
36
  "dependencies": {
26
37
  "extend": "^3.0.2"
27
38
  },
28
39
  "devDependencies": {
29
- "@homer0/eslint-plugin": "13.0.0",
30
- "@homer0/tsconfig": "3.0.0",
40
+ "@homer0/eslint-plugin": "14.0.0",
41
+ "@homer0/tsconfig": "4.0.0",
31
42
  "@types/extend": "^3.0.4",
32
- "jest": "catalog:",
33
- "ts-jest": "catalog:",
43
+ "@vitest/coverage-v8": "catalog:",
44
+ "eslint": "catalog:",
34
45
  "tsup": "catalog:",
35
- "typescript": "catalog:"
46
+ "typescript": "catalog:",
47
+ "unplugin-swc": "catalog:",
48
+ "vite-tsconfig-paths": "catalog:",
49
+ "vitest": "catalog:"
36
50
  },
37
51
  "engine-strict": true,
38
52
  "engines": {
39
53
  "node": ">=20 <23"
40
54
  },
41
- "main": "./dist/index.js",
42
- "module": "./dist/esm/index.js",
43
- "types": "./dist/index.d.ts",
44
55
  "scripts": {
45
56
  "lint": "eslint .",
46
- "test": "jest -c ./.jestrc.js",
57
+ "lint:file": "eslint $@",
58
+ "test": "vitest run $@",
47
59
  "types:check": "tsc --noEmit && tsc --noEmit --project ./tests/tsconfig.json",
48
- "build": "tsup src/index.ts",
60
+ "build": "tsup",
49
61
  "prepublishOnly": "pnpm run build"
50
62
  },
51
- "gitHead": "8ebd444fb628a91cebb3cd70e22ab9f041e5ec0a"
63
+ "gitHead": "fece630639760a2ea3b9f191ff203ac33bb88a09"
52
64
  }
@@ -0,0 +1,10 @@
1
+ import { merge } from './merge.js';
2
+
3
+ /**
4
+ * Creates a deep copy of a given object.
5
+ *
6
+ * @param target The object to copy.
7
+ * @template T The type of the input object, which will be the same as the one
8
+ * returned.
9
+ */
10
+ export const copy = <T>(target: T): T => merge(target);
@@ -0,0 +1,18 @@
1
+ import { formatKeys, type FormatKeysExtensionOptions } from './formatKeys.js';
2
+
3
+ /**
4
+ * A shorthand method for {@link formatKeys} that transforms the keys from `dash-case`
5
+ * to `lowerCamelCase`.
6
+ *
7
+ * @param options The options to use.
8
+ * @template T The type of the returned object.
9
+ */
10
+ export const dashToLowerCamelKeys = <T>(options: FormatKeysExtensionOptions): T =>
11
+ formatKeys<T>({
12
+ ...options,
13
+ search: /([a-z])-([a-z])/g,
14
+ replace: (_, firstLetter, secondLetter) => {
15
+ const newSecondLetter = secondLetter.toUpperCase();
16
+ return `${firstLetter}${newSecondLetter}`;
17
+ },
18
+ });
@@ -0,0 +1,15 @@
1
+ import { formatKeys, type FormatKeysExtensionOptions } from './formatKeys.js';
2
+
3
+ /**
4
+ * A shorthand method for {@link formatKeys} that transforms the keys from `dash-case`
5
+ * to `snake_case`.
6
+ *
7
+ * @param options The options to use.
8
+ * @template T The type of the returned object.
9
+ */
10
+ export const dashToSnakeKeys = <T>(options: FormatKeysExtensionOptions): T =>
11
+ formatKeys<T>({
12
+ ...options,
13
+ search: /([a-z])-([a-z])/g,
14
+ replace: (_, firstLetter, secondLetter) => `${firstLetter}_${secondLetter}`,
15
+ });
@@ -0,0 +1,120 @@
1
+ import { get } from './get.js';
2
+ import { set } from './set.js';
3
+ import { copy } from './copy.js';
4
+ /**
5
+ * Used in the {@link extract} function to specify a path for a property, or an "origin path"
6
+ * and an "extraction path".
7
+ */
8
+ export type extractionPath = string | Record<string, string>;
9
+
10
+ export type ExtractOptions = {
11
+ /**
12
+ * The object from where the property/properties will be extracted.
13
+ */
14
+ target: unknown;
15
+ /**
16
+ * This can be a single path or a list of them. And for this method, the paths are not
17
+ * only strings but can also be an object with a single key, that would be the path to
18
+ * where to "do the extraction", and the value the path on the target object.
19
+ */
20
+ paths: extractionPath | extractionPath[];
21
+ /**
22
+ * The delimiter that will separate the path components.
23
+ */
24
+ pathDelimiter?: string;
25
+ /**
26
+ * Whether or not to throw an error when the path is invalid. If this is `false`, the
27
+ * method will silently fail an empty object.
28
+ */
29
+ failWithError?: boolean;
30
+ };
31
+ /**
32
+ * Extracts a property or properties from an object in order to create a new one.
33
+ *
34
+ * @param options The options to use.
35
+ * @template T The type of the returned object.
36
+ * @example
37
+ *
38
+ * const target = {
39
+ * name: {
40
+ * first: 'Pilar',
41
+ * },
42
+ * age: 3,
43
+ * address: {
44
+ * planet: 'earth',
45
+ * something: 'else',
46
+ * },
47
+ * };
48
+ * console.log(
49
+ * extract({
50
+ * target: obj,
51
+ * paths: [{ name: 'name.first' }, 'age', 'address.planet'],
52
+ * }),
53
+ * );
54
+ * // Will output { name: 'Pilar', age: 3, address: { planet: 'earth' } }
55
+ *
56
+ */
57
+ export const extract = <T = Record<string, unknown>>(
58
+ options: ExtractOptions,
59
+ ): T | undefined => {
60
+ const { target, paths, pathDelimiter = '.', failWithError = false } = options;
61
+ const copied = copy(target) as Record<string, unknown>;
62
+ let result: Record<string, unknown> = {};
63
+ let failed = false;
64
+ (Array.isArray(paths) ? paths : [paths])
65
+ .reduce<Array<{ origin: string; customDest: boolean; dest: string }>>(
66
+ (acc, objPath) => {
67
+ let destPath: string;
68
+ let originPath: string;
69
+ if (typeof objPath === 'string') {
70
+ destPath = objPath;
71
+ originPath = objPath;
72
+ } else {
73
+ const [firstKey] = Object.keys(objPath);
74
+ destPath = firstKey!;
75
+ originPath = objPath[destPath]!;
76
+ }
77
+
78
+ acc.push({
79
+ origin: originPath,
80
+ customDest: destPath.includes(pathDelimiter),
81
+ dest: destPath,
82
+ });
83
+ return acc;
84
+ },
85
+ [],
86
+ )
87
+ .some((pathInfo) => {
88
+ let breakLoop = false;
89
+ const value = get({
90
+ target: copied,
91
+ path: pathInfo.origin,
92
+ pathDelimiter,
93
+ failWithError,
94
+ });
95
+ if (typeof value !== 'undefined') {
96
+ if (pathInfo.customDest) {
97
+ const withCustomProp = set({
98
+ target: result,
99
+ path: pathInfo.dest,
100
+ value,
101
+ pathDelimiter,
102
+ failWithError,
103
+ });
104
+ if (typeof withCustomProp === 'undefined') {
105
+ breakLoop = true;
106
+ failed = true;
107
+ } else {
108
+ result = withCustomProp;
109
+ }
110
+ } else {
111
+ result[pathInfo.dest] = value;
112
+ }
113
+ }
114
+
115
+ return breakLoop;
116
+ });
117
+
118
+ if (failed) return undefined;
119
+ return result as T;
120
+ };
@@ -0,0 +1,71 @@
1
+ import { copy } from './copy.js';
2
+ import { merge } from './merge.js';
3
+
4
+ /**
5
+ * Checks whether a key for an array or an Object should be flattened.
6
+ *
7
+ * @param key The key to check inside its parent.
8
+ * @param value The value of the key.
9
+ */
10
+ export type ShouldFlattenFn = (key: string, value: unknown) => boolean;
11
+
12
+ export type FlatOptions = {
13
+ /**
14
+ * The object to transform.
15
+ */
16
+ target: unknown;
17
+ /**
18
+ * A custom prefix to be added before the name of the properties. This can be used on
19
+ * custom cases and it's also used when the method calls itself in order to flatten a
20
+ * sub object.
21
+ */
22
+ prefix?: string;
23
+ /**
24
+ * The delimiter that will separate the path components.
25
+ */
26
+ pathDelimiter?: string;
27
+ /**
28
+ * A custom function that can be used in order to tell the function whether an Object or
29
+ * an Array property should be flatten or not.
30
+ */
31
+ shouldFlatten?: ShouldFlattenFn;
32
+ };
33
+ /**
34
+ * Flattens an object properties into a single level dictionary.
35
+ *
36
+ * @param options The options to use.
37
+ * @template T The type of the returned object.
38
+ * @example
39
+ *
40
+ * const target = {
41
+ * propOne: {
42
+ * propOneSub: 'Charito!',
43
+ * },
44
+ * propTwo: '!!!',
45
+ * };
46
+ * console.log(flat({ target });
47
+ * // Will output { 'propOne.propOneSub': 'Charito!', propTwo: '!!!' }
48
+ *
49
+ */
50
+ export const flat = <T = Record<string, unknown>>(options: FlatOptions): T => {
51
+ const { target, shouldFlatten, pathDelimiter = '.', prefix = '' } = options;
52
+ const useTarget = target as Record<string, unknown>;
53
+ let result: Record<string, unknown> = {};
54
+ const namePrefix = prefix ? `${prefix}${pathDelimiter}` : '';
55
+ Object.keys(useTarget).forEach((key) => {
56
+ const name = `${namePrefix}${key}`;
57
+ const value = useTarget[key] as unknown;
58
+ const valueType = typeof value;
59
+ const isObject = valueType === 'object' && value !== null;
60
+ if (isObject && (!shouldFlatten || shouldFlatten(key, value))) {
61
+ result = merge(
62
+ result,
63
+ flat({ target: value, pathDelimiter, prefix: name, shouldFlatten }),
64
+ );
65
+ } else {
66
+ result[name] = isObject ? copy(value) : value;
67
+ }
68
+ });
69
+
70
+ return result as T;
71
+ };