@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 CHANGED
@@ -1,472 +1,2 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/index.ts
31
- var index_exports = {};
32
- __export(index_exports, {
33
- copy: () => copy,
34
- dashToLowerCamelKeys: () => dashToLowerCamelKeys,
35
- dashToSnakeKeys: () => dashToSnakeKeys,
36
- extract: () => extract,
37
- flat: () => flat,
38
- formatKeys: () => formatKeys,
39
- get: () => get,
40
- lowerCamelToDashKeys: () => lowerCamelToDashKeys,
41
- lowerCamelToSnakeKeys: () => lowerCamelToSnakeKeys,
42
- merge: () => merge,
43
- remove: () => remove,
44
- set: () => set,
45
- snakeToDashKeys: () => snakeToDashKeys,
46
- snakeToLowerCamelKeys: () => snakeToLowerCamelKeys,
47
- unflat: () => unflat
48
- });
49
- module.exports = __toCommonJS(index_exports);
50
-
51
- // src/fns/merge.ts
52
- var import_extend = __toESM(require("extend"));
53
- var merge = (...targets) => {
54
- const [firstTarget] = targets;
55
- const base = Array.isArray(firstTarget) ? [] : {};
56
- return (0, import_extend.default)(true, base, ...targets);
57
- };
58
-
59
- // src/fns/copy.ts
60
- var copy = (target) => merge(target);
61
-
62
- // src/fns/formatKeys.ts
63
- var formatKeys = (options) => {
64
- const {
65
- target,
66
- search,
67
- replace,
68
- include = [],
69
- exclude = [],
70
- pathDelimiter = "."
71
- } = options;
72
- const useTarget = target;
73
- const keys = Object.keys(target);
74
- const hasChildrenByKey = {};
75
- keys.forEach((key) => {
76
- const value = useTarget[key];
77
- hasChildrenByKey[key] = !!(value && typeof value === "object" && value !== null && !Array.isArray(value) && Object.keys(value));
78
- });
79
- const escapedPathDelimiter = pathDelimiter.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
80
- const cleanPathStartExpression = new RegExp(`^${escapedPathDelimiter}`, "i");
81
- const cleanPathEndExpression = new RegExp(`${escapedPathDelimiter}$`, "i");
82
- const subIncludeByKey = {};
83
- let keysToFormat;
84
- if (include.length) {
85
- keysToFormat = include.map((includePath) => {
86
- const useIncludePath = includePath.replace(cleanPathStartExpression, "").replace(cleanPathEndExpression, "");
87
- let key;
88
- if (useIncludePath.includes(pathDelimiter)) {
89
- const pathParts = useIncludePath.split(pathDelimiter);
90
- const pathKey = pathParts.shift();
91
- key = "";
92
- if (!subIncludeByKey[pathKey]) {
93
- subIncludeByKey[pathKey] = [];
94
- }
95
- subIncludeByKey[pathKey].push(pathParts.join(pathDelimiter));
96
- } else {
97
- key = useIncludePath;
98
- }
99
- return key;
100
- }).filter((key) => key);
101
- } else {
102
- keysToFormat = keys;
103
- }
104
- const subExcludeByKey = {};
105
- if (exclude.length) {
106
- const keysToRemove = [];
107
- exclude.forEach((excludePath) => {
108
- const useExcludePath = excludePath.replace(cleanPathStartExpression, "").replace(cleanPathEndExpression, "");
109
- if (useExcludePath.includes(pathDelimiter)) {
110
- const pathParts = useExcludePath.split(pathDelimiter);
111
- const pathKey = pathParts.shift();
112
- if (!subExcludeByKey[pathKey]) {
113
- subExcludeByKey[pathKey] = [];
114
- }
115
- subExcludeByKey[pathKey].push(pathParts.join(pathDelimiter));
116
- } else {
117
- hasChildrenByKey[useExcludePath] = false;
118
- keysToRemove.push(useExcludePath);
119
- }
120
- });
121
- keysToFormat = keysToFormat.filter((key) => key && !keysToRemove.includes(key));
122
- }
123
- return keys.reduce((newObj, key) => {
124
- let newKey;
125
- let newValue;
126
- const value = useTarget[key];
127
- if (keysToFormat.includes(key)) {
128
- newKey = key.replace(search, replace);
129
- } else {
130
- newKey = key;
131
- }
132
- if (hasChildrenByKey[key]) {
133
- newValue = formatKeys({
134
- target: value,
135
- search,
136
- replace,
137
- include: subIncludeByKey[key] || [],
138
- exclude: subExcludeByKey[key] || [],
139
- pathDelimiter
140
- });
141
- } else {
142
- newValue = value;
143
- }
144
- return { ...newObj, [newKey]: newValue };
145
- }, {});
146
- };
147
-
148
- // src/fns/dashToLowerCamelKeys.ts
149
- var dashToLowerCamelKeys = (options) => formatKeys({
150
- ...options,
151
- search: /([a-z])-([a-z])/g,
152
- replace: (_, firstLetter, secondLetter) => {
153
- const newSecondLetter = secondLetter.toUpperCase();
154
- return `${firstLetter}${newSecondLetter}`;
155
- }
156
- });
157
-
158
- // src/fns/dashToSnakeKeys.ts
159
- var dashToSnakeKeys = (options) => formatKeys({
160
- ...options,
161
- search: /([a-z])-([a-z])/g,
162
- replace: (_, firstLetter, secondLetter) => `${firstLetter}_${secondLetter}`
163
- });
164
-
165
- // src/fns/get.ts
166
- function get(options, path) {
167
- let useOptions;
168
- if (typeof path === "string") {
169
- useOptions = {
170
- target: options,
171
- path
172
- };
173
- } else {
174
- useOptions = options;
175
- }
176
- const {
177
- target,
178
- path: usePath,
179
- pathDelimiter = ".",
180
- failWithError = false
181
- } = useOptions;
182
- const useTarget = target;
183
- const parts = usePath.split(pathDelimiter);
184
- const first = parts.shift();
185
- let currentElement = useTarget[first];
186
- if (typeof currentElement === "undefined") {
187
- if (failWithError) {
188
- throw new Error(`There's nothing on '${usePath}'`);
189
- }
190
- return void 0;
191
- }
192
- if (!parts.length) {
193
- return currentElement;
194
- }
195
- let currentPath = first;
196
- parts.some((currentPart) => {
197
- let breakLoop = false;
198
- currentPath += `${pathDelimiter}${currentPart}`;
199
- currentElement = currentElement[currentPart];
200
- if (typeof currentElement === "undefined") {
201
- if (failWithError) {
202
- throw new Error(`There's nothing on '${currentPath}'`);
203
- } else {
204
- breakLoop = true;
205
- }
206
- }
207
- return breakLoop;
208
- });
209
- return currentElement;
210
- }
211
-
212
- // src/fns/set.ts
213
- var FORBIDDEN_PATHS = ["__proto__", "prototype", "constructor"];
214
- function set(options, path, value) {
215
- let useOptions;
216
- if (typeof path === "string") {
217
- useOptions = {
218
- target: options,
219
- path,
220
- value
221
- };
222
- } else {
223
- useOptions = options;
224
- }
225
- const {
226
- target,
227
- path: usePath,
228
- value: useValue,
229
- pathDelimiter = ".",
230
- failWithError = false
231
- } = useOptions;
232
- const result = copy(target);
233
- if (!usePath.includes(pathDelimiter)) {
234
- if (!usePath || FORBIDDEN_PATHS.includes(usePath.toLowerCase())) {
235
- return void 0;
236
- }
237
- result[usePath] = useValue;
238
- return result;
239
- }
240
- const parts = usePath.split(pathDelimiter);
241
- const isInvalid = parts.some(
242
- (part) => !part || FORBIDDEN_PATHS.includes(part.toLowerCase())
243
- );
244
- if (isInvalid) {
245
- return void 0;
246
- }
247
- const last = parts.pop();
248
- let currentElement = result;
249
- let currentPath = "";
250
- let foundInvalid = false;
251
- parts.forEach((part) => {
252
- currentPath += `${pathDelimiter}${part}`;
253
- const element = currentElement[part];
254
- const elementType = typeof element;
255
- if (elementType === "undefined") {
256
- currentElement[part] = {};
257
- currentElement = currentElement[part];
258
- } else if (elementType === "object") {
259
- currentElement = currentElement[part];
260
- } else {
261
- const errorPath = currentPath.substring(pathDelimiter.length);
262
- if (failWithError) {
263
- throw new Error(
264
- `There's already an element of type '${elementType}' on '${errorPath}'`
265
- );
266
- } else {
267
- foundInvalid = true;
268
- }
269
- }
270
- });
271
- if (foundInvalid) return void 0;
272
- if (result && last) {
273
- currentElement[last] = useValue;
274
- }
275
- return result;
276
- }
277
-
278
- // src/fns/extract.ts
279
- var extract = (options) => {
280
- const { target, paths, pathDelimiter = ".", failWithError = false } = options;
281
- const copied = copy(target);
282
- let result = {};
283
- let failed = false;
284
- (Array.isArray(paths) ? paths : [paths]).reduce(
285
- (acc, objPath) => {
286
- let destPath;
287
- let originPath;
288
- if (typeof objPath === "string") {
289
- destPath = objPath;
290
- originPath = objPath;
291
- } else {
292
- const [firstKey] = Object.keys(objPath);
293
- destPath = firstKey;
294
- originPath = objPath[destPath];
295
- }
296
- acc.push({
297
- origin: originPath,
298
- customDest: destPath.includes(pathDelimiter),
299
- dest: destPath
300
- });
301
- return acc;
302
- },
303
- []
304
- ).some((pathInfo) => {
305
- let breakLoop = false;
306
- const value = get({
307
- target: copied,
308
- path: pathInfo.origin,
309
- pathDelimiter,
310
- failWithError
311
- });
312
- if (typeof value !== "undefined") {
313
- if (pathInfo.customDest) {
314
- const withCustomProp = set({
315
- target: result,
316
- path: pathInfo.dest,
317
- value,
318
- pathDelimiter,
319
- failWithError
320
- });
321
- if (typeof withCustomProp === "undefined") {
322
- breakLoop = true;
323
- failed = true;
324
- } else {
325
- result = withCustomProp;
326
- }
327
- } else {
328
- result[pathInfo.dest] = value;
329
- }
330
- }
331
- return breakLoop;
332
- });
333
- if (failed) return void 0;
334
- return result;
335
- };
336
-
337
- // src/fns/flat.ts
338
- var flat = (options) => {
339
- const { target, shouldFlatten, pathDelimiter = ".", prefix = "" } = options;
340
- const useTarget = target;
341
- let result = {};
342
- const namePrefix = prefix ? `${prefix}${pathDelimiter}` : "";
343
- Object.keys(useTarget).forEach((key) => {
344
- const name = `${namePrefix}${key}`;
345
- const value = useTarget[key];
346
- const valueType = typeof value;
347
- const isObject = valueType === "object" && value !== null;
348
- if (isObject && (!shouldFlatten || shouldFlatten(key, value))) {
349
- result = merge(
350
- result,
351
- flat({ target: value, pathDelimiter, prefix: name, shouldFlatten })
352
- );
353
- } else {
354
- result[name] = isObject ? copy(value) : value;
355
- }
356
- });
357
- return result;
358
- };
359
-
360
- // src/fns/lowerCamelToDashKeys.ts
361
- var lowerCamelToDashKeys = (options) => formatKeys({
362
- ...options,
363
- search: /([a-z])([A-Z])/g,
364
- replace: (_, firstLetter, secondLetter) => {
365
- const newSecondLetter = secondLetter.toLowerCase();
366
- return `${firstLetter}-${newSecondLetter}`;
367
- }
368
- });
369
-
370
- // src/fns/lowerCamelToSnakeKeys.ts
371
- var lowerCamelToSnakeKeys = (options) => formatKeys({
372
- ...options,
373
- search: /([a-z])([A-Z])/g,
374
- replace: (_, firstLetter, secondLetter) => {
375
- const newSecondLetter = secondLetter.toLowerCase();
376
- return `${firstLetter}_${newSecondLetter}`;
377
- }
378
- });
379
-
380
- // src/fns/remove.ts
381
- function remove(options, path) {
382
- let useOptions;
383
- if (typeof path === "string") {
384
- useOptions = {
385
- target: options,
386
- path
387
- };
388
- } else {
389
- useOptions = options;
390
- }
391
- const {
392
- target,
393
- path: usePath,
394
- pathDelimiter = ".",
395
- cleanEmptyProperties = true,
396
- failWithError = false
397
- } = useOptions;
398
- const parts = usePath.split(pathDelimiter);
399
- const last = parts.pop();
400
- const result = copy(target);
401
- if (!parts.length) {
402
- delete result[last];
403
- return result;
404
- }
405
- const parentPath = parts.join(pathDelimiter);
406
- const parentObj = get({
407
- target: result,
408
- path: parentPath,
409
- pathDelimiter,
410
- failWithError
411
- });
412
- if (typeof parentObj === "undefined") {
413
- return void 0;
414
- }
415
- delete parentObj[last];
416
- if (cleanEmptyProperties && !Object.keys(parentObj).length) {
417
- return remove({
418
- target: result,
419
- path: parentPath,
420
- pathDelimiter,
421
- failWithError,
422
- cleanEmptyProperties
423
- });
424
- }
425
- return result;
426
- }
427
-
428
- // src/fns/snakeToDashKeys.ts
429
- var snakeToDashKeys = (options) => formatKeys({
430
- ...options,
431
- search: /([a-z])_([a-z])/g,
432
- replace: (_, firstLetter, secondLetter) => `${firstLetter}-${secondLetter}`
433
- });
434
-
435
- // src/fns/snakeToLowerCamelKeys.ts
436
- var snakeToLowerCamelKeys = (options) => formatKeys({
437
- ...options,
438
- search: /([a-z])_([a-z])/g,
439
- replace: (_, firstLetter, secondLetter) => {
440
- const newSecondLetter = secondLetter.toUpperCase();
441
- return `${firstLetter}${newSecondLetter}`;
442
- }
443
- });
444
-
445
- // src/fns/unflat.ts
446
- var unflat = (options) => {
447
- const { target, pathDelimiter = "." } = options;
448
- const useTarget = target;
449
- return Object.keys(useTarget).reduce(
450
- (current, key) => set({ target: current, path: key, value: useTarget[key], pathDelimiter }),
451
- {}
452
- );
453
- };
454
- // Annotate the CommonJS export names for ESM import in node:
455
- 0 && (module.exports = {
456
- copy,
457
- dashToLowerCamelKeys,
458
- dashToSnakeKeys,
459
- extract,
460
- flat,
461
- formatKeys,
462
- get,
463
- lowerCamelToDashKeys,
464
- lowerCamelToSnakeKeys,
465
- merge,
466
- remove,
467
- set,
468
- snakeToDashKeys,
469
- snakeToLowerCamelKeys,
470
- unflat
471
- });
1
+ import $ from"extend";var E=(...n)=>{let[i]=n,e=Array.isArray(i)?[]:{};return $(!0,e,...n)};var k=n=>E(n);var y=n=>{let{target:i,search:e,replace:r,include:a=[],exclude:c=[],pathDelimiter:o="."}=n,f=i,p=Object.keys(i),s={};p.forEach(l=>{let u=f[l];s[l]=!!(u&&typeof u=="object"&&u!==null&&!Array.isArray(u)&&Object.keys(u))});let t=o.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),g=new RegExp(`^${t}`,"i"),m=new RegExp(`${t}$`,"i"),h={},w;a.length?w=a.map(l=>{let u=l.replace(g,"").replace(m,""),d;if(u.includes(o)){let T=u.split(o),x=T.shift();d="",h[x]||(h[x]=[]),h[x].push(T.join(o))}else d=u;return d}).filter(l=>l):w=p;let O={};if(c.length){let l=[];c.forEach(u=>{let d=u.replace(g,"").replace(m,"");if(d.includes(o)){let T=d.split(o),x=T.shift();O[x]||(O[x]=[]),O[x].push(T.join(o))}else s[d]=!1,l.push(d)}),w=w.filter(u=>u&&!l.includes(u))}return p.reduce((l,u)=>{let d,T,x=f[u];return w.includes(u)?d=u.replace(e,r):d=u,s[u]?T=y({target:x,search:e,replace:r,include:h[u]||[],exclude:O[u]||[],pathDelimiter:o}):T=x,{...l,[d]:T}},{})};var j=n=>y({...n,search:/([a-z])-([a-z])/g,replace:(i,e,r)=>{let a=r.toUpperCase();return`${e}${a}`}});var W=n=>y({...n,search:/([a-z])-([a-z])/g,replace:(i,e,r)=>`${e}_${r}`});function R(n,i){let e;typeof i=="string"?e={target:n,path:i}:e=n;let{target:r,path:a,pathDelimiter:c=".",failWithError:o=!1}=e,f=r,p=a.split(c),s=p.shift(),t=f[s];if(typeof t>"u"){if(o)throw new Error(`There's nothing on '${a}'`);return}if(!p.length)return t;let g=s;return p.some(m=>{let h=!1;if(g+=`${c}${m}`,t=t[m],typeof t>"u"){if(o)throw new Error(`There's nothing on '${g}'`);h=!0}return h}),t}var F=["__proto__","prototype","constructor"];function K(n,i,e){let r;typeof i=="string"?r={target:n,path:i,value:e}:r=n;let{target:a,path:c,value:o,pathDelimiter:f=".",failWithError:p=!1}=r,s=k(a);if(!c.includes(f))return!c||F.includes(c.toLowerCase())?void 0:(s[c]=o,s);let t=c.split(f);if(t.some(l=>!l||F.includes(l.toLowerCase())))return;let m=t.pop(),h=s,w="",O=!1;if(t.forEach(l=>{w+=`${f}${l}`;let d=typeof h[l];if(d==="undefined")h[l]={},h=h[l];else if(d==="object")h=h[l];else{let T=w.substring(f.length);if(p)throw new Error(`There's already an element of type '${d}' on '${T}'`);O=!0}}),!O)return s&&m&&(h[m]=o),s}var N=n=>{let{target:i,paths:e,pathDelimiter:r=".",failWithError:a=!1}=n,c=k(i),o={},f=!1;if((Array.isArray(e)?e:[e]).reduce((p,s)=>{let t,g;if(typeof s=="string")t=s,g=s;else{let[m]=Object.keys(s);t=m,g=s[t]}return p.push({origin:g,customDest:t.includes(r),dest:t}),p},[]).some(p=>{let s=!1,t=R({target:c,path:p.origin,pathDelimiter:r,failWithError:a});if(typeof t<"u")if(p.customDest){let g=K({target:o,path:p.dest,value:t,pathDelimiter:r,failWithError:a});typeof g>"u"?(s=!0,f=!0):o=g}else o[p.dest]=t;return s}),!f)return o};var v=n=>{let{target:i,shouldFlatten:e,pathDelimiter:r=".",prefix:a=""}=n,c=i,o={},f=a?`${a}${r}`:"";return Object.keys(c).forEach(p=>{let s=`${f}${p}`,t=c[p],m=typeof t==="object"&&t!==null;m&&(!e||e(p,t))?o=E(o,v({target:t,pathDelimiter:r,prefix:s,shouldFlatten:e})):o[s]=m?k(t):t}),o};var Y=n=>y({...n,search:/([a-z])([A-Z])/g,replace:(i,e,r)=>{let a=r.toLowerCase();return`${e}-${a}`}});var ne=n=>y({...n,search:/([a-z])([A-Z])/g,replace:(i,e,r)=>{let a=r.toLowerCase();return`${e}_${a}`}});function D(n,i){let e;typeof i=="string"?e={target:n,path:i}:e=n;let{target:r,path:a,pathDelimiter:c=".",cleanEmptyProperties:o=!0,failWithError:f=!1}=e,p=a.split(c),s=p.pop(),t=k(r);if(!p.length)return delete t[s],t;let g=p.join(c),m=R({target:t,path:g,pathDelimiter:c,failWithError:f});if(!(typeof m>"u"))return delete m[s],o&&!Object.keys(m).length?D({target:t,path:g,pathDelimiter:c,failWithError:f,cleanEmptyProperties:o}):t}var pe=n=>y({...n,search:/([a-z])_([a-z])/g,replace:(i,e,r)=>`${e}-${r}`});var le=n=>y({...n,search:/([a-z])_([a-z])/g,replace:(i,e,r)=>{let a=r.toUpperCase();return`${e}${a}`}});var me=n=>{let{target:i,pathDelimiter:e="."}=n,r=i;return Object.keys(r).reduce((a,c)=>K({target:a,path:c,value:r[c],pathDelimiter:e}),{})};export{k as copy,j as dashToLowerCamelKeys,W as dashToSnakeKeys,N as extract,v as flat,y as formatKeys,R as get,Y as lowerCamelToDashKeys,ne as lowerCamelToSnakeKeys,E as merge,D as remove,K as set,pe as snakeToDashKeys,le as snakeToLowerCamelKeys,me as unflat};
472
2
  //# sourceMappingURL=index.js.map