@alfalab/utils
Advanced tools
Comparing version 1.12.1 to 1.13.0
@@ -6,2 +6,18 @@ # Change Log | ||
# [1.13.0](http://git.moscow.alfaintra.net/ef/utils/compare/@alfalab/utils@1.12.0...@alfalab/utils@1.13.0) (2022-08-30) | ||
### Bug Fixes | ||
* **packages/utils:** added export for keyboard-switcher ([59e0c71](http://git.moscow.alfaintra.net/ef/utils/commits/59e0c71f60069deb6008810282a8260999f7560a)) | ||
### Features | ||
* **packages/utils:** added transform-data ([63aafb3](http://git.moscow.alfaintra.net/ef/utils/commits/63aafb352c9e04f20b6eae1c2ca4624ddf90f411)) | ||
# [1.8.0](https://github.com/alfa-laboratory/utils/compare/@alfalab/utils@1.7.0...@alfalab/utils@1.8.0) (2022-01-31) | ||
@@ -8,0 +24,0 @@ |
import { currency, countries } from '@alfalab/data'; | ||
import isPlainObject from 'lodash/isPlainObject'; | ||
import transform from 'lodash/transform'; | ||
import { chain } from 'stream-chain'; | ||
import { parser } from 'stream-json'; | ||
import { filter } from 'stream-json/filters/Filter'; | ||
import { replace } from 'stream-json/filters/Replace'; | ||
import { stringer } from 'stream-json/Stringer'; | ||
@@ -433,2 +440,148 @@ /** | ||
export { AMOUNT_MAJOR_MINOR_PARTS_SEPARATOR, NEGATIVE_SYMBOLS, THINSP, cropAccountNumber, formatAccount, formatAmount, formatFileSize, formatToRussian, getAllCurrencyCodes, getCountries, getCountriesHash, getCurrencySymbol, hasScrolledToBottomOfPage, isKeyboardLayout, isOverflown, isValidCardNumber, isValidEmail, keyboardLanguages, keyboardSwitcher, keyboardsLayouts, phoneNumber, pluralize, secondsToTime, splitAmount, switchToKeyboard }; | ||
/*! ***************************************************************************** | ||
Copyright (c) Microsoft Corporation. | ||
Permission to use, copy, modify, and/or distribute this software for any | ||
purpose with or without fee is hereby granted. | ||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH | ||
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY | ||
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, | ||
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM | ||
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR | ||
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR | ||
PERFORMANCE OF THIS SOFTWARE. | ||
***************************************************************************** */ | ||
var __assign = function() { | ||
__assign = Object.assign || function __assign(t) { | ||
for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
s = arguments[i]; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; | ||
} | ||
return t; | ||
}; | ||
return __assign.apply(this, arguments); | ||
}; | ||
function __spreadArray(to, from) { | ||
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) | ||
to[j] = from[i]; | ||
return to; | ||
} | ||
var NUMBER_REGEX = /^\d+$/; | ||
var SKIP_NODE_NAMES = ['', null, undefined]; | ||
var nodeNamesToPath = function (nodeNames) { | ||
return nodeNames.reduce(function (pathAcc, nodeName) { | ||
if (!SKIP_NODE_NAMES.includes(nodeName)) { | ||
if (nodeName === '*' || NUMBER_REGEX.test("" + nodeName)) { | ||
pathAcc += '[*]'; | ||
} | ||
else { | ||
if (pathAcc) { | ||
pathAcc += '.'; | ||
} | ||
pathAcc += nodeName; | ||
} | ||
} | ||
return pathAcc; | ||
}, ''); | ||
}; | ||
var INVALID_FILTER_CONFIG_VALUES = ['', null, undefined, true, false]; | ||
var VALID_REPLACE_CONFIG_TYPES = ['string', 'number', 'boolean', 'function']; | ||
var isReplacer = function (replacer) { | ||
return replacer === null || VALID_REPLACE_CONFIG_TYPES.includes(typeof replacer); | ||
}; | ||
var prepareConfig = function (_a) { | ||
var _b = _a.replace, replaceConfig = _b === void 0 ? {} : _b, _c = _a.filter, filterConfig = _c === void 0 ? [] : _c; | ||
var filteredReplaceConfig = Object.keys(replaceConfig).reduce(function (res, replaceConfigKey) { | ||
var replacer = replaceConfig[replaceConfigKey]; | ||
if (isReplacer(replacer)) { | ||
res[replaceConfigKey] = replacer; | ||
} | ||
return res; | ||
}, {}); | ||
var filteredFilterConfigObject = filterConfig.reduce(function (res, path) { | ||
var _a; | ||
if (INVALID_FILTER_CONFIG_VALUES.includes(path)) { | ||
return res; | ||
} | ||
return __assign(__assign({}, res), (_a = {}, _a[path] = true, _a)); | ||
}, {}); | ||
var paths = __spreadArray(__spreadArray([], Object.keys(filteredFilterConfigObject)), Object.keys(filteredReplaceConfig)); | ||
if (paths.length) { | ||
return { | ||
replaceConfig: filteredReplaceConfig, | ||
filterConfig: filteredFilterConfigObject, | ||
}; | ||
} | ||
throw new TypeError('required replace or filter in transformConfig'); | ||
}; | ||
var getReplaceValue = function (value, replacer) { | ||
if (isReplacer(replacer)) { | ||
return typeof replacer === 'function' ? replacer(value) : replacer; | ||
} | ||
return value; | ||
}; | ||
/** | ||
* Преобразование стрима (json) на основе конфига | ||
* | ||
* @param config {TransformConfig} конфиг с функциями преобразования и путей для фильтра | ||
*/ | ||
function createTransformDataStream(config) { | ||
var _a = prepareConfig(config), replaceConfig = _a.replaceConfig, filterConfig = _a.filterConfig; | ||
return chain([ | ||
parser(), | ||
filter({ filter: function (nodeNames) { return !filterConfig[nodeNamesToPath(nodeNames)]; } }), | ||
replace({ | ||
filter: function (nodeNames, _a) { | ||
var name = _a.name; | ||
return isReplacer(replaceConfig[nodeNamesToPath(nodeNames)]) && name.includes('Value'); | ||
}, | ||
replacement: function (nodeNames, _a) { | ||
var name = _a.name, value = _a.value; | ||
var newValue = getReplaceValue(value, replaceConfig[nodeNamesToPath(nodeNames)]); | ||
return [ | ||
{ name: name, value: typeof newValue === 'number' ? newValue.toString() : newValue }, | ||
]; | ||
}, | ||
}), | ||
stringer({ useValues: true }), | ||
]); | ||
} | ||
// eslint-disable-next-line @typescript-eslint/naming-convention, no-underscore-dangle | ||
var _transformData = function (data, _a, parentPath) { | ||
var filterConfig = _a.filterConfig, replaceConfig = _a.replaceConfig; | ||
if (parentPath === void 0) { parentPath = ''; } | ||
return transform(data, function (result, value, key) { | ||
var currentPath = nodeNamesToPath([parentPath, key]); | ||
// Recurse into arrays and objects. | ||
if (Array.isArray(value) || isPlainObject(value)) { | ||
value = _transformData(value, { | ||
filterConfig: filterConfig, | ||
replaceConfig: replaceConfig, | ||
}, currentPath); | ||
} | ||
if (filterConfig[currentPath]) { | ||
return; | ||
} | ||
var newValue = getReplaceValue(value, replaceConfig[currentPath]); | ||
if (Array.isArray(result)) { | ||
result.push(newValue); | ||
return; | ||
} | ||
result[key] = newValue; | ||
}); | ||
}; | ||
/** | ||
* Преобразование полей объекта на основе конфига | ||
* | ||
* @param data {Object|Array} данные для преобразования | ||
* @param config {TransformConfig} конфиг с функциями преобразования и путей для фильтра | ||
*/ | ||
var transformData = function (data, config) { | ||
return _transformData(data, prepareConfig(config)); | ||
}; | ||
export { AMOUNT_MAJOR_MINOR_PARTS_SEPARATOR, NEGATIVE_SYMBOLS, THINSP, createTransformDataStream, cropAccountNumber, formatAccount, formatAmount, formatFileSize, formatToRussian, getAllCurrencyCodes, getCountries, getCountriesHash, getCurrencySymbol, hasScrolledToBottomOfPage, isKeyboardLayout, isOverflown, isValidCardNumber, isValidEmail, keyboardLanguages, keyboardSwitcher, keyboardsLayouts, phoneNumber, pluralize, secondsToTime, splitAmount, switchToKeyboard, transformData }; |
@@ -286,3 +286,23 @@ // Generated by dts-bundle-generator v5.8.0 | ||
export declare function hasScrolledToBottomOfPage(): boolean; | ||
export declare type Data = Record<string, unknown> | unknown[]; | ||
export declare type ReplaceValue = string | number | boolean | null; | ||
export declare type Replacer = ((value: unknown) => ReplaceValue) | ReplaceValue; | ||
export declare type TransformConfig = { | ||
replace?: Record<string, Replacer>; | ||
filter?: string[]; | ||
}; | ||
/** | ||
* Преобразование стрима (json) на основе конфига | ||
* | ||
* @param config {TransformConfig} конфиг с функциями преобразования и путей для фильтра | ||
*/ | ||
export declare function createTransformDataStream(config: TransformConfig): import("stream-chain"); | ||
/** | ||
* Преобразование полей объекта на основе конфига | ||
* | ||
* @param data {Object|Array} данные для преобразования | ||
* @param config {TransformConfig} конфиг с функциями преобразования и путей для фильтра | ||
*/ | ||
export declare const transformData: (data: Data, config: TransformConfig) => Data; | ||
export {}; |
@@ -6,3 +6,15 @@ 'use strict'; | ||
var data = require('@alfalab/data'); | ||
var isPlainObject = require('lodash/isPlainObject'); | ||
var transform = require('lodash/transform'); | ||
var streamChain = require('stream-chain'); | ||
var streamJson = require('stream-json'); | ||
var Filter = require('stream-json/filters/Filter'); | ||
var Replace = require('stream-json/filters/Replace'); | ||
var Stringer = require('stream-json/Stringer'); | ||
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } | ||
var isPlainObject__default = /*#__PURE__*/_interopDefaultLegacy(isPlainObject); | ||
var transform__default = /*#__PURE__*/_interopDefaultLegacy(transform); | ||
/** | ||
@@ -438,5 +450,152 @@ * Возвращает 4 последние цифры номера счёта в формате `··XXXX` | ||
/*! ***************************************************************************** | ||
Copyright (c) Microsoft Corporation. | ||
Permission to use, copy, modify, and/or distribute this software for any | ||
purpose with or without fee is hereby granted. | ||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH | ||
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY | ||
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, | ||
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM | ||
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR | ||
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR | ||
PERFORMANCE OF THIS SOFTWARE. | ||
***************************************************************************** */ | ||
var __assign = function() { | ||
__assign = Object.assign || function __assign(t) { | ||
for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
s = arguments[i]; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; | ||
} | ||
return t; | ||
}; | ||
return __assign.apply(this, arguments); | ||
}; | ||
function __spreadArray(to, from) { | ||
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) | ||
to[j] = from[i]; | ||
return to; | ||
} | ||
var NUMBER_REGEX = /^\d+$/; | ||
var SKIP_NODE_NAMES = ['', null, undefined]; | ||
var nodeNamesToPath = function (nodeNames) { | ||
return nodeNames.reduce(function (pathAcc, nodeName) { | ||
if (!SKIP_NODE_NAMES.includes(nodeName)) { | ||
if (nodeName === '*' || NUMBER_REGEX.test("" + nodeName)) { | ||
pathAcc += '[*]'; | ||
} | ||
else { | ||
if (pathAcc) { | ||
pathAcc += '.'; | ||
} | ||
pathAcc += nodeName; | ||
} | ||
} | ||
return pathAcc; | ||
}, ''); | ||
}; | ||
var INVALID_FILTER_CONFIG_VALUES = ['', null, undefined, true, false]; | ||
var VALID_REPLACE_CONFIG_TYPES = ['string', 'number', 'boolean', 'function']; | ||
var isReplacer = function (replacer) { | ||
return replacer === null || VALID_REPLACE_CONFIG_TYPES.includes(typeof replacer); | ||
}; | ||
var prepareConfig = function (_a) { | ||
var _b = _a.replace, replaceConfig = _b === void 0 ? {} : _b, _c = _a.filter, filterConfig = _c === void 0 ? [] : _c; | ||
var filteredReplaceConfig = Object.keys(replaceConfig).reduce(function (res, replaceConfigKey) { | ||
var replacer = replaceConfig[replaceConfigKey]; | ||
if (isReplacer(replacer)) { | ||
res[replaceConfigKey] = replacer; | ||
} | ||
return res; | ||
}, {}); | ||
var filteredFilterConfigObject = filterConfig.reduce(function (res, path) { | ||
var _a; | ||
if (INVALID_FILTER_CONFIG_VALUES.includes(path)) { | ||
return res; | ||
} | ||
return __assign(__assign({}, res), (_a = {}, _a[path] = true, _a)); | ||
}, {}); | ||
var paths = __spreadArray(__spreadArray([], Object.keys(filteredFilterConfigObject)), Object.keys(filteredReplaceConfig)); | ||
if (paths.length) { | ||
return { | ||
replaceConfig: filteredReplaceConfig, | ||
filterConfig: filteredFilterConfigObject, | ||
}; | ||
} | ||
throw new TypeError('required replace or filter in transformConfig'); | ||
}; | ||
var getReplaceValue = function (value, replacer) { | ||
if (isReplacer(replacer)) { | ||
return typeof replacer === 'function' ? replacer(value) : replacer; | ||
} | ||
return value; | ||
}; | ||
/** | ||
* Преобразование стрима (json) на основе конфига | ||
* | ||
* @param config {TransformConfig} конфиг с функциями преобразования и путей для фильтра | ||
*/ | ||
function createTransformDataStream(config) { | ||
var _a = prepareConfig(config), replaceConfig = _a.replaceConfig, filterConfig = _a.filterConfig; | ||
return streamChain.chain([ | ||
streamJson.parser(), | ||
Filter.filter({ filter: function (nodeNames) { return !filterConfig[nodeNamesToPath(nodeNames)]; } }), | ||
Replace.replace({ | ||
filter: function (nodeNames, _a) { | ||
var name = _a.name; | ||
return isReplacer(replaceConfig[nodeNamesToPath(nodeNames)]) && name.includes('Value'); | ||
}, | ||
replacement: function (nodeNames, _a) { | ||
var name = _a.name, value = _a.value; | ||
var newValue = getReplaceValue(value, replaceConfig[nodeNamesToPath(nodeNames)]); | ||
return [ | ||
{ name: name, value: typeof newValue === 'number' ? newValue.toString() : newValue }, | ||
]; | ||
}, | ||
}), | ||
Stringer.stringer({ useValues: true }), | ||
]); | ||
} | ||
// eslint-disable-next-line @typescript-eslint/naming-convention, no-underscore-dangle | ||
var _transformData = function (data, _a, parentPath) { | ||
var filterConfig = _a.filterConfig, replaceConfig = _a.replaceConfig; | ||
if (parentPath === void 0) { parentPath = ''; } | ||
return transform__default["default"](data, function (result, value, key) { | ||
var currentPath = nodeNamesToPath([parentPath, key]); | ||
// Recurse into arrays and objects. | ||
if (Array.isArray(value) || isPlainObject__default["default"](value)) { | ||
value = _transformData(value, { | ||
filterConfig: filterConfig, | ||
replaceConfig: replaceConfig, | ||
}, currentPath); | ||
} | ||
if (filterConfig[currentPath]) { | ||
return; | ||
} | ||
var newValue = getReplaceValue(value, replaceConfig[currentPath]); | ||
if (Array.isArray(result)) { | ||
result.push(newValue); | ||
return; | ||
} | ||
result[key] = newValue; | ||
}); | ||
}; | ||
/** | ||
* Преобразование полей объекта на основе конфига | ||
* | ||
* @param data {Object|Array} данные для преобразования | ||
* @param config {TransformConfig} конфиг с функциями преобразования и путей для фильтра | ||
*/ | ||
var transformData = function (data, config) { | ||
return _transformData(data, prepareConfig(config)); | ||
}; | ||
exports.AMOUNT_MAJOR_MINOR_PARTS_SEPARATOR = AMOUNT_MAJOR_MINOR_PARTS_SEPARATOR; | ||
exports.NEGATIVE_SYMBOLS = NEGATIVE_SYMBOLS; | ||
exports.THINSP = THINSP; | ||
exports.createTransformDataStream = createTransformDataStream; | ||
exports.cropAccountNumber = cropAccountNumber; | ||
@@ -464,1 +623,2 @@ exports.formatAccount = formatAccount; | ||
exports.switchToKeyboard = switchToKeyboard; | ||
exports.transformData = transformData; |
{ | ||
"name": "@alfalab/utils", | ||
"version": "1.12.1", | ||
"version": "1.13.0", | ||
"description": "common utils", | ||
@@ -21,7 +21,11 @@ "sideEffects": false, | ||
"dependencies": { | ||
"@alfalab/data": "^1.2.3", | ||
"fast-redact": "^3.1.1" | ||
"@alfalab/data": "^1.3.0", | ||
"lodash": "4.17.21", | ||
"stream-chain": "2.2.5", | ||
"stream-json": "1.7.4" | ||
}, | ||
"devDependencies": { | ||
"@types/fast-redact": "3.0.1", | ||
"@types/lodash": "4.14.182", | ||
"@types/stream-chain": "2.0.1", | ||
"@types/stream-json": "1.7.2", | ||
"dts-bundle-generator": "^5.6.0", | ||
@@ -33,3 +37,3 @@ "rollup": "^2.38.0" | ||
}, | ||
"gitHead": "48d4f72e58a64556366fca17487f691ee4e3c768" | ||
"gitHead": "025070528b7ed7fe246c1a2842f2c917b771dff9" | ||
} |
@@ -46,6 +46,2 @@ <div align="center"> | ||
### [format-data](http://git.moscow.alfaintra.net/projects/EF/repos/utils/browse/packages/utils/src/format-data/util.ts) | ||
- `formatData` — Форматирует значение в объекте на основе конфига.<br />`formatData({ phones: ['+123','+234'] }, { phones[*]: (value)=> value.slice(1) }) -> { phones: ['123','234'] }` | ||
### [get-all-currency-codes](http://git.moscow.alfaintra.net/projects/EF/repos/utils/browse/packages/utils/src/get-all-currency-codes/util.ts) | ||
@@ -95,2 +91,7 @@ | ||
- `keyboardSwitcher` — Конвертирует символы из одной раскладки в другую. | ||
- `isKeyboardLayout` — Проверяет строку на совпадение с раскладкой клавиатуры. | ||
- `isKeyboardLayout` — Проверяет строку на совпадение с раскладкой клавиатуры. | ||
### [transform-data](http://git.moscow.alfaintra.net/projects/EF/repos/utils/browse/packages/utils/src/transform-data/util.ts) | ||
- `transformData` — Форматирует измененный объектом на основе конфига.<br />`formatData({ phones: ['+123','+234'], meta: 'info' }, { replace: { phones[*]: (value)=> value.slice(1) }, filter: ['meta'] }) -> { phones: ['123','234'] }` | ||
- `createTransformDataStream` — Форматирует стрим с измененным объектом на основе конфига.<br />`pipeline[Readable.from(JSON.stringify({ phones: ['+123','+234'], meta: 'info' })), createTransformDataStream({ replace: { phones[*]: (value)=> value.slice(1) })], filter: ['meta'] })] -> Stream<{ phones: ['123','234'] }>` |
New author
Supply chain riskA new npm collaborator published a version of the package for the first time. New collaborators are usually benign additions to a project, but do indicate a change to the security surface area of a package.
Found 1 instance in 1 package
65664
1456
95
0
4
5
+ Addedlodash@4.17.21
+ Addedstream-chain@2.2.5
+ Addedstream-json@1.7.4
+ Addedlodash@4.17.21(transitive)
+ Addedstream-chain@2.2.5(transitive)
+ Addedstream-json@1.7.4(transitive)
- Removedfast-redact@^3.1.1
- Removedfast-redact@3.5.0(transitive)
Updated@alfalab/data@^1.3.0