flattify 1.0.2 → 2.0.1

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.
@@ -0,0 +1,149 @@
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
+ /** Options of `flatten`. Each one also changes the inferred keys of the result. */
40
+ interface FlattenOptions {
41
+ /** Joins the keys of a path. Default: `'.'`. */
42
+ delimiter?: string;
43
+ /** `'dot'` (`items.0.id`), `'bracket'` (`items[0].id`) or `'pointer'` (`/items/0/id`, RFC 6901). Default: `'dot'`. */
44
+ notation?: Notation;
45
+ /** Levels to walk into; deeper objects are kept as values. `1` keeps the top-level keys only. Default: `Infinity`. */
46
+ maxDepth?: number;
47
+ /** Keeps arrays as values instead of flattening them to index keys. Default: `false`. */
48
+ safe?: boolean;
49
+ /** Keeps empty objects and arrays as values, so `unflatten` restores them. Default: `true`. */
50
+ keepEmpty?: boolean;
51
+ /** Escapes `\` and the delimiter inside keys (`'a.b'` → `'a\\.b'`), so `unflatten` restores them. Default: `true`. */
52
+ escape?: boolean;
53
+ /** What to do when an object contains itself: throw a `TypeError` or skip the key. Default: `'throw'`. */
54
+ circular?: "throw" | "skip";
55
+ /** Renames each object key before it is joined; array indices are left alone. Keys are typed as `string`. */
56
+ transformKey?: (key: string) => string;
57
+ /** Return `true` to keep an object or array as a value at `path` instead of walking into it. Keys are typed as `string`. */
58
+ preserve?: (path: string, value: unknown) => boolean;
59
+ }
60
+ /** Nesting levels TypeScript expands before typing deeper paths as `unknown`. */
61
+ type TypeDepthLimit = 10;
62
+ interface Context {
63
+ delimiter: string;
64
+ notation: Notation;
65
+ maxDepth: number | undefined;
66
+ safe: boolean;
67
+ keepEmpty: boolean;
68
+ escape: boolean;
69
+ }
70
+ 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";
71
+ type LeavesOf<V, C extends Context> = V extends unknown ? (Kind<V, C> extends "leaf" ? V : never) : never;
72
+ type ContainersOf<V, C extends Context> = V extends unknown ? (Kind<V, C> extends "leaf" ? never : V) : never;
73
+ /** Mirrors `escapeKey`: see `src/shared/path.ts`. `X` is `'['` in bracket notation. */
74
+ 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;
75
+ 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;
76
+ /** Proper prefixes of the delimiter that overlap with it: `':'` for `'::'`, as `':' + '::'` starts with `'::'`. */
77
+ type Overlaps<D extends string> = Prefixes<D> extends (infer P) ? (P extends string ? (`${P}${D}` extends `${D}${string}` ? P : never) : never) : never;
78
+ type Prefixes<D extends string, Acc extends string = ""> = D extends `${infer Char}${infer Rest}` ? (Rest extends "" ? never : `${Acc}${Char}` | Prefixes<Rest, `${Acc}${Char}`>) : never;
79
+ /** Mirrors `pathFormat().join`: appends key `K` to path `P` (the top level is at depth `[]`). */
80
+ 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>;
81
+ type JoinKey<P extends string, K extends string, D extends unknown[], C extends Context> = D extends [] ? K : `${P}${C["delimiter"]}${K}`;
82
+ /** Any path below `K`, for values whose shape is unknown. */
83
+ 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}`;
84
+ /** `?` is skipped for template keys (`` `tags.${number}.name` ``): they are index signatures, where it would only add `undefined`. */
85
+ 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; };
86
+ /** `true` when the container at depth `D` (the top-level one is `[]`) is walked into its children. */
87
+ type CanDescend<D extends unknown[], C extends Context> = C["maxDepth"] extends number ? ([...D, unknown]["length"] extends C["maxDepth"] ? false : true) : true;
88
+ /** An empty container flattens to itself when `keepEmpty` is on: the key is required if it is always empty. */
89
+ 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> : {} : {};
90
+ 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;
91
+ /** The flattened keys contributed by one property: `K` itself for leaf values, the paths below it for containers. */
92
+ 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>;
93
+ /**
94
+ * The `infer` hides the recursive type from the constraint of `MergeVariants`: TypeScript 5.0 reports
95
+ * a circular constraint otherwise.
96
+ */
97
+ type NestedMerged<V, K extends string, D extends unknown[], C extends Context> = [Nested<V, K, D, C>] extends [infer N] ? MergeVariants<N> : never;
98
+ /**
99
+ * A property holding a container, possibly alongside leaf values (`Address | null`). The paths below it
100
+ * are only certain when the property is required and always holds a container.
101
+ */
102
+ 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>);
103
+ 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]>;
104
+ /** Index signatures (`[key: string]: V`) are left required: `?` would add `undefined` to their values. */
105
+ type IsOptional<T, K extends keyof T> = string extends K ? false : number extends K ? false : {} extends Pick<T, K> ? true : false;
106
+ type TupleEntries<T extends readonly unknown[]> = { [K in keyof T as K extends `${number}` ? K : never]: T[K]; };
107
+ 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>;
108
+ 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;
109
+ /**
110
+ * The object returned by `flatten(T, O)`: one key per path, typed with the value found there.
111
+ *
112
+ * Options only known at runtime (a `string` delimiter, `transformKey`, `preserve`...) make the keys
113
+ * `string`, as the paths can no longer be computed.
114
+ *
115
+ * @example
116
+ * ```ts
117
+ * type User = Flatten<{ name: string; tags: string[] }>;
118
+ * // { name: string; [x: `tags.${number}`]: string; tags?: [] }
119
+ * ```
120
+ */
121
+ 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, {
122
+ delimiter: Option<O, "delimiter", ".">;
123
+ notation: Option<O, "notation", "dot">;
124
+ maxDepth: Option<O, "maxDepth", undefined>;
125
+ safe: Option<O, "safe", false>;
126
+ keepEmpty: Option<O, "keepEmpty", true>;
127
+ escape: Option<O, "escape", true>;
128
+ }> : Record<string, unknown>;
129
+ type FlattenWith<T, C extends Context> = IsWide<C> extends true ? Record<string, unknown> : T extends unknown ? Prettify<FlatContainer<T, "", [], C>> : never;
130
+ //#endregion
131
+ //#region src/shared/path-types.d.ts
132
+ /** The options that decide how a path is written. */
133
+ interface PathContext {
134
+ delimiter: string;
135
+ notation: Notation;
136
+ escape: boolean;
137
+ }
138
+ /** Walks a key that contains `\` one character at a time, mirroring `splitPath`. */
139
+ 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];
140
+ /** `[first key, rest of the path]`, or `[key, never]` for the last key of a path. Mirrors `pathFormat().split`. */
141
+ 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];
142
+ type Unpointer<S extends string> = ReplaceAll<ReplaceAll<S, "~1", "/">, "~0", "~">;
143
+ type SplitPointer<K extends string> = K extends `/${infer Path}` ? (Path extends `${infer Head}/${infer Rest}` ? [Unpointer<Head>, `/${Rest}`] : [Unpointer<Path>, never]) : never;
144
+ 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>;
145
+ 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];
146
+ /** Every key of a path, in order: `Segments<'a.b[0]', bracket>` is `['a', 'b', '0']`. */
147
+ 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[];
148
+ //#endregion
149
+ 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 };
package/dist/path.cjs ADDED
@@ -0,0 +1,132 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_flatten = require("./flatten-DWk2mUxV.cjs");
3
+ //#region src/path/path.ts
4
+ const MISSING = Symbol("missing");
5
+ const FORBIDDEN = /* @__PURE__ */ new Set([
6
+ "__proto__",
7
+ "constructor",
8
+ "prototype"
9
+ ]);
10
+ const hasOwn = (target, key) => Object.prototype.hasOwnProperty.call(target, key);
11
+ const isTraversable = (value) => typeof value === "object" && value !== null || typeof value === "function";
12
+ function formatOf(options) {
13
+ const { delimiter = ".", notation = "dot", escape = true } = options;
14
+ require_flatten.validateNotation(notation);
15
+ if (notation !== "pointer") require_flatten.validate(delimiter, escape);
16
+ return require_flatten.pathFormat(notation, delimiter, escape);
17
+ }
18
+ /**
19
+ * Reads `key` of `target`. Plain objects and arrays expose their own keys only, so `'toString'` or
20
+ * `'constructor'` are missing on data; other objects (class instances, dates...) expose inherited
21
+ * properties too, except `__proto__`, `constructor` and `prototype`.
22
+ */
23
+ function read(target, key) {
24
+ if (require_flatten.isPlainObject(target) || Array.isArray(target)) return hasOwn(target, key) ? target[key] : MISSING;
25
+ if (FORBIDDEN.has(key) && !hasOwn(target, key)) return MISSING;
26
+ return key in target ? target[key] : MISSING;
27
+ }
28
+ function checkTarget(input, name) {
29
+ if (!isTraversable(input)) throw new TypeError(`${name}() expects an object or an array`);
30
+ }
31
+ function get(obj, path, options = {}) {
32
+ checkTarget(obj, "get");
33
+ let current = obj;
34
+ for (const key of formatOf(options).split(path)) {
35
+ if (!isTraversable(current)) return void 0;
36
+ current = read(current, key);
37
+ if (current === MISSING) return void 0;
38
+ }
39
+ return current;
40
+ }
41
+ function has(obj, path, options = {}) {
42
+ checkTarget(obj, "has");
43
+ let current = obj;
44
+ for (const key of formatOf(options).split(path)) {
45
+ if (!isTraversable(current)) return false;
46
+ current = read(current, key);
47
+ if (current === MISSING) return false;
48
+ }
49
+ return true;
50
+ }
51
+ function set(obj, path, value, options = {}) {
52
+ checkTarget(obj, "set");
53
+ const { object = false, arrayLimit = 1e3 } = options;
54
+ if (arrayLimit !== Infinity && (!Number.isInteger(arrayLimit) || arrayLimit < 0)) throw new RangeError("`arrayLimit` must be a non-negative integer or Infinity");
55
+ const segments = formatOf(options).split(path);
56
+ if (segments.length === 0) throw new TypeError("set() cannot replace the whole object: the JSON Pointer \"\" has no key");
57
+ if (segments.includes("__proto__")) return obj;
58
+ let target = obj;
59
+ for (let i = 0; i < segments.length - 1; i++) {
60
+ const child = read(target, segments[i]);
61
+ if (isTraversable(child)) target = child;
62
+ else {
63
+ const next = !object && require_flatten.isIndex(segments[i + 1], arrayLimit) ? [] : {};
64
+ require_flatten.assign(target, segments[i], next);
65
+ target = next;
66
+ }
67
+ }
68
+ require_flatten.assign(target, segments[segments.length - 1], value);
69
+ return obj;
70
+ }
71
+ function del(obj, path, options = {}) {
72
+ checkTarget(obj, "del");
73
+ const segments = formatOf(options).split(path);
74
+ if (segments.length === 0) return false;
75
+ let target = obj;
76
+ for (let i = 0; i < segments.length - 1; i++) {
77
+ if (!isTraversable(target)) return false;
78
+ target = read(target, segments[i]);
79
+ }
80
+ const last = segments[segments.length - 1];
81
+ if (!isTraversable(target) || !hasOwn(target, last)) return false;
82
+ return delete target[last];
83
+ }
84
+ function paths(obj, options = {}) {
85
+ return Object.keys(require_flatten.flatten(obj, options));
86
+ }
87
+ function parsePath(path, options = {}) {
88
+ return formatOf(options).split(path);
89
+ }
90
+ /**
91
+ * Joins keys into a path, escaping them when needed: the reverse of `parsePath`. In bracket notation,
92
+ * keys that are array indices are written between brackets.
93
+ *
94
+ * @example
95
+ * ```ts
96
+ * stringifyPath(['user', 'first.name']); // 'user.first\\.name'
97
+ * stringifyPath(['items', '0', 'id'], { notation: 'bracket' }); // 'items[0].id'
98
+ * stringifyPath(['a/b', 'c'], { notation: 'pointer' }); // '/a~1b/c'
99
+ * ```
100
+ */
101
+ function stringifyPath(keys, options = {}) {
102
+ var _path;
103
+ const format = formatOf(options);
104
+ const bracket = options.notation === "bracket";
105
+ let path;
106
+ for (const key of keys) path = format.join(path, String(key), bracket && require_flatten.isIndex(String(key), Infinity));
107
+ return (_path = path) !== null && _path !== void 0 ? _path : "";
108
+ }
109
+ /**
110
+ * Escapes a single key so it can be put in a path as it is.
111
+ *
112
+ * @example
113
+ * ```ts
114
+ * `user.${escapeKey('first.name')}`; // 'user.first\\.name'
115
+ * escapeKey('a/b', { notation: 'pointer' }); // 'a~1b'
116
+ * ```
117
+ */
118
+ function escapeKey(key, options = {}) {
119
+ const { delimiter = ".", notation = "dot" } = options;
120
+ formatOf(options);
121
+ if (notation === "pointer") return require_flatten.escapePointer(key);
122
+ return require_flatten.escapeKey(key, delimiter, notation === "bracket" ? "[" : "");
123
+ }
124
+ //#endregion
125
+ exports.del = del;
126
+ exports.escapeKey = escapeKey;
127
+ exports.get = get;
128
+ exports.has = has;
129
+ exports.parsePath = parsePath;
130
+ exports.paths = paths;
131
+ exports.set = set;
132
+ exports.stringifyPath = stringifyPath;
@@ -0,0 +1,204 @@
1
+ import { _ as Notation, a as ContainersOf, c as FlattenOptions, d as TupleEntries, f as TypeDepthLimit, h as Option, i as Below, l as Join, m as IsUnion, n as Segments, o as Context, p as IsAny, s as Flatten, t as PathContext, u as Kind } from "./path-types-BjuDIcLg.cjs";
2
+ //#region src/path/types.d.ts
3
+ /** How the paths given to the `flattify/path` helpers are written. */
4
+ interface PathOptions {
5
+ /** Separates the keys of a path. Default: `'.'`. */
6
+ delimiter?: string;
7
+ /** `'dot'` (`items.0.id`), `'bracket'` (`items[0].id`) or `'pointer'` (`/items/0/id`, RFC 6901). Default: `'dot'`. */
8
+ notation?: Notation;
9
+ /** Reads `\` as an escape, so `'a\\.b'` is the single key `'a.b'`. Default: `true`. */
10
+ escape?: boolean;
11
+ }
12
+ /** Options of `set`: how the path is written, and what is created for missing keys. */
13
+ interface SetOptions extends PathOptions {
14
+ /** Creates objects only, never arrays, for missing keys along the path. Default: `false`. */
15
+ object?: boolean;
16
+ /** Largest index that creates an array for a missing key; larger ones create an object. Default: `1000`. */
17
+ arrayLimit?: number;
18
+ }
19
+ type ContextOf$1<O> = {
20
+ delimiter: Option<O, "delimiter", ".">;
21
+ notation: Option<O, "notation", "dot">;
22
+ escape: Option<O, "escape", true>;
23
+ maxDepth: undefined;
24
+ safe: false;
25
+ keepEmpty: true;
26
+ };
27
+ type IsWide<C extends Context> = string extends C["delimiter"] ? true : IsUnion<C["notation"]> extends true ? true : boolean extends C["escape"] ? true : false;
28
+ type PathsOf<T, P extends string, D extends unknown[], C extends Context> = T extends readonly unknown[] ? number extends T["length"] ? Node<T[number], Join<P, `${number}`, true, D, C>, D, C> : Entries<TupleEntries<T>, P, true, D, C> : Entries<T, P, false, D, C>;
29
+ type Entries<T, P extends string, IsArray extends boolean, D extends unknown[], C extends Context> = { [K in keyof T]-?: K extends string | number ? Node<T[K], Join<P, K, IsArray, D, C>, D, C> : never; }[keyof T];
30
+ type Node<V, K extends string, D extends unknown[], C extends Context> = IsAny<V> extends true ? K | Below<K, C> : K | (D["length"] extends TypeDepthLimit ? Below<K, C> : Nested<ContainersOf<V, C>, K, D, C>);
31
+ type Nested<V, K extends string, D extends unknown[], C extends Context> = V extends unknown ? (Kind<V, C> extends "unknown" ? Below<K, C> : [PathsOf<V, K, [...D, unknown], C>] extends [infer Paths] ? Paths : never) : never;
32
+ /**
33
+ * Every path of `T`, to an object, an array or a value: what `get`, `set`, `has` and `del` accept.
34
+ *
35
+ * @example
36
+ * ```ts
37
+ * type P = Path<{ user: { tags: string[] } }>;
38
+ * // 'user' | 'user.tags' | `user.tags.${number}`
39
+ * ```
40
+ */
41
+ type Path<T, O extends PathOptions = {}> = IsAny<T> extends true ? string : IsWide<ContextOf$1<O>> extends true ? string : T extends unknown ? ([PathsOf<T, "", [], ContextOf$1<O>>] extends [infer Paths extends string] ? Paths : never) : never;
42
+ /** One step of `Walk`. `Get` is `true` when reading, where arrays and records may miss the key. */
43
+ type Step<T, K extends string, Get extends boolean> = T extends unknown ? IsAny<T> extends true ? any : unknown extends T ? unknown : T extends null | undefined ? undefined : T extends readonly unknown[] ? number extends T["length"] ? K extends `${number}` ? T[number] | (Get extends true ? undefined : never) : undefined : K extends keyof T ? T[K] : undefined : [keyof T] extends [never] ? unknown : K extends keyof T ? T[K] | (string extends keyof T ? (Get extends true ? undefined : never) : never) : K extends `${infer N extends number}` ? N extends keyof T ? T[N] : IndexValue<T, Get> : IndexValue<T, Get> : never;
44
+ type IndexValue<T, Get extends boolean> = string extends keyof T ? T[string & keyof T] | (Get extends true ? undefined : never) : undefined;
45
+ type Walk<T, S, Get extends boolean> = S extends [infer K extends string, ...infer Rest] ? Walk<Step<T, K, Get>, Rest, Get> : S extends [] ? T : unknown;
46
+ /**
47
+ * The value at path `P` of `T`. Array elements and record values may be missing, so they include
48
+ * `undefined`, as with `noUncheckedIndexedAccess`.
49
+ *
50
+ * @example
51
+ * ```ts
52
+ * type City = Get<{ user: { address: { city: string } } }, 'user.address.city'>; // string
53
+ * type Tag = Get<{ tags: string[] }, 'tags.0'>; // string | undefined
54
+ * ```
55
+ */
56
+ type Get<T, P extends string, O extends PathOptions = {}> = IsAny<T> extends true ? any : string extends P ? unknown : IsWide<ContextOf$1<O>> extends true ? unknown : [Segments<P, ContextOf$1<O>>] extends [infer S] ? Walk<T, S, true> : never;
57
+ /** The type `set` accepts at path `P` of `T`. */
58
+ type SetValue<T, P extends string, O extends PathOptions = {}> = IsAny<T> extends true ? any : string extends P ? unknown : IsWide<ContextOf$1<O>> extends true ? unknown : [Segments<P, ContextOf$1<O>>] extends [infer S] ? Walk<T, S, false> : never;
59
+ //#endregion
60
+ //#region src/path/path.d.ts
61
+ /**
62
+ * Reads the value at `path`, or `undefined` when a key is missing along the way. The JSON Pointer `''`
63
+ * is `obj` itself.
64
+ *
65
+ * The path is autocompleted and the result typed from `obj`. Plain objects and arrays are read through
66
+ * their own keys only: `get({}, 'constructor')` is `undefined`.
67
+ *
68
+ * @example
69
+ * ```ts
70
+ * import { get } from 'flattify/path';
71
+ *
72
+ * const order = { items: [{ sku: 'A1', qty: 2 }] };
73
+ * get(order, 'items.0.sku'); // 'A1', typed string | undefined
74
+ * get(order, '/items/0/qty', { notation: 'pointer' }); // 2
75
+ * ```
76
+ */
77
+ export declare function get<T extends object, P extends Path<T>>(obj: T, path: P): Get<T, P>;
78
+ /**
79
+ * Reads the value at `path`, written in another `delimiter` or `notation`.
80
+ *
81
+ * @example
82
+ * ```ts
83
+ * get(order, '/items/0/sku', { notation: 'pointer' }); // 'BOOK-1'
84
+ * ```
85
+ */
86
+ export declare function get<T extends object, P extends Path<T, O>, const O extends PathOptions>(obj: T, path: P, options: O): Get<T, P, O>;
87
+ /**
88
+ * Reads the value at a path only known at runtime, such as one coming from user input: the result is
89
+ * `unknown`.
90
+ *
91
+ * @example
92
+ * ```ts
93
+ * const value = get(data, error.instancePath, { notation: 'pointer' }); // unknown
94
+ * ```
95
+ */
96
+ export declare function get(obj: object, path: string, options?: PathOptions): unknown;
97
+ /**
98
+ * `true` when every key of `path` exists, even if the value there is `undefined`.
99
+ *
100
+ * @example
101
+ * ```ts
102
+ * has({ a: { b: undefined } }, 'a.b'); // true
103
+ * has({ a: {} }, 'a.b'); // false
104
+ * ```
105
+ */
106
+ export declare function has<T extends object, O extends PathOptions = {}>(obj: T, path: Path<T, O> | (string & {}), options?: O): boolean;
107
+ /**
108
+ * Sets the value at `path`, creating the missing objects (or arrays, for index keys) along the way, and
109
+ * returns `obj`, which is modified. The value is type-checked against the path.
110
+ *
111
+ * Paths with a `__proto__` segment are ignored; other keys are only ever created as own properties, so
112
+ * no path reaches `Object.prototype`.
113
+ *
114
+ * @example
115
+ * ```ts
116
+ * import { set } from 'flattify/path';
117
+ *
118
+ * const config: { db: { port: number } } = { db: { port: 5432 } };
119
+ * set(config, 'db.port', 6543);
120
+ * set(config, 'db.port', '6543'); // type error: string is not number
121
+ * ```
122
+ */
123
+ export declare function set<T extends object, P extends Path<T>>(obj: T, path: P, value: SetValue<T, P>): T;
124
+ /**
125
+ * Sets the value at `path`, written in another `delimiter` or `notation`, or with `object` and
126
+ * `arrayLimit` to choose what is created for missing keys.
127
+ *
128
+ * @example
129
+ * ```ts
130
+ * set(config, 'db__port', 6543, { delimiter: '__' });
131
+ * ```
132
+ */
133
+ export declare function set<T extends object, P extends Path<T, O>, const O extends SetOptions>(obj: T, path: P, value: SetValue<T, P, O>, options: O): T;
134
+ /**
135
+ * Deletes the key at `path` and returns `true`, or `false` when there was nothing to delete. Array
136
+ * elements are deleted in place, leaving a hole, as `delete` does.
137
+ *
138
+ * @example
139
+ * ```ts
140
+ * const user = { name: 'Ada', password: 'secret' };
141
+ * del(user, 'password'); // true, user is { name: 'Ada' }
142
+ * ```
143
+ */
144
+ export declare function del<T extends object, O extends PathOptions = {}>(obj: T, path: Path<T, O> | (string & {}), options?: O): boolean;
145
+ /**
146
+ * The path of every value `flatten` would produce, in the same order.
147
+ *
148
+ * @example
149
+ * ```ts
150
+ * paths({ user: { name: 'Ada', tags: ['admin'] } });
151
+ * // ['user.name', 'user.tags.0']
152
+ * ```
153
+ */
154
+ export declare function paths<T extends object>(obj: T): Extract<keyof Flatten<T>, string>[];
155
+ /**
156
+ * The paths `flatten(obj, options)` produces, with the same options.
157
+ *
158
+ * @example
159
+ * ```ts
160
+ * paths({ user: { tags: ['admin'] } }, { notation: 'bracket' }); // ['user.tags[0]']
161
+ * ```
162
+ */
163
+ export declare function paths<T extends object, const O extends FlattenOptions>(obj: T, options: O): Extract<keyof Flatten<T, O>, string>[];
164
+ type ContextOf<O> = {
165
+ delimiter: Option<O, "delimiter", ".">;
166
+ notation: Option<O, "notation", "dot">;
167
+ escape: Option<O, "escape", true>;
168
+ };
169
+ type ParsedPath<P extends string, O> = string extends P ? string[] : ContextOf<O> extends (infer C extends PathContext) ? (string extends C["delimiter"] ? string[] : Segments<P, C>) : string[];
170
+ /**
171
+ * Splits a path into its keys, reading escapes and brackets.
172
+ *
173
+ * @example
174
+ * ```ts
175
+ * parsePath('user.tags.0'); // ['user', 'tags', '0']
176
+ * parsePath('a\\.b.c'); // ['a.b', 'c']
177
+ * parsePath('items[0][id]', { notation: 'bracket' }); // ['items', '0', 'id']
178
+ * ```
179
+ */
180
+ export declare function parsePath<const P extends string, const O extends PathOptions = {}>(path: P, options?: O): ParsedPath<P, O>;
181
+ /**
182
+ * Joins keys into a path, escaping them when needed: the reverse of `parsePath`. In bracket notation,
183
+ * keys that are array indices are written between brackets.
184
+ *
185
+ * @example
186
+ * ```ts
187
+ * stringifyPath(['user', 'first.name']); // 'user.first\\.name'
188
+ * stringifyPath(['items', '0', 'id'], { notation: 'bracket' }); // 'items[0].id'
189
+ * stringifyPath(['a/b', 'c'], { notation: 'pointer' }); // '/a~1b/c'
190
+ * ```
191
+ */
192
+ export declare function stringifyPath(keys: readonly (string | number)[], options?: PathOptions): string;
193
+ /**
194
+ * Escapes a single key so it can be put in a path as it is.
195
+ *
196
+ * @example
197
+ * ```ts
198
+ * `user.${escapeKey('first.name')}`; // 'user.first\\.name'
199
+ * escapeKey('a/b', { notation: 'pointer' }); // 'a~1b'
200
+ * ```
201
+ */
202
+ export declare function escapeKey(key: string, options?: PathOptions): string;
203
+ //#endregion
204
+ export type { Get, Notation, Path, PathOptions, SetOptions, SetValue };