hanzio 2.1.0 → 3.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kristoffer Hansen
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -52,6 +52,15 @@ subpath export:
52
52
  `scripts/verify-exports.mjs` imports every entry above from the packed tarball
53
53
  in CI, so this table and `package.json#exports` can't drift apart.
54
54
 
55
+ ## Migrating to 3.0
56
+
57
+ - `typedSwitch<Constraint>(…)` is removed. The explicit type argument switched
58
+ off inference, so those calls checked neither exhaustiveness nor, in object
59
+ mode, the return type. Annotate the result instead:
60
+ `const result: HasId = typedSwitch(status, { … })`.
61
+ - `typedSwitch` rejects case keys that aren't values of the switched union. A
62
+ typo used to compile and fall through to the default handler.
63
+
55
64
  ## Migrating to 2.0
56
65
 
57
66
  - Subpath-only modules are no longer re-exported from `hanzio`. Change
@@ -479,12 +488,13 @@ Validators run in order: `globalValidator`, `validators[toState]`, then
479
488
 
480
489
  ### typedSwitch
481
490
 
482
- `typedSwitch` is an exhaustive switch helper for string unions and discriminated
483
- unions (string, number or boolean discriminants). `assertNever` covers regular
484
- `switch` statements. See the [typedSwitch docs](src/typedswitch/README.md).
491
+ `typedSwitch` is an exhaustive switch helper for string, number and boolean
492
+ values and for discriminated unions. `typedSwitchGroup` lets several cases share
493
+ one handler. `assertNever` covers regular `switch` statements. See the
494
+ [typedSwitch docs](src/typedswitch/README.md).
485
495
 
