flattify 1.0.2 → 2.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/LICENSE +1 -1
- package/README.md +332 -120
- package/dist/flatten-CYe7gyYE.js +228 -0
- package/dist/flatten-DWk2mUxV.cjs +287 -0
- package/dist/index.cjs +89 -0
- package/dist/index.d.cts +152 -0
- package/dist/index.d.ts +152 -0
- package/dist/index.js +87 -0
- package/dist/path-types-D9d1uvNh.d.cts +148 -0
- package/dist/path-types-D9d1uvNh.d.ts +148 -0
- package/dist/path.cjs +132 -0
- package/dist/path.d.cts +168 -0
- package/dist/path.d.ts +168 -0
- package/dist/path.js +124 -0
- package/package.json +106 -17
- package/path/package.json +6 -0
- package/.editorconfig +0 -17
- package/.npmignore +0 -3
- package/CHANGELOG.md +0 -6
- package/index.js +0 -7
- package/lib/flattify.js +0 -60
- package/test/flattify.js +0 -180
- package/test/mocks/array.json +0 -44
- package/test/mocks/object.json +0 -21
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { _ as Notation, c as FlattenOptions, g as Prettify, h as Option, m as IsUnion, p as IsAny, r as Split, s as Flatten } from "./path-types-D9d1uvNh.cjs";
|
|
2
|
+
//#region src/flatten/flatten.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Flattens a nested object (or array) into a single-level object whose keys are the paths to each value.
|
|
5
|
+
*
|
|
6
|
+
* Only plain objects and arrays are walked: dates, maps, sets, class instances and any other object are
|
|
7
|
+
* kept as values. The walk uses an explicit stack instead of recursion, so deeply nested input cannot
|
|
8
|
+
* overflow the call stack.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```ts
|
|
12
|
+
* import { flatten } from 'flattify';
|
|
13
|
+
*
|
|
14
|
+
* const flat = flatten({ user: { name: 'Ada', tags: ['admin', 'dev'] } });
|
|
15
|
+
* // { 'user.name': 'Ada', 'user.tags.0': 'admin', 'user.tags.1': 'dev' }
|
|
16
|
+
*
|
|
17
|
+
* flatten({ user: { name: 'Ada' } }, { delimiter: '_' });
|
|
18
|
+
* // { user_name: 'Ada' }
|
|
19
|
+
*
|
|
20
|
+
* flatten({ items: [{ id: 1 }] }, { notation: 'bracket' });
|
|
21
|
+
* // { 'items[0].id': 1 }
|
|
22
|
+
*
|
|
23
|
+
* flatten({ items: [{ id: 1 }] }, { notation: 'pointer' });
|
|
24
|
+
* // { '/items/0/id': 1 }
|
|
25
|
+
* ```
|
|
26
|
+
*
|
|
27
|
+
* @param input The plain object or array to flatten.
|
|
28
|
+
* @param options See {@link FlattenOptions}.
|
|
29
|
+
* @returns A new object; values are not cloned.
|
|
30
|
+
* @throws {TypeError} If `input` is not a plain object or array, or on a circular reference when `circular` is `'throw'`.
|
|
31
|
+
*/
|
|
32
|
+
export declare function flatten<T extends object>(input: T): Flatten<T>;
|
|
33
|
+
export declare function flatten<T extends object, const O extends FlattenOptions>(input: T, options: O): Flatten<T, O>;
|
|
34
|
+
//#endregion
|
|
35
|
+
//#region src/unflatten/types.d.ts
|
|
36
|
+
interface UnflattenOptions {
|
|
37
|
+
/** Splits the keys into paths. Default: `'.'`. */
|
|
38
|
+
delimiter?: string;
|
|
39
|
+
/**
|
|
40
|
+
* `'dot'` (`items.0.id`), `'bracket'` (`items[0].id`, also `items[0][id]` as in form fields) or
|
|
41
|
+
* `'pointer'` (`/items/0/id`, RFC 6901: every key must start with `/`). Default: `'dot'`.
|
|
42
|
+
*/
|
|
43
|
+
notation?: Notation;
|
|
44
|
+
/** Builds objects only: `{ 'list.0': 'a' }` becomes `{ list: { 0: 'a' } }` instead of `{ list: ['a'] }`. Default: `false`. */
|
|
45
|
+
object?: boolean;
|
|
46
|
+
/** Lets a later key replace a value in its way (`{ a: 1, 'a.b': 2 }` → `{ a: { b: 2 } }`). Otherwise the later key is skipped. Default: `false`. */
|
|
47
|
+
overwrite?: boolean;
|
|
48
|
+
/** Reads `\` as an escape, so `'a\\.b'` is the single key `'a.b'`, as `flatten` writes it. Default: `true`. */
|
|
49
|
+
escape?: boolean;
|
|
50
|
+
/**
|
|
51
|
+
* Largest index turned into an array element; objects with a larger index key stay objects, so
|
|
52
|
+
* `{ 'a.4294967294': 1 }` cannot allocate a huge sparse array. Default: `1000`.
|
|
53
|
+
*/
|
|
54
|
+
arrayLimit?: number;
|
|
55
|
+
/**
|
|
56
|
+
* Returns an array: the top-level keys are its indices, as `flatten` writes them for an array
|
|
57
|
+
* (`{ '0.id': 1, '1.id': 2 }` → `[{ id: 1 }, { id: 2 }]`). Throws a `TypeError` if a top-level key is
|
|
58
|
+
* not an index up to `arrayLimit`. Default: `false`, the result is always an object.
|
|
59
|
+
*/
|
|
60
|
+
asArray?: boolean;
|
|
61
|
+
/** Renames each key of the path before it is set; array indices are left alone. The result is typed as `Record<string, unknown>`. */
|
|
62
|
+
transformKey?: (key: string) => string;
|
|
63
|
+
}
|
|
64
|
+
interface Context {
|
|
65
|
+
delimiter: string;
|
|
66
|
+
notation: Notation;
|
|
67
|
+
escape: boolean;
|
|
68
|
+
object: boolean;
|
|
69
|
+
}
|
|
70
|
+
type SplitKey<K, C extends Context> = K extends string | number ? Split<`${K}`, C> : never;
|
|
71
|
+
type Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;
|
|
72
|
+
/** Template keys (`` `tags.${number}` ``) come from arrays and records, which always exist once flattened. */
|
|
73
|
+
type IsRequiredKey<T, K extends keyof T> = {} extends Record<K, 1> ? true : {} extends Pick<T, K> ? false : true;
|
|
74
|
+
type Heads<T, C extends Context> = { [K in keyof T]-?: SplitKey<K, C>[0]; }[keyof T];
|
|
75
|
+
type RequiredHeads<T, C extends Context> = { [K in keyof T]-?: IsRequiredKey<T, K> extends true ? SplitKey<K, C>[0] : never; }[keyof T];
|
|
76
|
+
/** The keys below `H`, with `H` and the delimiter removed. */
|
|
77
|
+
type Children<T, H, C extends Context> = { [K in keyof T as SplitKey<K, C> extends [infer Head, infer Rest extends string] ? (Same<Head, H> extends true ? Rest : never) : never]: T[K]; };
|
|
78
|
+
/** The values set at `H` itself. */
|
|
79
|
+
type LeafValues<T, H, C extends Context> = { [K in keyof T]-?: SplitKey<K, C> extends [infer Head, never] ? (Same<Head, H> extends true ? T[K] : never) : never; }[keyof T];
|
|
80
|
+
/** Empty containers kept by `flatten`, already covered by the keys below the same path. */
|
|
81
|
+
type EmptyMarker = [] | readonly [] | Record<string, never>;
|
|
82
|
+
type Value<T, H, C extends Context> = [keyof Children<T, H, C>] extends [never] ? LeafValues<T, H, C> : Exclude<LeafValues<T, H, C>, EmptyMarker> | ([Children<T, H, C>] extends [infer Nested] ? ToArray<Build<Nested, C>, C> : never);
|
|
83
|
+
type Build<T, C extends Context> = Prettify<{ [H in RequiredHeads<T, C>]: Value<T, H, C>; } & { [H in Exclude<Heads<T, C>, RequiredHeads<T, C>>]?: Value<T, H, C>; }>;
|
|
84
|
+
type ToTuple<T, Acc extends unknown[] = []> = `${Acc["length"]}` extends keyof T ? ToTuple<T, [...Acc, T[`${Acc["length"]}` & keyof T]]> : Acc;
|
|
85
|
+
/** Objects whose keys are all array indices become arrays (tuples for `0..n` literal indices), as at runtime. */
|
|
86
|
+
type ToArray<T, C extends Context> = C["object"] extends true ? T : [keyof T] extends [never] ? T : [keyof T] extends [`${number}`] ? `${number}` extends keyof T ? T[keyof T][] : ToTuple<T> extends (infer Tuple extends unknown[]) ? Same<keyof T, Extract<keyof Tuple, `${number}`>> extends true ? Tuple : T[keyof T][] : never : T;
|
|
87
|
+
type IsWide<C extends Context> = string extends C["delimiter"] ? true : IsUnion<C["notation"]> extends true ? true : boolean extends C["escape"] ? true : boolean extends C["object"] ? true : false;
|
|
88
|
+
/**
|
|
89
|
+
* The object returned by `unflatten(T, O)`: the flat keys of `T` split into a nested object, with arrays
|
|
90
|
+
* for index keys. `Unflatten<Flatten<T>>` gives back `T` for plain data.
|
|
91
|
+
*
|
|
92
|
+
* @example
|
|
93
|
+
* ```ts
|
|
94
|
+
* type User = Unflatten<{ 'user.name': string; [x: `user.tags.${number}`]: string }>;
|
|
95
|
+
* // { user: { name: string; tags: string[] } }
|
|
96
|
+
*
|
|
97
|
+
* type Users = Unflatten<{ [x: `${number}.id`]: number }, { asArray: true }>;
|
|
98
|
+
* // { id: number }[]
|
|
99
|
+
* ```
|
|
100
|
+
*/
|
|
101
|
+
type Unflatten<T, O extends UnflattenOptions = {}> = Root<IsAny<T> extends true ? Record<string, any> : [Option<O, "transformKey", never>] extends [never] ? UnflattenWith<T, {
|
|
102
|
+
delimiter: Option<O, "delimiter", ".">;
|
|
103
|
+
notation: Option<O, "notation", "dot">;
|
|
104
|
+
escape: Option<O, "escape", true>;
|
|
105
|
+
object: Option<O, "object", false>;
|
|
106
|
+
}> : Record<string, unknown>, Option<O, "asArray", false>>;
|
|
107
|
+
/** With `asArray`, an array of the top-level values; `never` when a key is known not to be an index, as the call throws. */
|
|
108
|
+
type Root<R, AsArray> = AsArray extends true ? (R extends unknown ? RootArray<R> : never) : R;
|
|
109
|
+
type RootArray<R> = [keyof R] extends [never] ? [] : string extends keyof R ? R[keyof R][] : [keyof R] extends [`${number}`] ? ToArray<R, {
|
|
110
|
+
delimiter: ".";
|
|
111
|
+
notation: "dot";
|
|
112
|
+
escape: true;
|
|
113
|
+
object: false;
|
|
114
|
+
}> : never;
|
|
115
|
+
type UnflattenWith<T, C extends Context> = IsWide<C> extends true ? Record<string, unknown> : T extends unknown ? Build<T, C> : never;
|
|
116
|
+
//#endregion
|
|
117
|
+
//#region src/unflatten/unflatten.d.ts
|
|
118
|
+
/**
|
|
119
|
+
* Rebuilds a nested object from a flat object whose keys are paths: the reverse of `flatten`.
|
|
120
|
+
*
|
|
121
|
+
* Safe on untrusted input (form fields, query strings, JSON bodies): keys are only ever created as own
|
|
122
|
+
* properties, so no path, including `__proto__`, `constructor` or `prototype`, can reach
|
|
123
|
+
* `Object.prototype`. Paths with a `__proto__` segment are skipped.
|
|
124
|
+
*
|
|
125
|
+
* @example
|
|
126
|
+
* ```ts
|
|
127
|
+
* import { unflatten } from 'flattify';
|
|
128
|
+
*
|
|
129
|
+
* unflatten({ 'user.name': 'Ada', 'user.tags.0': 'admin' });
|
|
130
|
+
* // { user: { name: 'Ada', tags: ['admin'] } }
|
|
131
|
+
*
|
|
132
|
+
* // Form fields named `address.city`, `address.zip`...
|
|
133
|
+
* const body = unflatten(Object.fromEntries(new FormData(form)));
|
|
134
|
+
*
|
|
135
|
+
* // Form-field style names, or JSON Pointers
|
|
136
|
+
* unflatten({ 'user[name]': 'Ada', 'user[tags][0]': 'admin' }, { notation: 'bracket' });
|
|
137
|
+
* unflatten({ '/user/name': 'Ada' }, { notation: 'pointer' });
|
|
138
|
+
*
|
|
139
|
+
* // Back to the array given to `flatten`
|
|
140
|
+
* unflatten({ '0.id': 1, '1.id': 2 }, { asArray: true });
|
|
141
|
+
* // [{ id: 1 }, { id: 2 }]
|
|
142
|
+
* ```
|
|
143
|
+
*
|
|
144
|
+
* @param input A flat object, such as the one returned by `flatten`.
|
|
145
|
+
* @param options See {@link UnflattenOptions}.
|
|
146
|
+
* @returns A new object (an array with `asArray`). Objects and arrays found in `input` are copied before keys are added to them.
|
|
147
|
+
* @throws {TypeError} If `input` is not a plain object, with `asArray` when a top-level key is not an array index, or with the `'pointer'` notation when a key does not start with `/`.
|
|
148
|
+
*/
|
|
149
|
+
export declare function unflatten<T extends object>(input: T): Unflatten<T>;
|
|
150
|
+
export declare function unflatten<T extends object, const O extends UnflattenOptions>(input: T, options: O): Unflatten<T, O>;
|
|
151
|
+
//#endregion
|
|
152
|
+
export type { Flatten, FlattenOptions, Notation, Prettify, Unflatten, UnflattenOptions };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { _ as Notation, c as FlattenOptions, g as Prettify, h as Option, m as IsUnion, p as IsAny, r as Split, s as Flatten } from "./path-types-D9d1uvNh.js";
|
|
2
|
+
//#region src/flatten/flatten.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Flattens a nested object (or array) into a single-level object whose keys are the paths to each value.
|
|
5
|
+
*
|
|
6
|
+
* Only plain objects and arrays are walked: dates, maps, sets, class instances and any other object are
|
|
7
|
+
* kept as values. The walk uses an explicit stack instead of recursion, so deeply nested input cannot
|
|
8
|
+
* overflow the call stack.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```ts
|
|
12
|
+
* import { flatten } from 'flattify';
|
|
13
|
+
*
|
|
14
|
+
* const flat = flatten({ user: { name: 'Ada', tags: ['admin', 'dev'] } });
|
|
15
|
+
* // { 'user.name': 'Ada', 'user.tags.0': 'admin', 'user.tags.1': 'dev' }
|
|
16
|
+
*
|
|
17
|
+
* flatten({ user: { name: 'Ada' } }, { delimiter: '_' });
|
|
18
|
+
* // { user_name: 'Ada' }
|
|
19
|
+
*
|
|
20
|
+
* flatten({ items: [{ id: 1 }] }, { notation: 'bracket' });
|
|
21
|
+
* // { 'items[0].id': 1 }
|
|
22
|
+
*
|
|
23
|
+
* flatten({ items: [{ id: 1 }] }, { notation: 'pointer' });
|
|
24
|
+
* // { '/items/0/id': 1 }
|
|
25
|
+
* ```
|
|
26
|
+
*
|
|
27
|
+
* @param input The plain object or array to flatten.
|
|
28
|
+
* @param options See {@link FlattenOptions}.
|
|
29
|
+
* @returns A new object; values are not cloned.
|
|
30
|
+
* @throws {TypeError} If `input` is not a plain object or array, or on a circular reference when `circular` is `'throw'`.
|
|
31
|
+
*/
|
|
32
|
+
export declare function flatten<T extends object>(input: T): Flatten<T>;
|
|
33
|
+
export declare function flatten<T extends object, const O extends FlattenOptions>(input: T, options: O): Flatten<T, O>;
|
|
34
|
+
//#endregion
|
|
35
|
+
//#region src/unflatten/types.d.ts
|
|
36
|
+
interface UnflattenOptions {
|
|
37
|
+
/** Splits the keys into paths. Default: `'.'`. */
|
|
38
|
+
delimiter?: string;
|
|
39
|
+
/**
|
|
40
|
+
* `'dot'` (`items.0.id`), `'bracket'` (`items[0].id`, also `items[0][id]` as in form fields) or
|
|
41
|
+
* `'pointer'` (`/items/0/id`, RFC 6901: every key must start with `/`). Default: `'dot'`.
|
|
42
|
+
*/
|
|
43
|
+
notation?: Notation;
|
|
44
|
+
/** Builds objects only: `{ 'list.0': 'a' }` becomes `{ list: { 0: 'a' } }` instead of `{ list: ['a'] }`. Default: `false`. */
|
|
45
|
+
object?: boolean;
|
|
46
|
+
/** Lets a later key replace a value in its way (`{ a: 1, 'a.b': 2 }` → `{ a: { b: 2 } }`). Otherwise the later key is skipped. Default: `false`. */
|
|
47
|
+
overwrite?: boolean;
|
|
48
|
+
/** Reads `\` as an escape, so `'a\\.b'` is the single key `'a.b'`, as `flatten` writes it. Default: `true`. */
|
|
49
|
+
escape?: boolean;
|
|
50
|
+
/**
|
|
51
|
+
* Largest index turned into an array element; objects with a larger index key stay objects, so
|
|
52
|
+
* `{ 'a.4294967294': 1 }` cannot allocate a huge sparse array. Default: `1000`.
|
|
53
|
+
*/
|
|
54
|
+
arrayLimit?: number;
|
|
55
|
+
/**
|
|
56
|
+
* Returns an array: the top-level keys are its indices, as `flatten` writes them for an array
|
|
57
|
+
* (`{ '0.id': 1, '1.id': 2 }` → `[{ id: 1 }, { id: 2 }]`). Throws a `TypeError` if a top-level key is
|
|
58
|
+
* not an index up to `arrayLimit`. Default: `false`, the result is always an object.
|
|
59
|
+
*/
|
|
60
|
+
asArray?: boolean;
|
|
61
|
+
/** Renames each key of the path before it is set; array indices are left alone. The result is typed as `Record<string, unknown>`. */
|
|
62
|
+
transformKey?: (key: string) => string;
|
|
63
|
+
}
|
|
64
|
+
interface Context {
|
|
65
|
+
delimiter: string;
|
|
66
|
+
notation: Notation;
|
|
67
|
+
escape: boolean;
|
|
68
|
+
object: boolean;
|
|
69
|
+
}
|
|
70
|
+
type SplitKey<K, C extends Context> = K extends string | number ? Split<`${K}`, C> : never;
|
|
71
|
+
type Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;
|
|
72
|
+
/** Template keys (`` `tags.${number}` ``) come from arrays and records, which always exist once flattened. */
|
|
73
|
+
type IsRequiredKey<T, K extends keyof T> = {} extends Record<K, 1> ? true : {} extends Pick<T, K> ? false : true;
|
|
74
|
+
type Heads<T, C extends Context> = { [K in keyof T]-?: SplitKey<K, C>[0]; }[keyof T];
|
|
75
|
+
type RequiredHeads<T, C extends Context> = { [K in keyof T]-?: IsRequiredKey<T, K> extends true ? SplitKey<K, C>[0] : never; }[keyof T];
|
|
76
|
+
/** The keys below `H`, with `H` and the delimiter removed. */
|
|
77
|
+
type Children<T, H, C extends Context> = { [K in keyof T as SplitKey<K, C> extends [infer Head, infer Rest extends string] ? (Same<Head, H> extends true ? Rest : never) : never]: T[K]; };
|
|
78
|
+
/** The values set at `H` itself. */
|
|
79
|
+
type LeafValues<T, H, C extends Context> = { [K in keyof T]-?: SplitKey<K, C> extends [infer Head, never] ? (Same<Head, H> extends true ? T[K] : never) : never; }[keyof T];
|
|
80
|
+
/** Empty containers kept by `flatten`, already covered by the keys below the same path. */
|
|
81
|
+
type EmptyMarker = [] | readonly [] | Record<string, never>;
|
|
82
|
+
type Value<T, H, C extends Context> = [keyof Children<T, H, C>] extends [never] ? LeafValues<T, H, C> : Exclude<LeafValues<T, H, C>, EmptyMarker> | ([Children<T, H, C>] extends [infer Nested] ? ToArray<Build<Nested, C>, C> : never);
|
|
83
|
+
type Build<T, C extends Context> = Prettify<{ [H in RequiredHeads<T, C>]: Value<T, H, C>; } & { [H in Exclude<Heads<T, C>, RequiredHeads<T, C>>]?: Value<T, H, C>; }>;
|
|
84
|
+
type ToTuple<T, Acc extends unknown[] = []> = `${Acc["length"]}` extends keyof T ? ToTuple<T, [...Acc, T[`${Acc["length"]}` & keyof T]]> : Acc;
|
|
85
|
+
/** Objects whose keys are all array indices become arrays (tuples for `0..n` literal indices), as at runtime. */
|
|
86
|
+
type ToArray<T, C extends Context> = C["object"] extends true ? T : [keyof T] extends [never] ? T : [keyof T] extends [`${number}`] ? `${number}` extends keyof T ? T[keyof T][] : ToTuple<T> extends (infer Tuple extends unknown[]) ? Same<keyof T, Extract<keyof Tuple, `${number}`>> extends true ? Tuple : T[keyof T][] : never : T;
|
|
87
|
+
type IsWide<C extends Context> = string extends C["delimiter"] ? true : IsUnion<C["notation"]> extends true ? true : boolean extends C["escape"] ? true : boolean extends C["object"] ? true : false;
|
|
88
|
+
/**
|
|
89
|
+
* The object returned by `unflatten(T, O)`: the flat keys of `T` split into a nested object, with arrays
|
|
90
|
+
* for index keys. `Unflatten<Flatten<T>>` gives back `T` for plain data.
|
|
91
|
+
*
|
|
92
|
+
* @example
|
|
93
|
+
* ```ts
|
|
94
|
+
* type User = Unflatten<{ 'user.name': string; [x: `user.tags.${number}`]: string }>;
|
|
95
|
+
* // { user: { name: string; tags: string[] } }
|
|
96
|
+
*
|
|
97
|
+
* type Users = Unflatten<{ [x: `${number}.id`]: number }, { asArray: true }>;
|
|
98
|
+
* // { id: number }[]
|
|
99
|
+
* ```
|
|
100
|
+
*/
|
|
101
|
+
type Unflatten<T, O extends UnflattenOptions = {}> = Root<IsAny<T> extends true ? Record<string, any> : [Option<O, "transformKey", never>] extends [never] ? UnflattenWith<T, {
|
|
102
|
+
delimiter: Option<O, "delimiter", ".">;
|
|
103
|
+
notation: Option<O, "notation", "dot">;
|
|
104
|
+
escape: Option<O, "escape", true>;
|
|
105
|
+
object: Option<O, "object", false>;
|
|
106
|
+
}> : Record<string, unknown>, Option<O, "asArray", false>>;
|
|
107
|
+
/** With `asArray`, an array of the top-level values; `never` when a key is known not to be an index, as the call throws. */
|
|
108
|
+
type Root<R, AsArray> = AsArray extends true ? (R extends unknown ? RootArray<R> : never) : R;
|
|
109
|
+
type RootArray<R> = [keyof R] extends [never] ? [] : string extends keyof R ? R[keyof R][] : [keyof R] extends [`${number}`] ? ToArray<R, {
|
|
110
|
+
delimiter: ".";
|
|
111
|
+
notation: "dot";
|
|
112
|
+
escape: true;
|
|
113
|
+
object: false;
|
|
114
|
+
}> : never;
|
|
115
|
+
type UnflattenWith<T, C extends Context> = IsWide<C> extends true ? Record<string, unknown> : T extends unknown ? Build<T, C> : never;
|
|
116
|
+
//#endregion
|
|
117
|
+
//#region src/unflatten/unflatten.d.ts
|
|
118
|
+
/**
|
|
119
|
+
* Rebuilds a nested object from a flat object whose keys are paths: the reverse of `flatten`.
|
|
120
|
+
*
|
|
121
|
+
* Safe on untrusted input (form fields, query strings, JSON bodies): keys are only ever created as own
|
|
122
|
+
* properties, so no path, including `__proto__`, `constructor` or `prototype`, can reach
|
|
123
|
+
* `Object.prototype`. Paths with a `__proto__` segment are skipped.
|
|
124
|
+
*
|
|
125
|
+
* @example
|
|
126
|
+
* ```ts
|
|
127
|
+
* import { unflatten } from 'flattify';
|
|
128
|
+
*
|
|
129
|
+
* unflatten({ 'user.name': 'Ada', 'user.tags.0': 'admin' });
|
|
130
|
+
* // { user: { name: 'Ada', tags: ['admin'] } }
|
|
131
|
+
*
|
|
132
|
+
* // Form fields named `address.city`, `address.zip`...
|
|
133
|
+
* const body = unflatten(Object.fromEntries(new FormData(form)));
|
|
134
|
+
*
|
|
135
|
+
* // Form-field style names, or JSON Pointers
|
|
136
|
+
* unflatten({ 'user[name]': 'Ada', 'user[tags][0]': 'admin' }, { notation: 'bracket' });
|
|
137
|
+
* unflatten({ '/user/name': 'Ada' }, { notation: 'pointer' });
|
|
138
|
+
*
|
|
139
|
+
* // Back to the array given to `flatten`
|
|
140
|
+
* unflatten({ '0.id': 1, '1.id': 2 }, { asArray: true });
|
|
141
|
+
* // [{ id: 1 }, { id: 2 }]
|
|
142
|
+
* ```
|
|
143
|
+
*
|
|
144
|
+
* @param input A flat object, such as the one returned by `flatten`.
|
|
145
|
+
* @param options See {@link UnflattenOptions}.
|
|
146
|
+
* @returns A new object (an array with `asArray`). Objects and arrays found in `input` are copied before keys are added to them.
|
|
147
|
+
* @throws {TypeError} If `input` is not a plain object, with `asArray` when a top-level key is not an array index, or with the `'pointer'` notation when a key does not start with `/`.
|
|
148
|
+
*/
|
|
149
|
+
export declare function unflatten<T extends object>(input: T): Unflatten<T>;
|
|
150
|
+
export declare function unflatten<T extends object, const O extends UnflattenOptions>(input: T, options: O): Unflatten<T, O>;
|
|
151
|
+
//#endregion
|
|
152
|
+
export type { Flatten, FlattenOptions, Notation, Prettify, Unflatten, UnflattenOptions };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { c as assign, i as validateNotation, l as isContainer, n as validate, r as pathFormat, s as isIndex, t as flatten, u as isPlainObject } from "./flatten-CYe7gyYE.js";
|
|
2
|
+
//#region src/unflatten/unflatten.ts
|
|
3
|
+
const hasOwn = (target, key) => Object.prototype.hasOwnProperty.call(target, key);
|
|
4
|
+
function validateArrayLimit(arrayLimit) {
|
|
5
|
+
if (arrayLimit !== Infinity && (!Number.isInteger(arrayLimit) || arrayLimit < 0)) throw new RangeError("`arrayLimit` must be a non-negative integer or Infinity");
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Walks from `parent` into `key`, creating the object when it is missing. Returns `undefined` when a
|
|
9
|
+
* value that is not an object or array is in the way and `overwrite` is off.
|
|
10
|
+
*
|
|
11
|
+
* `owned` holds the objects built by `unflatten`. Objects and arrays that came in as values of `input`
|
|
12
|
+
* are not in it: they are copied before new keys go in, never modified.
|
|
13
|
+
*/
|
|
14
|
+
function descend(parent, key, overwrite, owned, candidates) {
|
|
15
|
+
const current = hasOwn(parent, key) ? parent[key] : void 0;
|
|
16
|
+
if (isContainer(current, false) && owned.has(current)) return current;
|
|
17
|
+
if (current !== void 0 && !isContainer(current, false) && !overwrite) return void 0;
|
|
18
|
+
const next = {};
|
|
19
|
+
if (isContainer(current, false)) for (const k of Object.keys(current)) assign(next, k, current[k]);
|
|
20
|
+
owned.add(next);
|
|
21
|
+
assign(parent, key, next);
|
|
22
|
+
candidates === null || candidates === void 0 || candidates.push([
|
|
23
|
+
parent,
|
|
24
|
+
key,
|
|
25
|
+
next
|
|
26
|
+
]);
|
|
27
|
+
return next;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Turns the candidates whose keys are all array indices into arrays. They are visited from the last one
|
|
31
|
+
* built, so nested arrays are in place before the object that holds them is converted.
|
|
32
|
+
*/
|
|
33
|
+
function restoreArrays(candidates, arrayLimit) {
|
|
34
|
+
for (let c = candidates.length - 1; c >= 0; c--) {
|
|
35
|
+
const [parent, key, object] = candidates[c];
|
|
36
|
+
if (parent[key] !== object) continue;
|
|
37
|
+
const keys = Object.keys(object);
|
|
38
|
+
if (!keys.every((k) => isIndex(k, arrayLimit))) continue;
|
|
39
|
+
const array = [];
|
|
40
|
+
for (const k of keys) array[Number(k)] = object[k];
|
|
41
|
+
parent[key] = array;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
function unflatten(input, options = {}) {
|
|
45
|
+
const { delimiter = ".", notation = "dot", object = false, overwrite = false, escape = true, arrayLimit = 1e3, asArray = false, transformKey } = options;
|
|
46
|
+
validateNotation(notation);
|
|
47
|
+
if (notation !== "pointer") validate(delimiter, escape);
|
|
48
|
+
validateArrayLimit(arrayLimit);
|
|
49
|
+
const { split } = pathFormat(notation, delimiter, escape);
|
|
50
|
+
if (!isPlainObject(input)) throw new TypeError("unflatten() expects a plain object");
|
|
51
|
+
const result = {};
|
|
52
|
+
const owned = /* @__PURE__ */ new Set([result]);
|
|
53
|
+
const candidates = object ? void 0 : [];
|
|
54
|
+
entries: for (const key of Object.keys(input)) {
|
|
55
|
+
const segments = split(key);
|
|
56
|
+
if (segments.length === 0) throw new TypeError("The JSON Pointer \"\" (the whole document) cannot be a key of a flat object");
|
|
57
|
+
if (segments.includes("__proto__")) continue;
|
|
58
|
+
if (transformKey) {
|
|
59
|
+
for (let i = 0; i < segments.length; i++) if (!isIndex(segments[i], Infinity)) segments[i] = transformKey(segments[i]);
|
|
60
|
+
}
|
|
61
|
+
let target = result;
|
|
62
|
+
for (let i = 0; i < segments.length - 1; i++) {
|
|
63
|
+
const next = descend(target, segments[i], overwrite, owned, candidates && isIndex(segments[i + 1], arrayLimit) ? candidates : void 0);
|
|
64
|
+
if (next === void 0) continue entries;
|
|
65
|
+
target = next;
|
|
66
|
+
}
|
|
67
|
+
const last = segments[segments.length - 1];
|
|
68
|
+
const value = input[key];
|
|
69
|
+
const current = hasOwn(target, last) ? target[last] : void 0;
|
|
70
|
+
const isEmpty = isContainer(value, false) && Object.keys(value).length === 0;
|
|
71
|
+
if (isContainer(current, false) && (!overwrite || isEmpty)) continue;
|
|
72
|
+
assign(target, last, value);
|
|
73
|
+
}
|
|
74
|
+
if (candidates) restoreArrays(candidates, arrayLimit);
|
|
75
|
+
return asArray ? toRootArray(result, arrayLimit) : result;
|
|
76
|
+
}
|
|
77
|
+
/** `asArray`: the top-level keys are the indices of the array, as written by `flatten(array)`. */
|
|
78
|
+
function toRootArray(result, arrayLimit) {
|
|
79
|
+
const array = [];
|
|
80
|
+
for (const key of Object.keys(result)) {
|
|
81
|
+
if (!isIndex(key, arrayLimit)) throw new TypeError(`\`asArray\` expects every top-level key to be an array index up to \`arrayLimit\`, got "${key}"`);
|
|
82
|
+
array[Number(key)] = result[key];
|
|
83
|
+
}
|
|
84
|
+
return array;
|
|
85
|
+
}
|
|
86
|
+
//#endregion
|
|
87
|
+
export { flatten, unflatten };
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
//#region src/shared/notation.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* How paths are written:
|
|
4
|
+
* - `'dot'`: `items.0.id`
|
|
5
|
+
* - `'bracket'`: `items[0].id`, array indices between brackets
|
|
6
|
+
* - `'pointer'`: `/items/0/id`, a JSON Pointer (RFC 6901); `delimiter` and `escape` do not apply
|
|
7
|
+
*/
|
|
8
|
+
type Notation = "dot" | "bracket" | "pointer";
|
|
9
|
+
//#endregion
|
|
10
|
+
//#region src/shared/types.d.ts
|
|
11
|
+
/** Flattens intersections so editors show the resulting keys instead of the type expression. */
|
|
12
|
+
type Prettify<T> = { [K in keyof T]: T[K]; } & {};
|
|
13
|
+
type UnionToIntersection<U> = (U extends unknown ? (x: U) => void : never) extends ((x: infer I) => void) ? I : never;
|
|
14
|
+
type IsAny<T> = 0 extends 1 & T ? true : false;
|
|
15
|
+
type IsUnion<T, All = T> = [T] extends [never] ? false : T extends unknown ? ([All] extends [T] ? false : true) : never;
|
|
16
|
+
/**
|
|
17
|
+
* Values that are never walked into, mirroring `isPlainObject` at runtime. TypeScript cannot tell a
|
|
18
|
+
* class instance from a plain object, so only built-ins are listed.
|
|
19
|
+
*/
|
|
20
|
+
type Leaf = string | number | bigint | boolean | symbol | null | undefined | ((...args: never[]) => unknown) | Date | RegExp | ReadonlyMap<unknown, unknown> | ReadonlySet<unknown> | WeakMap<object, unknown> | WeakSet<object> | PromiseLike<unknown> | ArrayBuffer | ArrayBufferView;
|
|
21
|
+
/** Replaces every `From` in `S`. Non-literal strings are returned as they are. */
|
|
22
|
+
type ReplaceAll<S extends string, From extends string, To extends string> = string extends S ? S : S extends `${infer Head}${From}${infer Tail}` ? `${Head}${To}${ReplaceAll<Tail, From, To>}` : S;
|
|
23
|
+
/**
|
|
24
|
+
* Reads option `K` from an options type: `Default` when it is missing or `undefined`. A value only known
|
|
25
|
+
* at runtime (`string`, `boolean`...) comes back as that wide type.
|
|
26
|
+
*/
|
|
27
|
+
type Option<O, K extends PropertyKey, Default> = K extends keyof O ? ([Exclude<O[K & keyof O], undefined>] extends [never] ? Default : Exclude<O[K & keyof O], undefined>) : Default;
|
|
28
|
+
/**
|
|
29
|
+
* Merges the flattened variants of a union: a key is required only when every variant has it, and its
|
|
30
|
+
* value is the union of the values of the variants that have it.
|
|
31
|
+
*/
|
|
32
|
+
type MergeVariants<U> = IsUnion<U> extends true ? Prettify<{ [K in KeysOf<U> as IsRequiredInAll<U, K> extends true ? K : never]: ValueIn<U, K>; } & { [K in KeysOf<U> as IsRequiredInAll<U, K> extends true ? never : K]?: ValueIn<U, K>; }> : U;
|
|
33
|
+
type KeysOf<U> = U extends unknown ? keyof U : never;
|
|
34
|
+
type ValueIn<U, K extends PropertyKey> = U extends unknown ? (K extends keyof U ? U[K & keyof U] : never) : never;
|
|
35
|
+
type RequiredKeys<T> = { [K in keyof T]-?: {} extends Pick<T, K> ? never : K; }[keyof T];
|
|
36
|
+
type IsRequiredInAll<U, K extends PropertyKey> = [U extends unknown ? (K extends RequiredKeys<U> ? never : 1) : never] extends [never] ? true : false;
|
|
37
|
+
//#endregion
|
|
38
|
+
//#region src/flatten/types.d.ts
|
|
39
|
+
interface FlattenOptions {
|
|
40
|
+
/** Joins the keys of a path. Default: `'.'`. */
|
|
41
|
+
delimiter?: string;
|
|
42
|
+
/** `'dot'` (`items.0.id`), `'bracket'` (`items[0].id`) or `'pointer'` (`/items/0/id`, RFC 6901). Default: `'dot'`. */
|
|
43
|
+
notation?: Notation;
|
|
44
|
+
/** Levels to walk into; deeper objects are kept as values. `1` keeps the top-level keys only. Default: `Infinity`. */
|
|
45
|
+
maxDepth?: number;
|
|
46
|
+
/** Keeps arrays as values instead of flattening them to index keys. Default: `false`. */
|
|
47
|
+
safe?: boolean;
|
|
48
|
+
/** Keeps empty objects and arrays as values, so `unflatten` restores them. Default: `true`. */
|
|
49
|
+
keepEmpty?: boolean;
|
|
50
|
+
/** Escapes `\` and the delimiter inside keys (`'a.b'` → `'a\\.b'`), so `unflatten` restores them. Default: `true`. */
|
|
51
|
+
escape?: boolean;
|
|
52
|
+
/** What to do when an object contains itself: throw a `TypeError` or skip the key. Default: `'throw'`. */
|
|
53
|
+
circular?: "throw" | "skip";
|
|
54
|
+
/** Renames each object key before it is joined; array indices are left alone. Keys are typed as `string`. */
|
|
55
|
+
transformKey?: (key: string) => string;
|
|
56
|
+
/** Return `true` to keep an object or array as a value at `path` instead of walking into it. Keys are typed as `string`. */
|
|
57
|
+
preserve?: (path: string, value: unknown) => boolean;
|
|
58
|
+
}
|
|
59
|
+
/** Nesting levels TypeScript expands before typing deeper paths as `unknown`. */
|
|
60
|
+
type TypeDepthLimit = 10;
|
|
61
|
+
interface Context {
|
|
62
|
+
delimiter: string;
|
|
63
|
+
notation: Notation;
|
|
64
|
+
maxDepth: number | undefined;
|
|
65
|
+
safe: boolean;
|
|
66
|
+
keepEmpty: boolean;
|
|
67
|
+
escape: boolean;
|
|
68
|
+
}
|
|
69
|
+
type Kind<V, C extends Context> = V extends Leaf ? "leaf" : V extends readonly unknown[] ? (C["safe"] extends true ? "leaf" : "array") : V extends object ? ([keyof V] extends [never] ? "unknown" : "object") : "leaf";
|
|
70
|
+
type LeavesOf<V, C extends Context> = V extends unknown ? (Kind<V, C> extends "leaf" ? V : never) : never;
|
|
71
|
+
type ContainersOf<V, C extends Context> = V extends unknown ? (Kind<V, C> extends "leaf" ? never : V) : never;
|
|
72
|
+
/** Mirrors `escapeKey`: see `src/shared/path.ts`. `X` is `'['` in bracket notation. */
|
|
73
|
+
type EscapeKey<K extends string, D extends string, X extends string> = NeedsEscape<K, D, X> extends true ? D extends `${infer First}${string}` ? ReplaceAll<ReplaceAll<ReplaceAll<K, "\\", "\\\\">, First, `\\${First}`>, X, `\\${X}`> : K : K;
|
|
74
|
+
type NeedsEscape<K extends string, D extends string, X extends string> = K extends `${string}\\${string}` | `${string}${D}${string}` | `${string}${X}${string}` ? true : [Overlaps<D>] extends [never] ? false : K extends `${string}${Overlaps<D>}` ? true : false;
|
|
75
|
+
/** Proper prefixes of the delimiter that overlap with it: `':'` for `'::'`, as `':' + '::'` starts with `'::'`. */
|
|
76
|
+
type Overlaps<D extends string> = Prefixes<D> extends (infer P) ? (P extends string ? (`${P}${D}` extends `${D}${string}` ? P : never) : never) : never;
|
|
77
|
+
type Prefixes<D extends string, Acc extends string = ""> = D extends `${infer Char}${infer Rest}` ? (Rest extends "" ? never : `${Acc}${Char}` | Prefixes<Rest, `${Acc}${Char}`>) : never;
|
|
78
|
+
/** Mirrors `pathFormat().join`: appends key `K` to path `P` (the top level is at depth `[]`). */
|
|
79
|
+
type Join<P extends string, K extends string | number, IsIndex extends boolean, D extends unknown[], C extends Context> = C["notation"] extends "pointer" ? `${P}/${K extends string ? ReplaceAll<ReplaceAll<K, "~", "~0">, "/", "~1"> : K}` : C["notation"] extends "bracket" ? IsIndex extends true ? `${P}[${K}]` : JoinKey<P, K extends string ? (C["escape"] extends true ? EscapeKey<K, C["delimiter"], "["> : K) : `${K}`, D, C> : JoinKey<P, K extends string ? (C["escape"] extends true ? EscapeKey<K, C["delimiter"], never> : K) : `${K}`, D, C>;
|
|
80
|
+
type JoinKey<P extends string, K extends string, D extends unknown[], C extends Context> = D extends [] ? K : `${P}${C["delimiter"]}${K}`;
|
|
81
|
+
/** Any path below `K`, for values whose shape is unknown. */
|
|
82
|
+
type Below<K extends string, C extends Context> = C["notation"] extends "pointer" ? `${K}/${string}` : C["notation"] extends "bracket" ? `${K}${C["delimiter"]}${string}` | `${K}[${string}` : `${K}${C["delimiter"]}${string}`;
|
|
83
|
+
/** `?` is skipped for template keys (`` `tags.${number}.name` ``): they are index signatures, where it would only add `undefined`. */
|
|
84
|
+
type Field<K extends string, V, Optional extends boolean> = [V] extends [never] ? {} : Optional extends true ? ({} extends Record<K, 1> ? { [_ in K]: V; } : { [_ in K]?: V; }) : { [_ in K]: V; };
|
|
85
|
+
/** `true` when the container at depth `D` (the top-level one is `[]`) is walked into its children. */
|
|
86
|
+
type CanDescend<D extends unknown[], C extends Context> = C["maxDepth"] extends number ? ([...D, unknown]["length"] extends C["maxDepth"] ? false : true) : true;
|
|
87
|
+
/** An empty container flattens to itself when `keepEmpty` is on: the key is required if it is always empty. */
|
|
88
|
+
type EmptyField<V, K extends string, C extends Context> = C["keepEmpty"] extends true ? V extends readonly unknown[] ? V extends readonly [] ? { [_ in K]: []; } : [] extends V ? Field<K, [], true> : {} : {} extends V ? Field<K, Record<string, never>, true> : {} : {};
|
|
89
|
+
type Nested<V, K extends string, D extends unknown[], C extends Context> = V extends unknown ? Kind<V, C> extends "unknown" ? { [_ in K | Below<K, C>]?: unknown; } : Prettify<FlatContainer<V, K, [...D, unknown], C> & EmptyField<V, K, C>> : never;
|
|
90
|
+
/** The flattened keys contributed by one property: `K` itself for leaf values, the paths below it for containers. */
|
|
91
|
+
type Property<V, K extends string, Optional extends boolean, D extends unknown[], C extends Context> = IsAny<V> extends true ? { [_ in K]: any; } : CanDescend<D, C> extends false ? Field<K, V, Optional> : D["length"] extends TypeDepthLimit ? { [_ in K | Below<K, C>]?: unknown; } : [ContainersOf<V, C>] extends [never] ? Field<K, LeavesOf<V, C>, Optional> : Mixed<Exclude<LeavesOf<V, C>, Optional extends true ? undefined : never>, NestedMerged<ContainersOf<V, C>, K, D, C>, K, Optional>;
|
|
92
|
+
/**
|
|
93
|
+
* The `infer` hides the recursive type from the constraint of `MergeVariants`: TypeScript 5.0 reports
|
|
94
|
+
* a circular constraint otherwise.
|
|
95
|
+
*/
|
|
96
|
+
type NestedMerged<V, K extends string, D extends unknown[], C extends Context> = [Nested<V, K, D, C>] extends [infer N] ? MergeVariants<N> : never;
|
|
97
|
+
/**
|
|
98
|
+
* A property holding a container, possibly alongside leaf values (`Address | null`). The paths below it
|
|
99
|
+
* are only certain when the property is required and always holds a container.
|
|
100
|
+
*/
|
|
101
|
+
type Mixed<L, N, K extends string, Optional extends boolean> = Field<K, L, true> & ([L] extends [never] ? (Optional extends true ? Partial<N> : N) : Partial<N>);
|
|
102
|
+
type ObjectEntries<T, P extends string, IsArray extends boolean, D extends unknown[], C extends Context> = UnionToIntersection<{ [K in keyof T]-?: K extends string | number ? Property<T[K], Join<P, K, IsArray, D, C>, IsOptional<T, K>, D, C> : {}; }[keyof T]>;
|
|
103
|
+
/** Index signatures (`[key: string]: V`) are left required: `?` would add `undefined` to their values. */
|
|
104
|
+
type IsOptional<T, K extends keyof T> = string extends K ? false : number extends K ? false : {} extends Pick<T, K> ? true : false;
|
|
105
|
+
type TupleEntries<T extends readonly unknown[]> = { [K in keyof T as K extends `${number}` ? K : never]: T[K]; };
|
|
106
|
+
type FlatContainer<T, P extends string, D extends unknown[], C extends Context> = T extends readonly unknown[] ? number extends T["length"] ? Property<T[number], Join<P, `${number}`, true, D, C>, false, D, C> : ObjectEntries<TupleEntries<T>, P, true, D, C> : ObjectEntries<T, P, false, D, C>;
|
|
107
|
+
type IsWide<C extends Context> = string extends C["delimiter"] ? true : IsUnion<C["notation"]> extends true ? true : number extends C["maxDepth"] ? true : boolean extends C["safe"] ? true : boolean extends C["keepEmpty"] ? true : boolean extends C["escape"] ? true : false;
|
|
108
|
+
/**
|
|
109
|
+
* The object returned by `flatten(T, O)`: one key per path, typed with the value found there.
|
|
110
|
+
*
|
|
111
|
+
* Options only known at runtime (a `string` delimiter, `transformKey`, `preserve`...) make the keys
|
|
112
|
+
* `string`, as the paths can no longer be computed.
|
|
113
|
+
*
|
|
114
|
+
* @example
|
|
115
|
+
* ```ts
|
|
116
|
+
* type User = Flatten<{ name: string; tags: string[] }>;
|
|
117
|
+
* // { name: string; [x: `tags.${number}`]: string; tags?: [] }
|
|
118
|
+
* ```
|
|
119
|
+
*/
|
|
120
|
+
type Flatten<T, O extends FlattenOptions = {}> = IsAny<T> extends true ? Record<string, any> : [Option<O, "transformKey", never> | Option<O, "preserve", never>] extends [never] ? FlattenWith<T, {
|
|
121
|
+
delimiter: Option<O, "delimiter", ".">;
|
|
122
|
+
notation: Option<O, "notation", "dot">;
|
|
123
|
+
maxDepth: Option<O, "maxDepth", undefined>;
|
|
124
|
+
safe: Option<O, "safe", false>;
|
|
125
|
+
keepEmpty: Option<O, "keepEmpty", true>;
|
|
126
|
+
escape: Option<O, "escape", true>;
|
|
127
|
+
}> : Record<string, unknown>;
|
|
128
|
+
type FlattenWith<T, C extends Context> = IsWide<C> extends true ? Record<string, unknown> : T extends unknown ? Prettify<FlatContainer<T, "", [], C>> : never;
|
|
129
|
+
//#endregion
|
|
130
|
+
//#region src/shared/path-types.d.ts
|
|
131
|
+
/** The options that decide how a path is written. */
|
|
132
|
+
interface PathContext {
|
|
133
|
+
delimiter: string;
|
|
134
|
+
notation: Notation;
|
|
135
|
+
escape: boolean;
|
|
136
|
+
}
|
|
137
|
+
/** Walks a key that contains `\` one character at a time, mirroring `splitPath`. */
|
|
138
|
+
type SplitEscaped<K extends string, D extends string, Acc extends string = ""> = K extends `\\${infer Char}${infer Rest}` ? SplitEscaped<Rest, D, `${Acc}${Char}`> : K extends `${D}${infer Rest}` ? [Acc, Rest] : K extends `${infer Char}${infer Rest}` ? SplitEscaped<Rest, D, `${Acc}${Char}`> : [`${Acc}${K}`, never];
|
|
139
|
+
/** `[first key, rest of the path]`, or `[key, never]` for the last key of a path. Mirrors `pathFormat().split`. */
|
|
140
|
+
type Split<K extends string, C extends PathContext> = C["notation"] extends "pointer" ? SplitPointer<K> : C["notation"] extends "bracket" ? SplitBracket<K, C["delimiter"], C["escape"]> : C["escape"] extends true ? K extends `${infer Head}${C["delimiter"]}${infer Rest}` ? Head extends `${string}\\${string}` ? SplitEscaped<K, C["delimiter"]> : [Head, Rest] : K extends `${string}\\${string}` ? SplitEscaped<K, C["delimiter"]> : [K, never] : K extends `${infer Head}${C["delimiter"]}${infer Rest}` ? [Head, Rest] : [K, never];
|
|
141
|
+
type Unpointer<S extends string> = ReplaceAll<ReplaceAll<S, "~1", "/">, "~0", "~">;
|
|
142
|
+
type SplitPointer<K extends string> = K extends `/${infer Path}` ? (Path extends `${infer Head}/${infer Rest}` ? [Unpointer<Head>, `/${Rest}`] : [Unpointer<Path>, never]) : never;
|
|
143
|
+
type SplitBracket<K extends string, D extends string, E extends boolean, Acc extends string = ""> = K extends `[${infer Inner}]${infer Rest}` ? Acc extends "" ? [Inner, Rest extends "" ? never : Rest extends `${D}${infer After}` ? After : Rest] : [Acc, K] : E extends true ? K extends `\\${infer Char}${infer Rest}` ? SplitBracket<Rest, D, E, `${Acc}${Char}`> : SplitBracketNext<K, D, E, Acc> : SplitBracketNext<K, D, E, Acc>;
|
|
144
|
+
type SplitBracketNext<K extends string, D extends string, E extends boolean, Acc extends string> = K extends `${D}${infer Rest}` ? [Acc, Rest] : K extends `${infer Char}${infer Rest}` ? SplitBracket<Rest, D, E, `${Acc}${Char}`> : [`${Acc}${K}`, never];
|
|
145
|
+
/** Every key of a path, in order: `Segments<'a.b[0]', bracket>` is `['a', 'b', '0']`. */
|
|
146
|
+
type Segments<P extends string, C extends PathContext> = Split<P, C> extends [infer Head extends string, infer Rest] ? ([Rest] extends [never] ? [Head] : Rest extends string ? [Head, ...Segments<Rest, C>] : [Head]) : string[];
|
|
147
|
+
//#endregion
|
|
148
|
+
export { Notation as _, ContainersOf as a, FlattenOptions as c, TupleEntries as d, TypeDepthLimit as f, Prettify as g, Option as h, Below as i, Join as l, IsUnion as m, Segments as n, Context as o, IsAny as p, Split as r, Flatten as s, PathContext as t, Kind as u };
|