@zgeoff/std 0.1.1 → 0.3.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/README.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # @zgeoff/std
2
2
 
3
3
  Small, dependency-free TypeScript helpers that more than one zgeoff repo needs. Each helper is one
4
- file with its test beside it, exported from the package root, and named by the shared function-verb
5
- rules.
4
+ file with its test beside it, exported from the package root, and named by the shared
5
+ function-naming rules.
6
6
 
7
7
  ## Install
8
8
 
@@ -48,3 +48,91 @@ import { isRecord } from '@zgeoff/std';
48
48
  const parsed: unknown = JSON.parse(text);
49
49
  const name = isRecord(parsed) ? parsed['name'] : undefined;
50
50
  ```
51
+
52
+ ### `isOneOf`
53
+
54
+ Tells whether a value is one of a list of values, and narrows it to the list's element type, so a
55
+ string read from outside the program becomes a literal union without a cast. It compares with
56
+ `Array.prototype.includes`, so `NaN` matches `NaN`.
57
+
58
+ ```ts
59
+ import { isOneOf } from '@zgeoff/std';
60
+
61
+ const sizes = ['small', 'large'] as const;
62
+
63
+ const size = isOneOf(input, sizes) ? input : 'small';
64
+ ```
65
+
66
+ ## Typed helpers
67
+
68
+ Each helper in this section holds the one type assertion that its job needs, because TypeScript
69
+ cannot prove the type it returns. `toExactOptional` holds one for the same reason. The assertion
70
+ carries an approved disable comment, so code that calls the helper needs no assertion of its own.
71
+
72
+ ### `machineTypes`
73
+
74
+ Returns the `types` value of an xstate `setup()` or `createMachine()` call. xstate reads `types`
75
+ only at compile time, and its documentation fills it with `{} as X`. The type argument names only
76
+ the keys xstate reads from `types`, such as `context`, `events`, `input` and `actors`, so a key
77
+ outside that set fails the type check. A key left out keeps xstate's default.
78
+
79
+ ```ts
80
+ import { machineTypes } from '@zgeoff/std';
81
+ import { setup } from 'xstate';
82
+
83
+ const doorMachine = setup({
84
+ types: machineTypes<{ context: { opens: number }; events: { type: 'open' } }>(),
85
+ }).createMachine({ context: { opens: 0 } });
86
+ ```
87
+
88
+ ### `pick`
89
+
90
+ Returns a copy of an object with only the listed keys, typed as `Pick<T, K>`. A listed key that the
91
+ object lacks stays out of the copy, so an optional key never holds an explicit `undefined`.
92
+
93
+ ```ts
94
+ import { pick } from '@zgeoff/std';
95
+
96
+ const summary = pick(order, ['id', 'total']);
97
+ ```
98
+
99
+ ### `mergeDeep`
100
+
101
+ Merges a deep partial of an object over the whole object and returns a new object of the same type.
102
+ A plain object in the patch merges key by key over an object in the base, at the root or nested, and
103
+ the result keeps the base object's prototype, so a class instance stays one. An array, a function, a
104
+ `Date`, a `RegExp`, a `Map`, a `Set` or a `Promise` replaces the base value whole. The base and the
105
+ patch stay untouched. The `PartialDeep<T>` type describes the patch.
106
+
107
+ ```ts
108
+ import { mergeDeep } from '@zgeoff/std';
109
+
110
+ const settings = mergeDeep(defaultSettings, { theme: { size: 14 } });
111
+ ```
112
+
113
+ ### `toTagged`
114
+
115
+ Returns a string, number or bigint typed as a tagged type, such as type-fest's
116
+ `Tagged<string, 'OrderID'>`. It takes the untagged base type and refuses a type that carries no tag,
117
+ such as a literal union, so it never narrows a value to a set of literals.
118
+
119
+ ```ts
120
+ import { toTagged } from '@zgeoff/std';
121
+ import type { Tagged } from 'type-fest';
122
+
123
+ type OrderID = Tagged<string, 'OrderID'>;
124
+
125
+ const orderID = toTagged<OrderID>(crypto.randomUUID());
126
+ ```
127
+
128
+ ### `toReadonlyDeep`
129
+
130
+ Returns a value unchanged, typed as `ReadonlyDeep<T>`: every nested key readonly, an array as a
131
+ readonly array, a `Map` as a `ReadonlyMap` and a `Set` as a `ReadonlySet`. It freezes nothing at run
132
+ time. A function, a `Date`, a `RegExp` and a `Promise` keep their own type.
133
+
134
+ ```ts
135
+ import { toReadonlyDeep } from '@zgeoff/std';
136
+
137
+ const config = toReadonlyDeep(parseConfig(text));
138
+ ```
package/dist/index.d.ts CHANGED
@@ -1,2 +1,8 @@
1
+ export { isOneOf } from './is-one-of.ts';
1
2
  export { isRecord } from './is-record.ts';
3
+ export { type MachineTypeKey, machineTypes } from './machine-types.ts';
4
+ export { mergeDeep, type PartialDeep } from './merge-deep.ts';
5
+ export { pick } from './pick.ts';
2
6
  export { type ExactOptional, toExactOptional } from './to-exact-optional.ts';
7
+ export { type ReadonlyDeep, toReadonlyDeep } from './to-readonly-deep.ts';
8
+ export { toTagged } from './to-tagged.ts';
@@ -0,0 +1 @@
1
+ export declare function isOneOf<const T extends readonly unknown[]>(value: unknown, options: T): value is T[number];
@@ -0,0 +1,4 @@
1
+ export type MachineTypeKey = 'context' | 'events' | 'children' | 'tags' | 'input' | 'output' | 'emitted' | 'meta' | 'transitionMeta' | 'actors' | 'actions' | 'guards' | 'delays';
2
+ type MachineTypeSpec = Partial<Readonly<Record<MachineTypeKey, unknown>>>;
3
+ export declare function machineTypes<T extends MachineTypeSpec & Record<Exclude<keyof T, MachineTypeKey>, never>>(): T;
4
+ export {};
@@ -0,0 +1,6 @@
1
+ type WholeValue = readonly unknown[] | ((...args: never[]) => unknown) | Date | RegExp | ReadonlyMap<unknown, unknown> | ReadonlySet<unknown> | Promise<unknown>;
2
+ export type PartialDeep<T> = T extends WholeValue ? T : T extends object ? {
3
+ [K in keyof T]?: PartialDeep<T[K]>;
4
+ } : T;
5
+ export declare function mergeDeep<T extends object>(base: T, patch: PartialDeep<T>): T;
6
+ export {};
package/dist/pick.d.ts ADDED
@@ -0,0 +1 @@
1
+ export declare function pick<T extends object, K extends keyof T>(value: T, keys: readonly K[]): Pick<T, K>;
@@ -0,0 +1,6 @@
1
+ type OpaqueValue = ((...args: never[]) => unknown) | Date | RegExp | Promise<unknown>;
2
+ export type ReadonlyDeep<T> = T extends OpaqueValue ? T : T extends ReadonlyMap<infer Key, infer Item> ? ReadonlyMap<ReadonlyDeep<Key>, ReadonlyDeep<Item>> : T extends ReadonlySet<infer Item> ? ReadonlySet<ReadonlyDeep<Item>> : T extends object ? {
3
+ readonly [K in keyof T]: ReadonlyDeep<T[K]>;
4
+ } : T;
5
+ export declare function toReadonlyDeep<T>(value: T): ReadonlyDeep<T>;
6
+ export {};
@@ -0,0 +1,6 @@
1
+ type TaggedBase = string | number | bigint;
2
+ type Untagged<T> = T extends string ? string : T extends number ? number : T extends bigint ? bigint : never;
3
+ type TagKey<T> = Exclude<keyof T, keyof Untagged<T>>;
4
+ type TaggedSource<T> = [TagKey<T>] extends [never] ? never : Untagged<T> & Pick<T, TagKey<T>> extends T ? Untagged<T> : never;
5
+ export declare function toTagged<T extends TaggedBase>(value: TaggedSource<T>): T;
6
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zgeoff/std",
3
- "version": "0.1.1",
3
+ "version": "0.3.0",
4
4
  "description": "Small, dependency-free TypeScript helpers shared across the zgeoff repos",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -30,7 +30,9 @@
30
30
  },
31
31
  "devDependencies": {
32
32
  "@types/bun": "1.4.2",
33
- "typescript": "7.0.2"
33
+ "type-fest": "5.10.0",
34
+ "typescript": "7.0.2",
35
+ "xstate": "5.33.2"
34
36
  },
35
37
  "engines": {
36
38
  "bun": ">=1.3"
package/src/index.ts CHANGED
@@ -1,2 +1,8 @@
1
+ export { isOneOf } from './is-one-of.ts';
1
2
  export { isRecord } from './is-record.ts';
3
+ export { type MachineTypeKey, machineTypes } from './machine-types.ts';
4
+ export { mergeDeep, type PartialDeep } from './merge-deep.ts';
5
+ export { pick } from './pick.ts';
2
6
  export { type ExactOptional, toExactOptional } from './to-exact-optional.ts';
7
+ export { type ReadonlyDeep, toReadonlyDeep } from './to-readonly-deep.ts';
8
+ export { toTagged } from './to-tagged.ts';
@@ -0,0 +1,6 @@
1
+ export function isOneOf<const T extends readonly unknown[]>(
2
+ value: unknown,
3
+ options: T,
4
+ ): value is T[number] {
5
+ return options.includes(value);
6
+ }
@@ -0,0 +1,24 @@
1
+ // The keys xstate reads from `types` in setup() and in createMachine().
2
+ export type MachineTypeKey =
3
+ | 'context'
4
+ | 'events'
5
+ | 'children'
6
+ | 'tags'
7
+ | 'input'
8
+ | 'output'
9
+ | 'emitted'
10
+ | 'meta'
11
+ | 'transitionMeta'
12
+ | 'actors'
13
+ | 'actions'
14
+ | 'guards'
15
+ | 'delays';
16
+
17
+ type MachineTypeSpec = Partial<Readonly<Record<MachineTypeKey, unknown>>>;
18
+
19
+ export function machineTypes<
20
+ T extends MachineTypeSpec & Record<Exclude<keyof T, MachineTypeKey>, never>,
21
+ >(): T {
22
+ // oxlint-disable-next-line typescript/consistent-type-assertions -- approved GEO-1460: xstate v5 documents only `{} as X` for setup({ types }), and reads the value only at compile time
23
+ return {} as T;
24
+ }
@@ -0,0 +1,74 @@
1
+ import { types } from 'node:util';
2
+
3
+ // A value the merge replaces whole rather than merging key by key.
4
+ type WholeValue =
5
+ | readonly unknown[]
6
+ | ((...args: never[]) => unknown)
7
+ | Date
8
+ | RegExp
9
+ | ReadonlyMap<unknown, unknown>
10
+ | ReadonlySet<unknown>
11
+ | Promise<unknown>;
12
+
13
+ export type PartialDeep<T> = T extends WholeValue
14
+ ? T
15
+ : T extends object
16
+ ? { [K in keyof T]?: PartialDeep<T[K]> }
17
+ : T;
18
+
19
+ export function mergeDeep<T extends object>(base: T, patch: PartialDeep<T>): T {
20
+ // oxlint-disable-next-line typescript/consistent-type-assertions -- approved GEO-1460: TypeScript cannot prove that a deep partial merged over T gives T
21
+ return mergeValues(base, patch) as T;
22
+ }
23
+
24
+ function mergeValues(base: unknown, patch: unknown): unknown {
25
+ return isMergeable(base) && isPlainObject(patch) ? mergeRecords(base, patch) : patch;
26
+ }
27
+
28
+ function isMergeable(value: unknown): value is object {
29
+ return (
30
+ typeof value === 'object' &&
31
+ value !== null &&
32
+ !Array.isArray(value) &&
33
+ !types.isDate(value) &&
34
+ !types.isRegExp(value) &&
35
+ !types.isMap(value) &&
36
+ !types.isSet(value) &&
37
+ !types.isPromise(value)
38
+ );
39
+ }
40
+
41
+ function isPlainObject(value: unknown): value is object {
42
+ if (typeof value !== 'object' || value === null) {
43
+ return false;
44
+ }
45
+
46
+ const prototype: unknown = Object.getPrototypeOf(value);
47
+
48
+ return prototype === Object.prototype || prototype === null;
49
+ }
50
+
51
+ function mergeRecords(base: object, patch: object): object {
52
+ const merged: object = { ...base };
53
+
54
+ Reflect.setPrototypeOf(merged, Reflect.getPrototypeOf(base));
55
+
56
+ for (const key of Reflect.ownKeys(patch)) {
57
+ if (Object.prototype.propertyIsEnumerable.call(patch, key)) {
58
+ const current: unknown = Object.getOwnPropertyDescriptor(merged, key)?.value;
59
+ const next: unknown = Reflect.get(patch, key);
60
+ const value = mergeValues(current, next);
61
+
62
+ // an assignment to a `__proto__` key calls the inherited setter and
63
+ // replaces the prototype, so each key is defined as an own data property
64
+ Object.defineProperty(merged, key, {
65
+ value,
66
+ writable: true,
67
+ enumerable: true,
68
+ configurable: true,
69
+ });
70
+ }
71
+ }
72
+
73
+ return merged;
74
+ }
package/src/pick.ts ADDED
@@ -0,0 +1,9 @@
1
+ export function pick<T extends object, K extends keyof T>(
2
+ value: T,
3
+ keys: readonly K[],
4
+ ): Pick<T, K> {
5
+ const entries = keys.filter((key) => key in value).map((key): [K, T[K]] => [key, value[key]]);
6
+
7
+ // oxlint-disable-next-line typescript/consistent-type-assertions -- approved GEO-1460: Object.fromEntries loses key types inside a generic
8
+ return Object.fromEntries(entries) as Pick<T, K>;
9
+ }
@@ -25,6 +25,6 @@ export function toExactOptional<T extends object>(value: T): ExactOptional<T> {
25
25
  .map((key): [PropertyKey, unknown] => [key, Reflect.get(value, key)])
26
26
  .filter(([, entry]) => entry !== undefined);
27
27
 
28
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the filter above is what makes the keys optional; the type system cannot follow it
28
+ // oxlint-disable-next-line typescript/consistent-type-assertions -- approved GEO-1460: Object.fromEntries loses key types inside a generic
29
29
  return Object.fromEntries(entries) as ExactOptional<T>;
30
30
  }
@@ -0,0 +1,17 @@
1
+ // A value whose own methods a readonly mapped type would break.
2
+ type OpaqueValue = ((...args: never[]) => unknown) | Date | RegExp | Promise<unknown>;
3
+
4
+ export type ReadonlyDeep<T> = T extends OpaqueValue
5
+ ? T
6
+ : T extends ReadonlyMap<infer Key, infer Item>
7
+ ? ReadonlyMap<ReadonlyDeep<Key>, ReadonlyDeep<Item>>
8
+ : T extends ReadonlySet<infer Item>
9
+ ? ReadonlySet<ReadonlyDeep<Item>>
10
+ : T extends object
11
+ ? { readonly [K in keyof T]: ReadonlyDeep<T[K]> }
12
+ : T;
13
+
14
+ export function toReadonlyDeep<T>(value: T): ReadonlyDeep<T> {
15
+ // oxlint-disable-next-line typescript/consistent-type-assertions -- approved GEO-1460: TypeScript cannot resolve the conditional type inside the generic
16
+ return value as ReadonlyDeep<T>;
17
+ }
@@ -0,0 +1,24 @@
1
+ type TaggedBase = string | number | bigint;
2
+
3
+ type Untagged<T> = T extends string
4
+ ? string
5
+ : T extends number
6
+ ? number
7
+ : T extends bigint
8
+ ? bigint
9
+ : never;
10
+
11
+ type TagKey<T> = Exclude<keyof T, keyof Untagged<T>>;
12
+
13
+ type TaggedSource<T> = [TagKey<T>] extends [never]
14
+ ? never
15
+ : Untagged<T> & Pick<T, TagKey<T>> extends T
16
+ ? Untagged<T>
17
+ : never;
18
+
19
+ export function toTagged<T extends TaggedBase>(value: TaggedSource<T>): T {
20
+ const untagged: unknown = value;
21
+
22
+ // oxlint-disable-next-line typescript/consistent-type-assertions -- approved GEO-1460: a type-fest Tagged value cannot be made without a cast
23
+ return untagged as T;
24
+ }