486
496
  ```ts
487
- import { assertNever, typedSwitch } from 'hanzio'
497
+ import { assertNever, typedSwitch, typedSwitchGroup } from 'hanzio'
488
498
 
489
499
  type Event =
490
500
  | { type: 'click'; x: number; y: number }
@@ -501,6 +511,11 @@ const text = typedSwitch(response as Response, 'code', {
501
511
  404: () => 'Not found'
502
512
  })
503
513
 
514
+ const event = { type: 'scroll', offset: 4 } as Event
515
+ typedSwitch(event, 'type', {
516
+ ...typedSwitchGroup(event, 'type', ['click', 'scroll'], (e) => e.type)
517
+ })
518
+
504
519
  function area(shape: Shape) {
505
520
  switch (shape.kind) {
506
521
  case 'circle':
@@ -1156,9 +1171,8 @@ bun run build
1156
1171
 
1157
1172
  ## Releasing
1158
1173
 
1159
- Releases are cut by [Release Please](https://github.com/googleapis/release-please)
1160
- from squash-merged PR titles written as conventional commits. `feat:` bumps the
1161
- minor version, `fix:` the patch, `feat!:` or a `BREAKING CHANGE:` footer the
1162
- major. `chore:`, `ci:`, `docs:`, `refactor:` and `test:` do not release. Each
1163
- merge to main updates a release PR; merging that PR tags the version and
1164
- publishes to npm. Nobody runs `npm publish` locally.
1174
+ Squash PRs with conventional titles (`fix:`, `feat:`, or `feat!:`). Release Please keeps the version and changelog in a release PR; merge that PR to publish with release notes and npm provenance. See [release and recovery instructions](docs/releasing.md).
1175
+
1176
+ ## License
1177
+
1178
+ [MIT](LICENSE).
@@ -1,10 +1,11 @@
1
1
  import type { z } from 'zod';
2
- import type { ApiEndpoint } from './types';
2
+ import type { ApiEndpoint, CheckResponseContext } from './types';
3
3
  /**
4
4
  * Defines an endpoint with full inference, as an alternative to
5
5
  * `satisfies ApiEndpoint`: `resFormatter` must return what `resSchema`
6
- * accepts, and a literal `path` types its `:params` (making `reqParams`
7
- * required when there's no `reqParamsSchema`).
6
+ * accepts, `checkResponse` receives the parsed `resSchema` output, and a
7
+ * literal `path` types its `:params` (making `reqParams` required when
8
+ * there's no `reqParamsSchema`).
8
9
  *
9
10
  * @example
10
11
  * export const usersGet = defineEndpoint({
@@ -13,6 +14,8 @@ import type { ApiEndpoint } from './types';
13
14
  * resSchema: User
14
15
  * })
15
16
  */
16
- export declare function defineEndpoint<const TEndpoint extends ApiEndpoint>(endpoint: TEndpoint & {
17
- resFormatter?: (data: unknown, headers: Record<string, string>) => z.input<TEndpoint['resSchema']>;
17
+ export declare function defineEndpoint<const TEndpoint extends Omit<ApiEndpoint, 'checkResponse'>, TRes extends z.ZodType = TEndpoint['resSchema']>(endpoint: TEndpoint & {
18
+ resSchema: TRes;
19
+ resFormatter?: (data: unknown, headers: Record<string, string>) => z.input<TRes>;
20
+ checkResponse?: ((data: z.output<TRes>, context: CheckResponseContext) => void | Promise<void>) | false;
18
21
  }): TEndpoint;
@@ -49,6 +49,7 @@ export declare function makeRequestWithRetry<TValidated>(args: MakeRequestArgs<T
49
49
  export declare function validateAndTransformResponse<T extends z.ZodType>(endpoint: ApiEndpoint<z.ZodType | undefined, z.ZodType | undefined, z.ZodType | undefined, z.ZodType | undefined, T>, response: Response, ctx: (over?: Partial<ApiErrorContext>) => ApiErrorContext): Promise<{
50
50
  data: z.infer<T>;
51
51
  responseSizeBytes: number;
52
+ headers: Record<string, string>;
52
53
  }>;
53
54
  export declare function defaultShouldRetry(ctx: RetryContext): boolean;
54
55
  export {};
@@ -17,6 +17,11 @@ export interface ApiEndpoint<TReqBody extends z.ZodType | undefined = z.ZodType
17
17
  resFormatter?: (data: unknown, headers: Record<string, string>) => z.input<TResponse>;
18
18
  reqDefaultQueryParams?: QueryParams;
19
19
  doNotEncodeQueryParams?: boolean;
20
+ /**
21
+ * Replaces the client's `checkResponse` for this endpoint; `false` skips it.
22
+ * `defineEndpoint` types `data` as the parsed `resSchema` output.
23
+ */
24
+ checkResponse?: ((data: any, context: CheckResponseContext) => void | Promise<void>) | false;
20
25
  }
21
26
  export interface ApiWrapperResponse<T> {
22
27
  data: T;
@@ -25,6 +30,8 @@ export interface ApiWrapperResponse<T> {
25
30
  responseTimeMs: number;
26
31
  httpStatus: number;
27
32
  retryCount: number;
33
+ /** Response headers of the final attempt, keyed by lowercase name. */
34
+ headers: Record<string, string>;
28
35
  }
29
36
  export type RetryContext = {
30
37
  error?: unknown;
@@ -1006,7 +1006,7 @@ async function validateAndTransformResponse(endpoint, response, ctx) {
1006
1006
  }
1007
1007
  const transformedData = endpoint.resFormatter ? endpoint.resFormatter(responseData, responseHeaders) : responseData;
1008
1008
  const data = await validateResponse(endpoint.resSchema, transformedData, ctx);
1009
- return { data, responseSizeBytes };
1009
+ return { data, responseSizeBytes, headers: responseHeaders };
1010
1010
  }
1011
1011
  function defaultShouldRetry2(ctx) {
1012
1012
  if (ctx.error)
@@ -1170,14 +1170,16 @@ function createApiClientImpl(apiConfig) {
1170
1170
  responseSizeMb: result.validatedData.responseSizeBytes / (1024 * 1024),
1171
1171
  responseTimeMs: elapsed(),
1172
1172
  httpStatus: result.httpStatus,
1173
- retryCount: result.retryCount
1173
+ retryCount: result.retryCount,
1174
+ headers: result.validatedData.headers
1174
1175
  };
1175
1176
  };
1176
1177
  const runCheckResponse = async (data, httpStatus, attempt) => {
1177
- if (!apiConfig.checkResponse)
1178
+ const checkResponse = endpoint.checkResponse === undefined ? apiConfig.checkResponse : endpoint.checkResponse;
1179
+ if (!checkResponse)
1178
1180
  return;
1179
1181
  try {
1180
- await apiConfig.checkResponse(data, {
1182
+ await checkResponse(data, {
1181
1183
  endpoint: endpointName,
1182
1184
  method: endpoint.method,
1183
1185
  url: fullUrl,
@@ -28,7 +28,7 @@ import {
28
28
  paginate2,
29
29
  otelMiddleware2,
30
30
  defineEndpoint2
31
- } from "../../index-j1ybktbr.js";
31
+ } from "../../index-zbj9s3s3.js";
32
32
  export {
33
33
  ActionError2 as ActionError,
34
34
  ApiError2 as ApiError,
package/dist/src/index.js CHANGED
@@ -90,8 +90,8 @@ function typedSwitch(value, keyOrCases, casesOrDefault, defaultCase) {
90
90
  let cases;
91
91
  let defaultHandler;
92
92
  let discriminantKey;
93
- if (typeof value === "string") {
94
- key = value;
93
+ if (typeof value !== "object") {
94
+ key = String(value);
95
95
  cases = keyOrCases;
96
96
  defaultHandler = casesOrDefault;
97
97
  } else {
@@ -119,6 +119,11 @@ function typedSwitch(value, keyOrCases, casesOrDefault, defaultCase) {
119
119
  const contextSuffix = discriminantKey ? ` (discriminant key: "${discriminantKey}")` : "";
120
120
  throw new Error(`Unhandled case: ${key}${contextSuffix}.${availableCasesSuffix}`);
121
121
  }
122
+ function typedSwitchGroup(_value, keyOrKeys, keysOrHandler, handler) {
123
+ const keys = handler ? keysOrHandler : keyOrKeys;
124
+ const shared = handler ?? keysOrHandler;
125
+ return Object.fromEntries(keys.map((key) => [String(key), shared]));
126
+ }
122
127
  function assertNever(value, message) {
123
128
  throw new Error(message ?? `Unexpected value: ${String(value)}`);
124
129
  }
@@ -1093,6 +1098,7 @@ export {
1093
1098
  typedFromEntries,
1094
1099
  typedKeys,
1095
1100
  typedSwitch,
1101
+ typedSwitchGroup,
1096
1102
  unwrapResult2 as unwrapResult,
1097
1103
  withAlpha,
1098
1104
  withTimeout2 as withTimeout
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  HttpResponseError2,
3
3
  createApiClient2
4
- } from "../../index-j1ybktbr.js";
4
+ } from "../../index-zbj9s3s3.js";
5
5
  import {
6
6
  getViteDefine2,
7
7
  viteSecretSetPlugin2
@@ -3,7 +3,8 @@
3
3
  *
4
4
  * Supports two input modes:
5
5
  *
6
- * 1. STRING INPUT - switch on a string/enum value directly:
6
+ * 1. PLAIN VALUE INPUT - switch on a string, number or boolean value directly.
7
+ * Cases are keyed by `String(value)`:
7
8
  *
8
9
  * @example
9
10
  * const status: 'success' | 'error' = 'success'
@@ -19,6 +20,9 @@
19
20
  * success: (val) => 'handled success',
20
21
  * }, (val) => 'default handler')
21
22
  *
23
+ * typedSwitch(code, { 200: (c) => 'ok', 404: (c) => 'missing' }) // c: 200, 404
24
+ * typedSwitch(flag, { true: () => 'on', false: () => 'off' })
25
+ *
22
26
  *
23
27
  * 2. OBJECT INPUT - switch on a discriminated union with custom key:
24
28
  *
@@ -46,20 +50,27 @@
46
50
  * })
47
51
  *
48
52
  *
49
- * 3. WITH CONSTRAINT - use `typedSwitch<T>` to enforce return type:
53
+ * 3. GROUPED CASES - share one handler between several values with
54
+ * `typedSwitchGroup`. The handler receives the union of the grouped
55
+ * members, and the spread keeps exhaustiveness and return type inference:
50
56
  *
51
57
  * @example
52
- * interface HasId { id: string }
58
+ * typedSwitch(event, 'type', {
59
+ * ...typedSwitchGroup(event, 'type', ['click', 'scroll'], (e) => e.type), // e: ClickEvent | ScrollEvent
60
+ * key: (e) => e.key,
61
+ * })
53
62
  *
54
- * // All handlers must return something with { id: string }
55
- * typedSwitch<HasId>(status, {
56
- * success: () => ({ id: '123', name: 'John' }), // ✓ OK
57
- * error: () => ({ id: '456' }), // ✓ OK
63
+ * typedSwitch(status, {
64
+ * ...typedSwitchGroup(status, ['success', 'pending'], (s) => 'fine'), // s: 'success' | 'pending'
65
+ * error: () => 'failed',
58
66
  * })
59
67
  *
60
- * // Type error - missing 'id' property
61
- * typedSwitch<HasId>(status, {
62
- * success: () => ({ name: 'John' }), // ✗ Error!
68
+ *
69
+ * 4. ENFORCING A RETURN TYPE - annotate the result:
70
+ *
71
+ * @example
72
+ * const result: { id: string } = typedSwitch(status, {
73
+ * success: () => ({ id: '123' }),
63
74
  * error: () => ({ id: '456' }),
64
75
  * })
65
76
  */
@@ -95,30 +106,40 @@ type PartialObjectCases<T, K extends keyof T, R> = {
95
106
  export type ObjectSwitchCases<T, K extends keyof T, R> = T[K] extends Discriminant ? ObjectCases<T, K, R | Promise<R>> : never;
96
107
  /** Partial cases for object input with custom key (when default is provided) */
97
108
  export type PartialObjectSwitchCases<T, K extends keyof T, R> = T[K] extends Discriminant ? PartialObjectCases<T, K, R | Promise<R>> : never;
98
- export declare function typedSwitch<T extends string, Cases extends {
99
- [K in T]: (value: K) => unknown;
100
- }>(value: T, cases: Cases): RawCasesReturnType<Cases>;
101
- export declare function typedSwitch<T extends string, Cases extends {
102
- [K in T]?: (value: K) => unknown;
103
- }, DefaultCase extends (value: Exclude<T, HandledCaseKeys<Cases>>) => unknown>(value: T, cases: Cases, defaultCase: DefaultCase): RawCasesReturnType<Cases> | RawHandlerReturnType<DefaultCase>;
104
- export declare function typedSwitch<T extends object, K extends keyof T, Cases extends ObjectCases<T, K, unknown>>(value: T, key: K, cases: Cases): RawCasesReturnType<Cases>;
105
- export declare function typedSwitch<T extends object, K extends keyof T, Cases extends PartialObjectCases<T, K, unknown>, DefaultCase extends (value: Exclude<T, Record<K, ValuesForKeys<T[K], HandledCaseKeys<Cases>>>>) => unknown>(value: T, key: K, cases: Cases, defaultCase: DefaultCase): RawCasesReturnType<Cases> | RawHandlerReturnType<DefaultCase>;
106
- export declare function typedSwitch<Constraint, T extends string = string>(value: T, cases: {
107
- [K in T]: (value: K) => Constraint;
108
- }): Constraint;
109
- export declare function typedSwitch<Constraint, T extends string = string>(value: T, cases: {
110
- [K in T]: (value: K) => Constraint | Promise<Constraint>;
111
- }): Constraint | Promise<Constraint>;
112
- export declare function typedSwitch<Constraint, T extends string = string>(value: T, cases: {
113
- [K in T]?: (value: K) => Constraint;
114
- }, defaultCase: (value: T) => Constraint): Constraint;
115
- export declare function typedSwitch<Constraint, T extends string = string>(value: T, cases: {
116
- [K in T]?: (value: K) => Constraint | Promise<Constraint>;
117
- }, defaultCase: (value: T) => Constraint | Promise<Constraint>): Constraint | Promise<Constraint>;
118
- export declare function typedSwitch<Constraint, T extends Record<string, unknown> = Record<string, unknown>, K extends keyof T = keyof T>(value: T, key: K, cases: ObjectCases<T, K, Constraint>): Constraint;
119
- export declare function typedSwitch<Constraint, T extends Record<string, unknown> = Record<string, unknown>, K extends keyof T = keyof T>(value: T, key: K, cases: ObjectCases<T, K, Constraint | Promise<Constraint>>): Constraint | Promise<Constraint>;
120
- export declare function typedSwitch<Constraint, T extends Record<string, unknown> = Record<string, unknown>, K extends keyof T = keyof T>(value: T, key: K, cases: PartialObjectCases<T, K, Constraint>, defaultCase: (value: T) => Constraint): Constraint;
121
- export declare function typedSwitch<Constraint, T extends Record<string, unknown> = Record<string, unknown>, K extends keyof T = keyof T>(value: T, key: K, cases: PartialObjectCases<T, K, Constraint | Promise<Constraint>>, defaultCase: (value: T) => Constraint | Promise<Constraint>): Constraint | Promise<Constraint>;
109
+ /**
110
+ * Rejects case keys that are not values of the switched union, so a typo
111
+ * fails to compile instead of silently falling through to the default.
112
+ */
113
+ type NoUnknownCases<Cases, Allowed extends string> = {
114
+ [P in keyof Cases as `${P & (string | number)}` extends Allowed ? never : P]: never;
115
+ };
116
+ export declare function typedSwitch<T extends Discriminant, Cases extends {
117
+ [V in T as `${V}`]: (value: V) => unknown;
118
+ } & NoUnknownCases<Cases, `${T}`>>(value: T, cases: Cases): RawCasesReturnType<Cases>;
119
+ export declare function typedSwitch<T extends Discriminant, Cases extends {
120
+ [V in T as `${V}`]?: (value: V) => unknown;
121
+ } & NoUnknownCases<Cases, `${T}`>, DefaultCase extends (value: Exclude<T, ValuesForKeys<T, HandledCaseKeys<Cases>>>) => unknown>(value: T, cases: Cases, defaultCase: DefaultCase): RawCasesReturnType<Cases> | RawHandlerReturnType<DefaultCase>;
122
+ export declare function typedSwitch<T extends object, K extends keyof T, Cases extends ObjectCases<T, K, unknown> & NoUnknownCases<Cases, `${Extract<T[K], Discriminant>}`>>(value: T, key: K, cases: Cases): RawCasesReturnType<Cases>;
123
+ export declare function typedSwitch<T extends object, K extends keyof T, Cases extends PartialObjectCases<T, K, unknown> & NoUnknownCases<Cases, `${Extract<T[K], Discriminant>}`>, DefaultCase extends (value: Exclude<T, Record<K, ValuesForKeys<T[K], HandledCaseKeys<Cases>>>>) => unknown>(value: T, key: K, cases: Cases, defaultCase: DefaultCase): RawCasesReturnType<Cases> | RawHandlerReturnType<DefaultCase>;
124
+ /**
125
+ * Builds cases that share one handler, for spreading into `typedSwitch` cases.
126
+ * Pass the switched value so its type is inferred; the handler receives the
127
+ * union of the grouped members. A case listed after the spread replaces the
128
+ * grouped handler for that key; listing it before the spread is a type error.
129
+ * If two groups list the same key, the later group wins.
130
+ *
131
+ * @example
132
+ * typedSwitch(event, 'type', {
133
+ * ...typedSwitchGroup(event, 'type', ['click', 'scroll'], (e) => e.type),
134
+ * key: (e) => e.key,
135
+ * })
136
+ */
137
+ export declare function typedSwitchGroup<T extends Discriminant, const Keys extends readonly T[], R>(value: T, keys: Keys, handler: (value: Keys[number]) => R): {
138
+ [V in Keys[number] as `${V}`]: (value: V) => R;
139
+ };
140
+ export declare function typedSwitchGroup<T extends object, K extends keyof T, const Keys extends readonly Extract<T[K], Discriminant>[], R>(value: T, key: K, keys: Keys, handler: (value: Extract<T, Record<K, Keys[number]>>) => R): {
141
+ [V in Keys[number] as `${V}`]: (value: Extract<T, Record<K, V>>) => R;
142
+ };
122
143
  /**
123
144
  * Exhaustiveness helper for regular `switch` statements. Place it in the
124
145
  * `default` branch: it only type-checks when every case has been handled, and
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hanzio",
3
- "version": "2.1.0",
3
+ "version": "3.0.0",
4
4
  "description": "A lightweight set of utility functions for TypeScript",
5
5
  "type": "module",
6
6
  "module": "./dist/src/index.js",
@@ -25,6 +25,8 @@
25
25
  },
26
26
  "files": [
27
27
  "src/**/*.ts",
28
+ "src/**/README.md",
29
+ "src/api-wrapper/SKILL.md",
28
30
  "dist",
29
31
  "!src/**/*.test.ts"
30
32
  ],
@@ -132,7 +134,8 @@
132
134
  "typecheck": "tsgo --noEmit",
133
135
  "prepare": "husky",
134
136
  "test:secrets:runtime": "bun run build && node scripts/verify-secrets.mjs",
135
- "test:exports": "bun run build && node scripts/verify-exports.mjs"
137
+ "test:exports": "bun run build && node scripts/verify-exports.mjs",
138
+ "verify:package": "node scripts/verify-package.mjs"
136
139
  },
137
140
  "devDependencies": {
138
141
  "@biomejs/biome": "^2.4.6",
@@ -152,5 +155,10 @@
152
155
  "zod": {
153
156
  "optional": true
154
157
  }
155
- }
158
+ },
159
+ "homepage": "https://github.com/HansKristoffer/hanzio#readme",
160
+ "bugs": {
161
+ "url": "https://github.com/HansKristoffer/hanzio/issues"
162
+ },
163
+ "packageManager": "bun@1.4.2"
156
164
  }