@tolki/types 1.5.0 → 1.7.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tolki/types",
3
- "version": "1.5.0",
3
+ "version": "1.7.0",
4
4
  "description": "Utility TypeScript types for @tolki packages and Laravel HTTP responses.",
5
5
  "author": "Abraham Arango <https://github.com/abetwothree>",
6
6
  "license": "MIT",
package/src/arrays.d.ts CHANGED
@@ -64,6 +64,18 @@ export type UndotResult<
64
64
  ? UndotValue<TValue>[]
65
65
  : TValue[];
66
66
 
67
+ /**
68
+ * Key shape accepted by `Arr.undot`: either a bare numeric index (`0`, `"0"`)
69
+ * or a dot-path whose first segment is numeric (`"0.1"`, `"12.foo"`). A
70
+ * string-first-segment key like `"user.languages.0"` belongs to `Obj.undot`
71
+ * instead — this type rejects it at compile time rather than at runtime.
72
+ *
73
+ * @example
74
+ * UndotArrayKey // matches: 0, "0", "1.2", "3.foo.bar"
75
+ * UndotArrayKey // rejects: "foo", "user.languages.0"
76
+ */
77
+ export type UndotArrayKey = number | `${number}` | `${number}.${string}`;
78
+
67
79
  /**
68
80
  * Helper type to check if an array is mutable (not readonly)
69
81
  */
@@ -83,3 +95,41 @@ export type AddToArray<T extends unknown[], V> =
83
95
  ? Array<U | V>
84
96
  : never
85
97
  : never;
98
+
99
+ /**
100
+ * Removes `null` from an array's element type.
101
+ * Used by helpers that filter null values out of an array.
102
+ *
103
+ * @example
104
+ * NonNullableArray<(string | null)[]> // string[]
105
+ * NonNullableArray<string[]> // string[]
106
+ */
107
+ export type NonNullableArray<T extends readonly unknown[]> =
108
+ T extends readonly (infer U)[] ? Exclude<U, null>[] : never;
109
+
110
+ /**
111
+ * Removes the values PHP treats as falsy from an array's element type.
112
+ *
113
+ * @example
114
+ * TruthyArray<(string | null | undefined)[]> // string[]
115
+ * TruthyArray<(number | false)[]> // number[]
116
+ */
117
+ export type TruthyArray<T extends readonly unknown[]> =
118
+ T extends readonly (infer U)[]
119
+ ? Exclude<U, null | undefined | false | 0 | "">[]
120
+ : never;
121
+
122
+ /**
123
+ * A single sort descriptor accepted by array sort helpers.
124
+ *
125
+ * - a dot-notated key path, sorted ascending
126
+ * - a `[key]` single-element tuple, identical to a bare key path, ascending
127
+ * - a `[key, direction]` tuple: `true`/`'asc'`/`"Ascending"` sorts ascending,
128
+ * everything else descending, mirroring `Collection::sortByMany`
129
+ * - a comparator returning a negative, zero, or positive number
130
+ */
131
+ export type SortSpec<TValue> =
132
+ | string
133
+ | readonly [string]
134
+ | readonly [string, boolean | "Ascending" | "Descending" | "asc" | "desc"]
135
+ | ((a: TValue, b: TValue) => number);
@@ -1,2 +1,2 @@
1
- export type ProxyTarget = this;
1
+ export type ProxyTarget = object;
2
2
  export type PropertyName = string | symbol;
package/src/data.d.ts CHANGED
@@ -1,3 +1,8 @@
1
+ /**
2
+ * Data that is either a list or a keyed record. Use it for an implementation signature only:
3
+ * as a return type it is a union, so it can only ever be a lower bound and erases the
4
+ * per-shape type the `@tolki/arr` and `@tolki/obj` helpers compute.
5
+ */
1
6
  export type DataItems<TValue, TKey extends PropertyKey = PropertyKey> =
2
7
  | TValue[]
3
8
  | Record<TKey, TValue>;
@@ -6,6 +11,11 @@ export type DataItems<TValue, TKey extends PropertyKey = PropertyKey> =
6
11
  * Data that may also be supplied as one of the iterable structures that stand
7
12
  * in for a PHP `iterable`: a Map for keyed items, or any other iterable such
8
13
  * as a generator or a Set for positional items.
14
+ *
15
+ * No `src/` file references it today; it is kept for `@tolki/collection`, whose constructor
16
+ * and `getArrayableItems` accept exactly this set, and it names the shape `@tolki/data`'s
17
+ * type tests measure their own widened rows against. Deleting it would be a breaking change
18
+ * to a published package for no gain, so it stays until that consumer lands.
9
19
  */
10
20
  export type DataIterableItems<TValue, TKey extends PropertyKey = PropertyKey> =
11
21
  | DataItems<TValue, TKey>
package/src/objects.d.ts CHANGED
@@ -1,3 +1,6 @@
1
+ import type { ArrayInnerValue } from "./arrays";
2
+ import type { KnownObjectKeys } from "./path-resolve";
3
+
1
4
  /**
2
5
  * Helper type to add a key-value pair to an object type
3
6
  */
@@ -6,3 +9,661 @@ export type AddToObject<
6
9
  K extends PropertyKey,
7
10
  V,
8
11
  > = T & Record<K, V>;
