-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathutils.ts
360 lines (325 loc) · 9.17 KB
/
utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
/* eslint-disable @typescript-eslint/ban-types */
import { flatten } from 'wild-wild-utils'
import { isMatch } from 'micromatch'
import deepmerge from 'deepmerge'
import { decode as decodeHtml, encode as encodeHtml } from 'html-entities'
import xss from 'xss'
/**
* #### Deep merge objects (without mutating the target object).
*
* @example const newObj = merge(obj1, obj2, obj3)
*
* @param {any[]} sources
* @returns any
*/
export function merge(...sources: any[]): any {
return deepmerge.all([{}, ...sources])
}
/**
* #### Deep clone object.
*
* @example const newObj = clone(sourceObj)
*
* @param {any} source
* @returns any
*/
export function clone(source: any): any {
return deepmerge({}, source)
}
/**
* #### Returns decoded text, replacing HTML special characters.
*
* @example decode('< > " ' & © ∆')
* // returns '< > " \' & © ∆'
*
* @param {string} str
* @returns string
*/
export function decode(str: string): string {
return decodeHtml(str)
}
/**
* #### Returns encoded text, version of string.
*
* @example encode('<script>alert("xss");</scr' + "ipt>")
*
* @param {string} str
* @returns string
*/
export function encode(str: string): string {
return encodeHtml(str)
}
/**
* #### Transform an object to a dotted-key/value pair.
*
* @example dotate({ data: { title: "glut" } })
* // returns { 'data.title': 'glut' }
*
* @param {any} source
* @returns any
*/
export function dotate(source: any): any {
return flatten(source, { shallowArrays: true })
}
/**
* #### Transform an object to an array of paths.
*
* @example objectToPaths({ data: { title: "glut" } })
* // returns [ 'data', 'data/title']
*
* @param {any} source
* @returns any
*/
export function objectToPaths(source: any): string[] {
const dotObject = flatten(source)
const dotPaths = Object.keys(dotObject).map((k: string) => {
return k
.split('.')
.filter((part) => {
const isDigit = Boolean(/\b(\d+)\b/gi.exec(part))
return !isDigit
})
.join('/')
})
const paths: string[] = []
const seen: Set<string> = new Set()
for (const dotPath of dotPaths) {
const parts = dotPath.split('/')
let current = ''
for (const part of parts) {
current += current === '' ? part : `/${part}`
if (!seen.has(current)) {
paths.push(current)
seen.add(current)
}
}
}
return paths
}
/**
* #### Return an object ommitting one to multiple keys.
*
* @example omit({ foo: 'foo', bar: 'bar' }, 'foo')
* // returns { foo: 'foo' }
*
* @param {any} obj
* @param {string | string[]} omitKey
* @returns any
*/
export function omit(obj: any, omitKey: string | string[]): any {
const newObj = clone(obj)
const omitKeys = !Array.isArray(omitKey) ? [omitKey] : omitKey
omitKeys.forEach(k => delete newObj?.[k])
return newObj
}
/**
* #### Returns true if specified path matches any of the glob patterns.
*
* @example isMatchingGlob('get/post/title', ['get/post{,/**}'])
*
* @param {string} path
* @param {string|string[]} globPatterns
* @returns boolean
*/
export function isMatchingGlob(path: string, globPatterns: string | string[]): boolean {
return isMatch(path, globPatterns)
}
/**
* #### Sanitize untrusted HTML to prevent XSS.
*
* @example filterXSS('<script>alert("xss");</scr' + "ipt>")
*
* @param {string} str
* @returns string
*/
export function filterXSS(str: string): string {
return xss(str)
}
/**
* #### Return true if element is Empty.
*
* @example isEmpty(prismaArgs?.data?.title)
*
* @param {any} element
* @returns boolean
*/
export function isEmpty(element: any): boolean {
return (
element === null
|| element === undefined
|| typeof element === 'undefined'
|| (typeof element === 'string' && element.trim() === '')
|| (Array.isArray(element) && element.length === 0)
|| (Object.getPrototypeOf(element) === Object.prototype && Object.keys(element).length === 0)
)
}
/**
* #### Return true if element is Undefined.
*
* @example isUndefined(prismaArgs?.data?.title)
*
* @param {any} element
* @returns boolean
*/
export function isUndefined(element: any): boolean {
return element === undefined || typeof element === 'undefined'
}
/**
* #### Return true if element is an Array
*
* @example isArray(element)
*
* @param {any} element
* @returns boolean
*/
export const isArray = (val: any): val is any[] => Array.isArray(val)
/**
* #### Return string with first letter lowercase.
*
* @example lowerFirst("PostOffice")
* // returns 'postOffice'
*
* @param {string} str
* @returns string
*/
export function lowerFirst(str: string): string {
if (str)
return str.charAt(0).toLowerCase() + str.slice(1)
else
return String()
}
/**
* #### Return string with first letter uppercase.
*
* @example upperFirst("postOffice")
* // returns 'PostOffice'
*
* @param {string} str
* @returns string
*/
export function upperFirst(str: string): string {
if (str)
return str.charAt(0).toUpperCase() + str.slice(1)
else return String()
}
/**
* #### Return true if element is an object
*
* @example isObject(element)
*
* @param {any} element
* @returns boolean
*/
export const isObject = (val: any): val is object => Object.prototype.toString.call(val) === '[object Object]'
/**
* #### Return true if element is a function
*
* @example isFunction(element)
*
* @param {any} element
* @returns boolean
*/
export const isFunction = <T extends Function>(val: any): val is T => typeof val === 'function'
/**
* Applies a mutation function to each key and value of an object recursively.
* Ensures immutability of the original object by returning a new, deeply-copied and mutated object.
*
* @param {Object} obj - Original object.
* @param {Function} fn - Async mutator function, should return an object with potentially new key-value pair.
* @return {Object} - A new mutated object.
*/
export async function walk(
jsonObj: any,
fn: (arg: { key: string; value: any }, node: WalkNode) => Promise<{ key: string; value: any }>,
) {
if (Array.isArray(jsonObj))
return await Promise.all(jsonObj.map(async value => await walkObj(value, fn)))
else if (isObject(jsonObj))
return await walkObj(jsonObj, fn)
else
return jsonObj
}
async function walkObj(
jsonObj: any,
fn: (arg: { key: string; value: any }, node: WalkNode) => Promise<{ key: string; value: any }>,
node: WalkNode = new WalkNode(),
): Promise<any> {
const cloneObj = clone(jsonObj)
const out: any = {}
const keys = Object.keys(cloneObj)
for (const key of keys) {
const newNode = new WalkNode([...node._path, key])
let { key: newKey, value: newValue } = await fn({ key, value: cloneObj[key] }, newNode)
if (newValue && isObject(newValue) && !newNode._ignoreChildren) {
newValue = await walkObj(newValue, fn, newNode)
}
else if (newValue && isArray(newValue) && !newNode._ignoreChildren) {
for (let idx = 0; idx < newValue.length; idx++) {
if (newValue[idx] && isObject(newValue[idx]))
newValue[idx] = await walkObj(newValue[idx], fn, new WalkNode([...newNode._path, idx]))
}
}
out[newKey] = newValue
}
return out
}
class WalkNode {
constructor(public _path: (string | number)[] = [], public _ignoreChildren: boolean = false) {
this._path = _path
this._ignoreChildren = _ignoreChildren
}
ignoreChilds() { this._ignoreChildren = true }
getPath() { return this._path }
}
/**
* #### Replace all from findArray with replaceArray
*
* @example replaceAll('you & me', ['you','me'], ['me','you'])
*
* @param {string} str
* @param {string[]} findArray
* @param {string[]} replaceArray
* @returns string
*/
export function replaceAll(str: string, findArray: string[], replaceArray: string[]): string {
let regex: string[] | string = []
const map = {}
for (let i = 0; i < findArray.length; i++) {
regex.push(findArray[i].replace(/([-[\]{}()*+?.\\^$|#,])/g, '\\$1'))
map[findArray[i]] = replaceArray[i]
}
regex = regex.join('|')
str = str.replace(new RegExp(regex, 'g'), (matched) => {
return map[matched]
})
return str
}
/**
* #### Creates a duplicate-free version of an array
*
* @example uniq(['a', 'b', 'a'])
*
* @param {any[]} array
* @returns any[]
*/
export function uniq<T>(array: readonly T[]): T[] {
return Array.from(new Set(array))
}
/**
* #### Creates a duplicate-free version of an array using iteratee
*
* @category Array
*/
export function uniqBy<T>(array: readonly T[], iteratee: keyof T | ((a: any) => any)): T[] {
return array.reduce((acc: T[], cur: any) => {
const computed = isFunction(iteratee)
const index = acc.findIndex((item: any) =>
computed
? iteratee(item) === iteratee(cur)
: typeof cur?.[iteratee] !== 'undefined' && item?.[iteratee] === cur?.[iteratee],
)
if (index === -1)
acc.push(cur)
return acc
}, [])
}