12
+
13
+ /**
14
+ * Values the `@tolki/obj` helpers do not walk as objects: arrays, Maps, Sets, WeakMaps, WeakSets and functions.
15
+ * An overload taking this type first routes them to the untyped result instead of a misleading per-key type.
16
+ * A helper that walks a Map declares its Map rows first; this type's row then gives `Map | string[]` its widest result.
17
+ */
18
+ export type NonObjectItems =
19
+ | readonly unknown[]
20
+ | ReadonlyMap<unknown, unknown>
21
+ | ReadonlySet<unknown>
22
+ | WeakMap<object, unknown>
23
+ | WeakSet<object>
24
+ | ((...args: never[]) => unknown);
25
+
26
+ /**
27
+ * `NonObjectItems` without the Map, for an obj helper's empty-result row, so `Map | string[]` is not typed as empty.
28
+ *
29
+ * @remarks A Map keyed by `unknown`, `any` or an object type still fits the `WeakMap` member, so a union
30
+ * holding it beside another of these values is typed as empty, though its Map is walked.
31
+ */
32
+ export type NonKeyedItems = Exclude<
33
+ NonObjectItems,
34
+ ReadonlyMap<unknown, unknown>
35
+ >;
36
+
37
+ /**
38
+ * Flattens an intersection into a single object type, so hovers and exact
39
+ * type assertions see plain properties.
40
+ *
41
+ * @example
42
+ * Simplify<{ a: 1 } & { b: 2 }> // { a: 1; b: 2 }
43
+ */
44
+ export type Simplify<T> = { [K in keyof T]: T[K] } & {};
45
+
46
+ /**
47
+ * Converts a union to an intersection.
48
+ *
49
+ * @example
50
+ * UnionToIntersection<{ a: 1 } | { b: 2 }> // { a: 1 } & { b: 2 }
51
+ */
52
+ export type UnionToIntersection<U> = (
53
+ U extends unknown ? (value: U) => void : never
54
+ ) extends (value: infer I) => void
55
+ ? I
56
+ : never;
57
+
58
+ /**
59
+ * The union of an object's value types.
60
+ *
61
+ * @example
62
+ * ObjectValue<{ a: number; b: string }> // number | string
63
+ */
64
+ export type ObjectValue<T> = T[keyof T];
65
+
66
+ /**
67
+ * The key PHP stores for an array key: a canonical decimal integer string
68
+ * becomes a number, every other string stays a string.
69
+ *
70
+ * @example
71
+ * PhpArrayKey<"10"> // 10
72
+ * PhpArrayKey<"-1"> // -1
73
+ * PhpArrayKey<"01"> // "01"
74
+ * PhpArrayKey<"1.5"> // "1.5"
75
+ */
76
+ export type PhpArrayKey<K> = K extends number
77
+ ? K
78
+ : K extends `${infer N extends number}`
79
+ ? K extends `${bigint}`
80
+ ? `${N}` extends K
81
+ ? N
82
+ : K
83
+ : K
84
+ : K extends string
85
+ ? string extends K
86
+ ? string | number
87
+ : K
88
+ : never;
89
+
90
+ /**
91
+ * The keys `@tolki/obj` reports for an object's own keys, the way PHP would:
92
+ * what `keys()` returns and what every callback receives as its key.
93
+ *
94
+ * @example
95
+ * ObjectKey<{ a: 1; 0: 2; "10": 3 }> // "a" | 0 | 10
96
+ */
97
+ export type ObjectKey<T> = PhpArrayKey<keyof T>;
98
+
99
+ /**
100
+ * The key `@tolki/obj` reports for a Map key: the key PHP stores for it, since a Map stands for a PHP array.
101
+ * A key that is not a string, number, boolean, `null` or `undefined` is stringified, typed `string | number`.
102
+ *
103
+ * @remarks An integer key, or a float's truncation, outside the safe integer range reaches callbacks and
104
+ * `keys()` as its decimal string, yet is typed `number`.
105
+ *
106
+ * @example
107
+ * MapArrayKey<"10"> // 10
108
+ * MapArrayKey<"01"> // "01"
109
+ * MapArrayKey<2> // 2
110
+ * MapArrayKey<1.5> // number
111
+ * MapArrayKey<true> // 1
112
+ * MapArrayKey<null> // ""
113
+ * MapArrayKey<object> // string | number
114
+ */
115
+ export type MapArrayKey<K> = K extends string
116
+ ? PhpArrayKey<K>
117
+ : K extends number
118
+ ? `${K}` extends `${bigint}`
119
+ ? K
120
+ : number
121
+ : K extends boolean
122
+ ? K extends true
123
+ ? 1
124
+ : 0
125
+ : K extends null | undefined
126
+ ? ""
127
+ : string | number;
128
+
129
+ /**
130
+ * The key a callback receives for an entry of `M`, a Map or a union holding Maps: each Map's
131
+ * `MapArrayKey`, and nothing for a member that is not a Map. It distributes over `M`, which
132
+ * a `ReadonlyMap<TKey, TValue>` parameter cannot do: TypeScript infers one `TKey` from a union
133
+ * of Maps, finds the other Map does not fit it, and skips the row.
134
+ *
135
+ * @example
136
+ * MapEntryKey<Map<"1" | "a", string>> // 1 | "a"
137
+ * MapEntryKey<Map<string, number> | Map<number, string>> // string | number
138
+ * MapEntryKey<Map<boolean, string> | undefined> // 0 | 1
139
+ */
140
+ export type MapEntryKey<M> =
141
+ M extends ReadonlyMap<infer K, unknown> ? MapArrayKey<K> : never;
142
+
143
+ /**
144
+ * The value an entry of `M`, a Map or a union holding Maps, holds: each Map's value type, and
145
+ * nothing for a member that is not a Map. Like `MapEntryKey`, it distributes over `M`.
146
+ *
147
+ * @example
148
+ * MapEntryValue<Map<number, string>> // string
149
+ * MapEntryValue<Map<string, number> | Map<number, string>> // number | string
150
+ * MapEntryValue<Map<number, string> | string[]> // string
151
+ */
152
+ export type MapEntryValue<M> =
153
+ M extends ReadonlyMap<unknown, infer V> ? V : never;
154
+
155
+ /**
156
+ * The `data` a Map row takes to read a union of Maps whole, for `MapEntryKey` and `MapEntryValue` to read.
157
+ * An `any` argument does not match it, so `any` reaches the per-key rows instead of reading as a Map.
158
+ *
159
+ * @remarks `TMap` must be a bare, unconstrained type parameter, or the `any` test lets `any` through. A Map typed
160
+ * by a caller's type parameter (`M extends Map<K, V>`) fails it too, so a `ReadonlyMap<TKey, TValue>` row goes first.
161
+ *
162
+ * @example
163
+ * declare function values<TMap>(data: MapData<TMap>): MapEntryValue<TMap>[];
164
+ * values(new Map([[2, "c"]]) as Map<number, string> | Map<string, boolean>); // (string | boolean)[]
165
+ * values(JSON.parse("{}")); // no match: any is turned away
166
+ */
167
+ export type MapData<TMap> = TMap &
168
+ ReadonlyMap<unknown, unknown> &
169
+ (0 extends 1 & TMap ? never : unknown);
170
+
171
+ /**
172
+ * The object an obj helper returns after renumbering integer-like keys: `T`
173
+ * itself when it has none, otherwise a record of its values.
174
+ *
175
+ * @example
176
+ * ReindexedObject<{ a: 1 }> // { a: 1 }
177
+ * ReindexedObject<{ 0: "x" }> // Record<string | number, "x">
178
+ */
179
+ export type ReindexedObject<T> = [
180
+ Extract<keyof T, number | `${number}`>,
181
+ ] extends [never]
182
+ ? T
183
+ : Record<string | number, ObjectValue<T>>;
184
+
185
+ type PhpFalsyValue = null | undefined | false | 0 | "";
186
+
187
+ /**
188
+ * The entries left after dropping PHP-falsy values: every key becomes
189
+ * optional, and a key whose type is only ever falsy is removed.
190
+ *
191
+ * @example
192
+ * TruthyObject<{ a: number; b: null; c: string }> // { a?: number; c?: string }
193
+ */
194
+ export type TruthyObject<T> = {
195
+ -readonly [K in keyof T as [Exclude<T[K], PhpFalsyValue>] extends [never]
196
+ ? never
197
+ : K]?: Exclude<T[K], PhpFalsyValue>;
198
+ };
199
+
200
+ /**
201
+ * The entries left after dropping `null` values: a key that may be `null`
202
+ * becomes optional, a key that is only `null` is removed.
203
+ *
204
+ * @example
205
+ * NonNullableObject<{ a: string | null; b: null; c: number }> // { a?: string; c: number }
206
+ */
207
+ export type NonNullableObject<T> = Simplify<
208
+ {
209
+ -readonly [K in keyof T as null extends T[K]
210
+ ? [Exclude<T[K], null>] extends [never]
211
+ ? never
212
+ : K
213
+ : never]?: Exclude<T[K], null>;
214
+ } & {
215
+ -readonly [K in keyof T as null extends T[K] ? never : K]: T[K];
216
+ }
217
+ >;
218
+
219
+ /**
220
+ * Swaps an object's keys and values, skipping values PHP could not use as a key.
221
+ *
222
+ * @example
223
+ * FlipObject<{ name: "taylor" }> // { taylor: "name" }
224
+ */
225
+ export type FlipObject<T> = {
226
+ -readonly [K in keyof T as T[K] extends string | number
227
+ ? `${T[K]}`
228
+ : never]: PhpArrayKey<K>;
229
+ };
230
+
231
+ /**
232
+ * Prefixes every string or numeric key of an object.
233
+ *
234
+ * @example
235
+ * PrefixKeys<{ a: 1 }, "item_"> // { item_a: 1 }
236
+ */
237
+ export type PrefixKeys<T, P extends string> = {
238
+ -readonly [K in keyof T as K extends string | number
239
+ ? `${P}${K}`
240
+ : never]: T[K];
241
+ };
242
+
243
+ type PlainObjectOf<T> = T extends NonObjectItems | null | undefined
244
+ ? never
245
+ : T extends object
246
+ ? T
247
+ : never;
248
+
249
+ /**
250
+ * The entries `arrayableItems()` reads from an operand: an Enumerable- or
251
+ * Arrayable-like object unwraps through `all()`, `toArray()` or `toJSON()`,
252
+ * a list or iterable is keyed by index, a Map by its keys, `null` and
253
+ * `undefined` are empty, and a scalar or function sits under key 0.
254
+ *
255
+ * @example
256
+ * ArrayableItems<{ all(): { a: number } }> // { a: number }
257
+ * ArrayableItems<string[]> // Record<number, string>
258
+ * ArrayableItems<null> // Record<never, never>
259
+ */
260
+ export type ArrayableItems<T> = unknown extends T
261
+ ? Record<string, unknown>
262
+ : T extends null | undefined
263
+ ? Record<never, never>
264
+ : T extends readonly unknown[]
265
+ ? Record<number, T[number]>
266
+ : T extends (...args: never[]) => unknown
267
+ ? { 0: T }
268
+ : T extends object
269
+ ? T extends { all: (...args: never[]) => infer R }
270
+ ? ArrayableItems<R>
271
+ : T extends { toArray: (...args: never[]) => infer R }
272
+ ? ArrayableItems<R>
273
+ : T extends { toJSON: (...args: never[]) => infer R }
274
+ ? ArrayableItems<R>
275
+ : T extends ReadonlyMap<infer K, infer V>
276
+ ? MapItems<K extends string | number ? K : string, V>
277
+ : T extends WeakMap<object, unknown> | WeakSet<object>
278
+ ? Record<never, never>
279
+ : T extends Iterable<infer V>
280
+ ? Record<number, V>
281
+ : T
282
+ : { 0: T };
283
+
284
+ /** A Map's entries as an object: `String(key)` holds each value, and a literal key may be absent. */
285
+ type MapItems<K extends string | number, V> = string extends K
286
+ ? Record<string, V>
287
+ : number extends K
288
+ ? Record<number, V>
289
+ : Partial<Record<K, V>>;
290
+
291
+ /**
292
+ * The own entries `{ ...value }` copies: a list's indices, and nothing from a Map, Set, Date, RegExp, Promise or
293
+ * function, none of which keeps its data in own enumerable keys.
294
+ */
295
+ export type SpreadItems<T> = T extends readonly unknown[]
296
+ ? Record<number, T[number]>
297
+ : T extends
298
+ | ReadonlyMap<unknown, unknown>
299
+ | ReadonlySet<unknown>
300
+ | WeakMap<object, unknown>
301
+ | WeakSet<object>
302
+ | Date
303
+ | RegExp
304
+ | Promise<unknown>
305
+ | ((...args: never[]) => unknown)
306
+ ? Record<never, never>
307
+ : T;
308
+
309
+ /** The keys `T` always has: declared, and not optional. */
310
+ type RequiredObjectKeys<T> = {
311
+ [K in KnownObjectKeys<T>]: T extends Record<K, unknown> ? K : never;
312
+ }[KnownObjectKeys<T>];
313
+
314
+ /** The key types `T`'s index signatures cover, such as `string` for `Record<string, V>`. */
315
+ type IndexKeyOf<T> = Exclude<keyof T, KnownObjectKeys<T>>;
316
+
317
+ /** Whether `T` always, maybe or never has key `K`; JS stores an integer key as a string. */
318
+ type KeyPresence<T, K> =
319
+ K extends RequiredObjectKeys<T>
320
+ ? "always"
321
+ : K extends keyof T
322
+ ? "maybe"
323
+ : K extends number
324
+ ? string extends IndexKeyOf<T>
325
+ ? "maybe"
326
+ : "never"
327
+ : K extends `${number}`
328
+ ? number extends IndexKeyOf<T>
329
+ ? "maybe"
330
+ : "never"
331
+ : "never";
332
+
333
+ /** The value `T` holds at key `K` when it has one; `never` when it cannot. */
334
+ type PresentValue<T, K> =
335
+ K extends KnownObjectKeys<T>
336
+ ? Required<T>[K & keyof T]
337
+ : KeyPresence<T, K> extends "never"
338
+ ? never
339
+ : Required<T>[IndexKeyOf<T> & keyof T];
340
+
341
+ /**
342
+ * A merge result: `V`'s entries, required where `L` or `W` always has the
343
+ * key, plus `L`'s and `W`'s index signatures, each holding `IV` and every
344
+ * entry of `V` whose key it covers.
345
+ */
346
+ type MergedEntries<L, W, V, IV> = Simplify<
347
+ {
348
+ [K in keyof V as "always" extends KeyPresence<L, K> | KeyPresence<W, K>
349
+ ? K
350
+ : never]: V[K];
351
+ } & {
352
+ [K in keyof V as "always" extends KeyPresence<L, K> | KeyPresence<W, K>
353
+ ? never
354
+ : K]?: V[K];
355
+ } & {
356
+ [P in IndexKeyOf<L> | IndexKeyOf<W>]:
357
+ | IV
358
+ | V[Extract<
359
+ keyof V,
360
+ string extends P
361
+ ? string | number
362
+ : number extends P
363
+ ? number | `${number}`
364
+ : P
365
+ >];
366
+ }
367
+ >;
368
+
369
+ /** `W`'s entries laid over `L`'s: `W` wins every key it has. */
370
+ type OverlayObjects<L, W> = L extends unknown
371
+ ? W extends unknown
372
+ ? MergedEntries<
373
+ L,
374
+ W,
375
+ {
376
+ [K in KnownObjectKeys<L> | KnownObjectKeys<W>]:
377
+ | (KeyPresence<W, K> extends "always"
378
+ ? never
379
+ : PresentValue<L, K>)
380
+ | PresentValue<W, K>;
381
+ },
382
+ PresentValue<L, IndexKeyOf<L>> | PresentValue<W, IndexKeyOf<W>>
383
+ >
384
+ : never
385
+ : never;
386
+
387
+ /** The entries a union's first operand, the data, holds itself: a list's indices or an object's own entries. */
388
+ type OwnItems<T> = T extends object ? SpreadItems<T> : Record<never, never>;
389
+
390
+ /** A union's operands after the first, each read the way `arrayableItems()` reads it; the left-most wins each key. */
391
+ type UnionOperands<T extends readonly unknown[]> = T extends readonly [
392
+ infer First,
393
+ ...infer Rest,
394
+ ]
395
+ ? unknown extends First
396
+ ? Record<string, unknown>
397
+ : OverlayObjects<UnionOperands<Rest>, ArrayableItems<First>>
398
+ : T extends readonly (infer E)[]
399
+ ? number extends T["length"]
400
+ ? Partial<ArrayableItems<E>>
401
+ : Record<never, never>
402
+ : Record<never, never>;
403
+
404
+ /**
405
+ * Merges a tuple of operands with the left-most winning each key, the way
406
+ * PHP's `+` array union does. The first operand is the data, read by its own
407
+ * entries as `$this->items` is; each later one is read the way
408
+ * `arrayableItems()` reads it, so a Collection-like unwraps, a list adds its
409
+ * indices and a `null` adds nothing.
410
+ *
411
+ * @example
412
+ * MergeObjects<[{ a: 1 }, { a: 2; b: 3 }]> // { a: 1; b: 3 }
413
+ * MergeObjects<[{ a: 1 }, number[]]> // { [x: number]: number; a: 1 }
414
+ * MergeObjects<[{ all: () => 1 }, { b: 2 }]> // { all: () => 1; b: 2 }
415
+ */
416
+ export type MergeObjects<T extends readonly unknown[]> = T extends readonly [
417
+ infer First,
418
+ ...infer Rest,
419
+ ]
420
+ ? unknown extends First
421
+ ? Record<string, unknown>
422
+ : OverlayObjects<UnionOperands<Rest>, OwnItems<First>>
423
+ : T extends readonly (infer E)[]
424
+ ? number extends T["length"]
425
+ ? Partial<OwnItems<E> | ArrayableItems<E>>
426
+ : Record<never, never>
427
+ : Record<never, never>;
428
+
429
+ /**
430
+ * The object `{ ...T1, ...T2 }` produces: `T2`'s own entries laid over `T1`'s.
431
+ * A list spreads its indices, and a Map, Set or function spreads nothing.
432
+ *
433
+ * @example
434
+ * SpreadObjects<{ a: 1; b: 2 }, { b: "x" }> // { a: 1; b: "x" }
435
+ * SpreadObjects<{ a: 1 }, { a?: "x" }> // { a: 1 | "x" }
436
+ */
437
+ export type SpreadObjects<T1, T2> = OverlayObjects<
438
+ SpreadItems<T1>,
439
+ SpreadItems<T2>
440
+ >;
441
+
442
+ type ObjectDepth = [never, 0, 1, 2, 3, 4];
443
+
444
+ /**
445
+ * How `replaceRecursive` treats a value: a list, an object it merges into, or a leaf it replaces.
446
+ * A `Date`, `RegExp`, `Map`, `Set`, `WeakMap`, `WeakSet`, `Promise` or function is a leaf, as a PHP object is.
447
+ */
448
+ type MergeKind<T> = T extends readonly unknown[]
449
+ ? "list"
450
+ : T extends NonObjectItems | Date | RegExp | Promise<unknown>
451
+ ? "leaf"
452
+ : T extends object
453
+ ? "object"
454
+ : "leaf";
455
+
456
+ /** A merged object, or the list it becomes when its keys come out as `0..n-1`. */
457
+ type ListOrObject<M> = [
458
+ Exclude<RequiredObjectKeys<M>, number | `${number}`>,
459
+ ] extends [never]
460
+ ? M | ObjectValue<Required<M>>[]
461
+ : M;
462
+
463
+ /** What `replaceRecursive` stores when an existing value `A` meets a replacer value `B`. */
464
+ type DeepMergeValue<A, B, D extends number> = [D] extends [never]
465
+ ? unknown
466
+ : A extends unknown
467
+ ? B extends unknown
468
+ ? [MergeKind<A>, MergeKind<B>] extends ["object", "object"]
469
+ ? DeepMergeSpread<A, B, ObjectDepth[D]>
470
+ : [MergeKind<A>, MergeKind<B>] extends ["list", "list"]
471
+ ? (
472
+ | ArrayInnerValue<A>
473
+ | ArrayInnerValue<B>
474
+ | DeepMergeValue<
475
+ ArrayInnerValue<A>,
476
+ ArrayInnerValue<B>,
477
+ ObjectDepth[D]
478
+ >
479
+ )[]
480
+ : "leaf" extends MergeKind<A> | MergeKind<B>
481
+ ? B
482
+ : ListOrObject<DeepMergeSpread<A, B, ObjectDepth[D]>>
483
+ : never
484
+ : never;
485
+
486
+ /** A nested merge. Only the operand itself is unwrapped, so both sides are read as `{ ...value }` reads them. */
487
+ type DeepMergeSpread<A, B, D extends number> = [D] extends [never]
488
+ ? Record<string | number, unknown>
489
+ : DeepOverlayObjects<SpreadItems<A>, SpreadItems<B>, D>;
490
+
491
+ /** The value at key `K` after a merge: `L`'s alone, `W`'s alone, or both combined. */
492
+ type DeepOverlayValue<L, W, K, D extends number> =
493
+ | (KeyPresence<W, K> extends "always" ? never : PresentValue<L, K>)
494
+ | (KeyPresence<L, K> extends "always" ? never : PresentValue<W, K>)
495
+ | DeepMergeValue<PresentValue<L, K>, PresentValue<W, K>, D> extends infer V
496
+ ? V
497
+ : never;
498
+
499
+ /** `W`'s entries merged into `L`'s: a key both may hold gets `DeepOverlayValue`. */
500
+ type DeepOverlayObjects<L, W, D extends number> = L extends unknown
501
+ ? W extends unknown
502
+ ? MergedEntries<
503
+ L,
504
+ W,
505
+ {
506
+ [K in
507
+ | KnownObjectKeys<L>
508
+ | KnownObjectKeys<W>]: DeepOverlayValue<L, W, K, D>;
509
+ },
510
+ DeepOverlayValue<L, W, IndexKeyOf<L> | IndexKeyOf<W>, D>
511
+ >
512
+ : never
513
+ : never;
514
+
515
+ /**
516
+ * What `replaceRecursive(T1, T2)` returns. `T2` is read the way `arrayableItems()` reads it, but nothing nested is
517
+ * unwrapped; nested lists and plain objects merge by key, as two PHP arrays do, and a built-in object is a leaf.
518
+ * The runtime replaces a class instance whole too, but a type can't tell one from a plain object, so it merges.
519
+ *
520
+ * @example
521
+ * DeepMergeObjects<{ a: { x: 1 } }, { a: { y: 2 } }> // { a: { x: 1; y: 2 } }
522
+ * DeepMergeObjects<{ a: number[] }, { a: string[] }> // { a: (number | string)[] }
523
+ */
524
+ export type DeepMergeObjects<T1, T2, D extends number = 5> = [D] extends [never]
525
+ ? Record<string | number, unknown>
526
+ : DeepOverlayObjects<SpreadItems<T1>, ArrayableItems<T2>, D>;
527
+
528
+ /**
529
+ * The object produced by writing `V` at dot path `P`, creating nested objects
530
+ * for missing or non-object segments the way `Arr::set` creates arrays.
531
+ *
532
+ * @example
533
+ * SetObjectPath<Record<never, never>, "a.b", 1> // { a: { b: 1 } }
534
+ * SetObjectPath<{ a: { x: 1 } }, "a.y", 2> // { a: { x: 1; y: 2 } }
535
+ */
536
+ export type SetObjectPath<T, P extends string, V> = P extends keyof T
537
+ ? Simplify<Omit<T, P> & { [K in P]: V }>
538
+ : P extends `${infer Head}.${infer Rest}`
539
+ ? Simplify<
540
+ Omit<T, Head> & {
541
+ [K in Head]: SetObjectPath<
542
+ Head extends keyof T
543
+ ? [PlainObjectOf<T[Head]>] extends [never]
544
+ ? Record<never, never>
545
+ : PlainObjectOf<T[Head]>
546
+ : Record<never, never>,
547
+ Rest,
548
+ V
549
+ >;
550
+ }
551
+ >
552
+ : Simplify<Omit<T, P> & { [K in P]: V }>;
553
+
554
+ /**
555
+ * A value `undot` may produce from leaves of type `V`: the leaf itself, or a
556
+ * list or object nesting more of them.
557
+ */
558
+ export type UndotObjectValue<V> =
559
+ | V
560
+ | UndotObjectValue<V>[]
561
+ | { [key: string]: UndotObjectValue<V> };
562
+
563
+ /**
564
+ * The leaf values left after fully flattening nested arrays and objects the way `flatten()` does: a Collection-like
565
+ * value is read through `all()` first, and a `Date`, `RegExp`, `Map`, `Set`, `Promise` or function is a leaf.
566
+ * The runtime keeps a class instance whole too, but a type can't tell one from a plain object, so it walks it.
567
+ *
568
+ * @example
569
+ * ObjectFlatValue<{ a: [1, 2]; b: { c: "x" } }> // 1 | 2 | "x"
570
+ * ObjectFlatValue<{ a: { all(): number[] } }> // number
571
+ */
572
+ export type ObjectFlatValue<T, D extends number = 5> = [D] extends [never]
573
+ ? unknown
574
+ : FlatLeafValue<
575
+ T extends { all: (...args: never[]) => infer R } ? R : T,
576
+ D
577
+ >;
578
+
579
+ /** A value `flatten()` has read through `all()`: the leaves of a list or plain object, or the value itself. */
580
+ type FlatLeafValue<T, D extends number> = T extends readonly (infer E)[]
581
+ ? ObjectFlatValue<E, ObjectDepth[D]>
582
+ : MergeKind<T> extends "object"
583
+ ? [keyof T] extends [never]
584
+ ? unknown
585
+ : ObjectFlatValue<ObjectValue<T>, ObjectDepth[D]>
586
+ : T;
587
+
588
+ /**
589
+ * The object members of a resolved type, falling back to a loose record when
590
+ * it has none — `objectItem` throws for a non-object at runtime.
591
+ *
592
+ * @example
593
+ * EnsureObject<{ a: 1 } | null> // { a: 1 }
594
+ * EnsureObject<number> // Record<string, unknown>
595
+ */
596
+ export type EnsureObject<T> = [PlainObjectOf<T>] extends [never]
597
+ ? Record<string, unknown>
598
+ : PlainObjectOf<T>;
599
+
600
+ /**
601
+ * `T`'s string-keyed entries plus integer-keyed entries holding `V` or `T`'s own
602
+ * integer-keyed values, for helpers that renumber integer keys as they insert.
603
+ *
604
+ * @example
605
+ * RenumberedObject<{ b: 2 }, "x"> // { b: 2 } & Record<number, "x">
606
+ */
607
+ export type RenumberedObject<T, V> = Simplify<
608
+ Omit<T, Extract<keyof T, number | `${number}`>>
609
+ > &
610
+ Record<
611
+ number,
612
+ V | ObjectValue<Pick<T, Extract<keyof T, number | `${number}`>>>
613
+ >;
614
+
615
+ /**
616
+ * Every key of `T`, at every depth, made optional: what may remain after an
617
+ * unknown set of dot paths is removed.
618
+ *
619
+ * @example
620
+ * ObjectDeepPartial<{ a: { b: 1 } }> // { a?: { b?: 1 } }
621
+ */
622
+ export type ObjectDeepPartial<T, D extends number = 5> = [D] extends [never]
623
+ ? unknown
624
+ : [PlainObjectOf<T>] extends [never]
625
+ ? T
626
+ : { [K in keyof T]?: ObjectDeepPartial<T[K], ObjectDepth[D]> };
627
+
628
+ /**
629
+ * `T` with the value at dot path `P` removed: a declared key is omitted, a
630
+ * nested path omits its leaf, and a path `T` does not have leaves it unchanged.
631
+ *
632
+ * @example
633
+ * OmitObjectPath<{ a: 1; b: { c: 2; d: 3 } }, "b.c"> // { a: 1; b: { d: 3 } }
634
+ */
635
+ export type OmitObjectPath<T, P extends string> = string extends P
636
+ ? ObjectDeepPartial<T>
637
+ : P extends keyof T
638
+ ? Simplify<Omit<T, P>>
639
+ : P extends `${infer Head}.${infer Rest}`
640
+ ? Head extends keyof T
641
+ ? [PlainObjectOf<T[Head]>] extends [never]
642
+ ? T
643
+ : Simplify<
644
+ Omit<T, Head> & {
645
+ [K in keyof T as K extends Head ? K : never]:
646
+ | OmitObjectPath<NonNullable<T[K]>, Rest>
647
+ | Extract<T[K], null | undefined>;
648
+ }
649
+ >
650
+ : T
651
+ : T;
652
+
653
+ /**
654
+ * `T` with every dot path in the tuple `Ps` removed, left to right.
655
+ *
656
+ * @example
657
+ * OmitObjectPaths<{ a: 1; b: { c: 2 } }, ["a", "b.c"]> // { b: {} }
658
+ */
659
+ export type OmitObjectPaths<
660
+ T,
661
+ Ps extends readonly string[],
662
+ > = number extends Ps["length"]
663
+ ? ObjectDeepPartial<T>
664
+ : Ps extends readonly [
665
+ infer First extends string,
666
+ ...infer Rest extends readonly string[],
667
+ ]
668
+ ? OmitObjectPaths<OmitObjectPath<T, First>, Rest>
669
+ : T;
@@ -5,8 +5,11 @@ export type PathKey = number | string | null | undefined;
5
5
 
6
6
  /**
7
7
  * A set of keys used to access a path in an object or array.
8
+ *
9
+ * The array half is `readonly`, so a caller may hand over an `as const` tuple: nothing
10
+ * reading a key set writes to it.
8
11
  */
9
- export type PathKeys = number | string | null | undefined | Array<PathKey>;
12
+ export type PathKeys = number | string | null | undefined | readonly PathKey[];
10
13
 
11
14
  /**
12
15
  * Unwraps a value or function that returns a value.
@@ -202,9 +205,32 @@ export type IsLiteral<T> = string extends T
202
205
  */
203
206
  export type ArrayResolvePathOrNull<TArray extends readonly unknown[], TPath> =
204
207
  IsLiteral<TPath> extends true
205
- ? ArrayResolvePath<TArray, TPath, TArray[number]>
208
+ ? PathFallback<ArrayResolvePath<TArray, TPath, TArray[number]>, null>
206
209
  : ArrayResolvePath<TArray, TPath, TArray[number]> | null;
207
210
 
211
+ /**
212
+ * Swaps the `undefined` an optional intermediate segment leaves behind for the value
213
+ * the helper actually answers with.
214
+ *
215
+ * `{ a?: { b: string } }` resolved at `"a.b"` is `string | undefined`, because the
216
+ * optional `a` distributes through the walk. `Arr.get` never returns `undefined` for
217
+ * that path — it returns its default, `null` when none was given — so the resolved
218
+ * type must say so. A fully unresolved path is already `never` here and takes the
219
+ * fallback whole.
220
+ *
221
+ * @example
222
+ * ```ts
223
+ * type A = PathFallback<string | undefined, null>; // string | null
224
+ * type B = PathFallback<string, "D">; // string
225
+ * type C = PathFallback<never, "D">; // "D"
226
+ * ```
227
+ */
228
+ type PathFallback<TResolved, TFallback> = [TResolved] extends [never]
229
+ ? TFallback
230
+ : TResolved extends undefined
231
+ ? TFallback
232
+ : TResolved;
233
+
208
234
  /**
209
235
  * Resolves a path within an array and adds `| TDefault` only when the path
210
236
  * is non-literal (widened `string` or `number`), meaning it cannot be
@@ -232,7 +258,7 @@ export type ArrayResolvePathOrDefault<
232
258
  TDefault,
233
259
  > =
234
260
  IsLiteral<TPath> extends true
235
- ? ArrayResolvePath<TArray, TPath, TDefault>
261
+ ? PathFallback<ArrayResolvePath<TArray, TPath, TDefault>, TDefault>
236
262
  : ArrayResolvePath<TArray, TPath, TArray[number]> | TDefault;
237
263
 
238
264
  /**
@@ -261,3 +287,251 @@ export type GetFieldType<
261
287
  : R
262
288
  : TDefault
263
289
  : TDefault;
290
+
291
+ /**
292
+ * Resolves the value type produced by plucking `TPath` out of each element of
293
+ * an array. A `*` segment produces an array of the values found at that level.
294
+ * Non-literal paths resolve to `unknown`.
295
+ *
296
+ * The terminal (non-wildcard) arm maps `undefined` to `null`: at runtime,
297
+ * `resolvePluckPath` (arr.ts) substitutes `null` for any segment that
298
+ * resolves to `undefined` — including an absent optional property — so an
299
+ * optional property's type must be `T | null`, never `T | undefined`, to
300
+ * match what `pluck` actually returns.
301
+ *
302
+ * The same mapping applies to intermediate segments: an optional or
303
+ * nullable intermediate makes the whole resolved type nullable, because
304
+ * `resolvePluckPath` short-circuits to `null` the moment any segment is
305
+ * null or undefined.
306
+ *
307
+ * @example
308
+ * PluckValue<{ name: string }, "name"> // string
309
+ * PluckValue<{ user: { name: string } }, "user.name"> // string
310
+ * PluckValue<{ users: { first: string }[] }, "users.*.first"> // string[]
311
+ * PluckValue<{ name: string }, string> // unknown
312
+ * PluckValue<{ name?: string }, "name"> // string | null
313
+ * PluckValue<{ user?: { name: string } }, "user.name"> // string | null
314
+ */
315
+ export type PluckValue<TItem, TPath> =
316
+ TPath extends `${infer Head}.${infer Rest}`
317
+ ? Head extends "*"
318
+ ? TItem extends readonly (infer TElement)[]
319
+ ? PluckValue<TElement, Rest>[]
320
+ : unknown
321
+ : Head extends keyof TItem
322
+ ? null extends TItem[Head]
323
+ ? PluckValue<NonNullable<TItem[Head]>, Rest> | null
324
+ : undefined extends TItem[Head]
325
+ ? PluckValue<NonNullable<TItem[Head]>, Rest> | null
326
+ : PluckValue<TItem[Head], Rest>
327
+ : unknown
328
+ : TPath extends "*"
329
+ ? TItem extends readonly (infer TElement)[]
330
+ ? TElement[]
331
+ : unknown
332
+ : TPath extends keyof TItem
333
+ ? TItem[TPath] extends infer TResolved
334
+ ? TResolved extends undefined
335
+ ? null
336
+ : TResolved
337
+ : never
338
+ : unknown;
339
+
340
+ type ObjectPathDepth = [never, 0, 1, 2, 3, 4];
341
+
342
+ /** `T`'s declared keys, without its string, number or symbol index signatures. */
343
+ type KnownObjectKeys<T> = keyof {
344
+ [K in keyof T as string extends K
345
+ ? never
346
+ : number extends K
347
+ ? never
348
+ : symbol extends K
349
+ ? never
350
+ : K]: unknown;
351
+ };
352
+
353
+ /**
354
+ * Whether `T` is the bare `object` type: it names no key, yet any object's entries may sit behind it. `{}`, which a
355
+ * string also fits, is the type of an empty object literal, so it stays keyless.
356
+ */
357
+ type IsBareObject<T> = [keyof T] extends [never]
358
+ ? string extends T
359
+ ? false
360
+ : T extends (...args: never[]) => unknown
361
+ ? false
362
+ : true
363
+ : false;
364
+
365
+ /** One step through an index signature: always possibly missing. A numeric segment also reads a number index. */
366
+ type ObjectIndexStep<T, K extends string> = K extends keyof T
367
+ ? [T[K & keyof T], true]
368
+ : K extends `${infer N extends number}`
369
+ ? N extends keyof T
370
+ ? [T[N & keyof T], true]
371
+ : [never, true]
372
+ : [never, true];
373
+
374
+ /**
375
+ * Resolves one path segment to `[value, mayBeMissing]`. `get()` walks only objects and lists, so a scalar or function
376
+ * ends the path; a built-in object's members are mostly on its prototype, which `Object.hasOwn` doesn't see.
377
+ */
378
+ type ObjectPathStep<T, K extends string> = T extends readonly unknown[]
379
+ ? K extends `${infer N extends number}`
380
+ ? N extends KnownObjectKeys<T>
381
+ ? [T[N], false]
382
+ : [T[number], true]
383
+ : [never, true]
384
+ : T extends
385
+ | string
386
+ | number
387
+ | boolean
388
+ | bigint
389
+ | symbol
390
+ | ((...args: never[]) => unknown)
391
+ ? [never, true]
392
+ : T extends
393
+ | Date
394
+ | RegExp
395
+ | Promise<unknown>
396
+ | ReadonlyMap<unknown, unknown>
397
+ | ReadonlySet<unknown>
398
+ | WeakMap<object, unknown>
399
+ | WeakSet<object>
400
+ ? [T[K & keyof T], true]
401
+ : IsBareObject<T> extends true
402
+ ? [unknown, true]
403
+ : ObjectKeyStep<T, K>;
404
+
405
+ /** One segment through an object with declared keys or index signatures. */
406
+ type ObjectKeyStep<T, K extends string> =
407
+ K extends KnownObjectKeys<T>
408
+ ? [T[K], false]
409
+ : K extends `${infer N extends number}`
410
+ ? N extends KnownObjectKeys<T>
411
+ ? [T[N & keyof T], false]
412
+ : ObjectIndexStep<T, K>
413
+ : ObjectIndexStep<T, K>;
414
+
415
+ type ObjectSegmentMissing<V, M> = M extends true
416
+ ? true
417
+ : null extends V
418
+ ? true
419
+ : undefined extends V
420
+ ? true
421
+ : false;
422
+
423
+ /** Walks a dot path to `[resolvedValue, mayBeMissing]`. */
424
+ type ObjectPathWalk<
425
+ T,
426
+ P extends string,
427
+ > = P extends `${infer Head}.${infer Rest}`
428
+ ? ObjectPathStep<T, Head> extends [infer V, infer M]
429
+ ? unknown extends V
430
+ ? [unknown, true]
431
+ : [NonNullable<V>] extends [never]
432
+ ? [never, true]
433
+ : ObjectPathWalk<NonNullable<V>, Rest> extends [
434
+ infer RV,
435
+ infer RM,
436
+ ]
437
+ ? [RV, ObjectSegmentMissing<V, M> | RM]
438
+ : never
439
+ : never
440
+ : ObjectPathLeaf<T, P>;
441
+
442
+ /** A path's last segment: `[value, mayBeMissing]`, where an `undefined` value counts as missing. */
443
+ type ObjectPathLeaf<T, K extends string> =
444
+ ObjectPathStep<T, K> extends [infer V, infer M]
445
+ ? [
446
+ Exclude<V, undefined>,
447
+ M extends true ? true : undefined extends V ? true : false,
448
+ ]
449
+ : never;
450
+
451
+ /**
452
+ * A path from the top, the way `get()` reads it, for each member of `T`: a number key is one literal key and never
453
+ * walks, and a dotted path is read as one literal key first whenever `T` may hold it.
454
+ */
455
+ type ObjectPathTop<T, P> = T extends unknown
456
+ ? P extends number
457
+ ? ObjectPathLeaf<T, `${P}`>
458
+ : P extends `${string}.${string}`
459
+ ? ObjectPathLiteral<T, P> extends true
460
+ ? ObjectPathLeaf<T, P>
461
+ : ObjectPathLiteral<T, P> extends false
462
+ ? ObjectPathWalk<T, P>
463
+ : ObjectPathLeaf<T, P> | ObjectPathWalk<T, P>
464
+ : P extends string
465
+ ? ObjectPathWalk<T, P>
466
+ : never
467
+ : never;
468
+
469
+ /** Whether `get()` reads dotted path `P` as one literal key of `T`: always, never, or maybe (then it walks). */
470
+ type ObjectPathLiteral<T, P extends string> =
471
+ P extends KnownObjectKeys<T>
472
+ ? Record<never, never> extends Pick<T, P & keyof T>
473
+ ? boolean
474
+ : true
475
+ : string extends keyof T
476
+ ? boolean
477
+ : P extends `${number}`
478
+ ? number extends keyof T
479
+ ? boolean
480
+ : false
481
+ : false;
482
+
483
+ /**
484
+ * Every value a dot path through `T` can reach, to a bounded depth. Used when
485
+ * a path is a widened `string`, so it may address any node; past the depth
486
+ * bound it widens to `unknown`.
487
+ *
488
+ * @example
489
+ * ObjectPathValue<{ a: { b: number } }> // { b: number } | number
490
+ */
491
+ export type ObjectPathValue<T, D extends number = 5> = [D] extends [never]
492
+ ? unknown
493
+ : T extends readonly (infer E)[]
494
+ ?
495
+ | Exclude<E, undefined>
496
+ | ObjectPathValue<NonNullable<E>, ObjectPathDepth[D]>
497
+ : T extends (...args: never[]) => unknown
498
+ ? never
499
+ : T extends object
500
+ ? [keyof T] extends [never]
501
+ ? unknown
502
+ : {
503
+ [K in keyof T]-?:
504
+ | Exclude<T[K], undefined>
505
+ | ObjectPathValue<
506
+ NonNullable<T[K]>,
507
+ ObjectPathDepth[D]
508
+ >;
509
+ }[keyof T]
510
+ : never;
511
+
512
+ /**
513
+ * Resolves the value at a dot path within an object, adding `TDefault`
514
+ * exactly when the path may not exist: an optional or nullable segment, an
515
+ * index-signature key, an array index, or a key the type does not declare.
516
+ * A `null` leaf is returned as `null`, not the default, like `Arr::get`.
517
+ *
518
+ * Unlike {@link ArrayResolvePath}, a literal path is only trusted through
519
+ * declared keys: arrays have no declared indices, objects usually do. As in
520
+ * `get()`, a top-level key is read literally first, and a number key never walks.
521
+ *
522
+ * @example
523
+ * ObjectResolvePath<{ a: { b: number } }, "a.b"> // number
524
+ * ObjectResolvePath<{ a?: { b: number } }, "a.b"> // number | null
525
+ * ObjectResolvePath<Record<string, number>, "x", 0> // number | 0
526
+ * ObjectResolvePath<{ a: number }, null> // { a: number }
527
+ * ObjectResolvePath<{ a: { b: number } }, string> // { b: number } | number | null
528
+ */
529
+ export type ObjectResolvePath<T, P, TDefault = null> = P extends
530
+ | null
531
+ | undefined
532
+ ? T
533
+ : Record<never, never> extends Record<P & (string | number), unknown>
534
+ ? ObjectPathValue<T> | TDefault
535
+ : ObjectPathTop<T, P> extends [infer V, infer M]
536
+ ? V | (true extends M ? TDefault : never)
537
+ : TDefault;