hono-takibi 0.14.0 → 0.15.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
@@ -4,32 +4,30 @@
4
4
 
5
5
  ![img](https://raw.githubusercontent.com/nakita628/hono-takibi/refs/heads/main/assets/img/hono-takibi.png)
6
6
 
7
- **[Hono Takibi](https://www.npmjs.com/package/hono-takibi)** generates type-safe [Hono](https://hono.dev/) code from [OpenAPI](https://www.openapis.org/) / [TypeSpec](https://typespec.io/) specifications.
7
+ **[Hono Takibi](https://hono-takibi.dev/)** generates type-safe [Hono](https://hono.dev/) code from [OpenAPI](https://www.openapis.org/) / [TypeSpec](https://typespec.io/) specifications.
8
8
 
9
- - OpenAPI schemas to [Zod](https://zod.dev/) schemas
10
- - [@hono/zod-openapi](https://hono.dev/examples/zod-openapi) route definitions
11
- - App entry point + handler stubs + test files
12
- - Client library hooks (SWR, TanStack Query, Preact Query, Solid Query, Vue Query, Svelte Query, Angular Query)
13
- - RPC client, mock server, TypeScript types
14
- - API reference docs with [hono-cli](https://github.com/honojs/cli) commands
9
+ From one document it can generate:
15
10
 
16
- ## Quick Start
11
+ - [Zod](https://zod.dev/) schemas and [@hono/zod-openapi](https://hono.dev/examples/zod-openapi) route definitions
12
+ - App entry, handler stubs and test files
13
+ - RPC client and hooks for SWR, TanStack Query, Preact / Solid / Vue / Svelte / Angular Query
14
+ - Mock server, TypeScript types and API reference docs
15
+
16
+ 📖 **Documentation: [hono-takibi.dev](https://hono-takibi.dev/)** · 🔥 **[Playground](https://hono-takibi.dev/playground)**
17
17
 
18
- ### Installation
18
+ ## Quick Start
19
19
 
20
20
  ```bash
21
21
  npm install -D hono-takibi
22
22
  ```
23
23
 
24
- ### CLI
24
+ Pass an OpenAPI (`.yaml`, `.json`) or TypeSpec (`.tsp`) document and an output file:
25
25
 
26
26
  ```bash
27
- npx hono-takibi path/to/input.{yaml,json,tsp} -o path/to/output.ts
27
+ npx hono-takibi openapi.yaml -o src/routes.ts
28
28
  ```
29
29
 
30
- ### Configuration File
31
-
32
- Create `hono-takibi.config.ts`:
30
+ For anything beyond a single routes file, create `hono-takibi.config.ts`:
33
31
 
34
32
  ```ts
35
33
  import { defineConfig } from 'hono-takibi'
@@ -44,992 +42,21 @@ export default defineConfig({
44
42
  npx hono-takibi
45
43
  ```
46
44
 
47
- ### CLI Reference
48
-
49
- `hono-takibi --help`:
50
-
51
- ```
52
- DESCRIPTION
53
- Hono Takibi is a code generator from OpenAPI to @hono/zod-openapi
54
-
55
- USAGE
56
- hono-takibi [flags] [<input>]
57
-
58
- ARGUMENTS
59
- input input.{yaml,json,tsp} OpenAPI (.yaml, .json) or TypeSpec (.tsp) document to generate from (optional)
60
-
61
- FLAGS
62
- --output, -o output.ts TypeScript file the generated routes are written to
63
- --config, -c file Config file to run (default: ./hono-takibi.config.ts)
64
- --watch, -w Rerun the config on every change to its documents or itself
65
-
66
- GLOBAL FLAGS
67
- --help, -h Show help information
68
- --version, -v Show version information
69
- --wizard Start wizard mode for a command
70
- --completions <bash|zsh|fish|sh> Print shell completion script (choices: bash, zsh, fish, sh)
71
- --log-level <all|trace|debug|info|warn|warning|error|fatal|none> Sets the minimum log level (choices: all, trace, debug, info, warn, warning, error, fatal, none)
72
-
73
- EXAMPLES
74
- # Generate a single routes file
75
- hono-takibi openapi.yaml -o src/routes.ts
76
-
77
- # Run every generator declared in ./hono-takibi.config.ts
78
- hono-takibi
79
-
80
- # Run a config file from another location
81
- hono-takibi --config config/api.config.ts
82
-
83
- # Rerun on every change to the input documents or the config
84
- hono-takibi --watch
85
- ```
86
-
87
- With an `<input>` the CLI writes a single routes file, and `-o` is required. With no
88
- `<input>` it runs the config file, which opts in the routes, components, webhooks,
89
- types, mock, docs, test and tanstack-query generators. Paths inside a config file
90
- resolve against the current directory, so `--config` names where the config lives, not
91
- where its outputs land.
92
-
93
- ### Watch mode
94
-
95
- ```bash
96
- npx hono-takibi --watch
97
- ```
98
-
99
- Reruns the config on every change to the input documents or to the config itself, and
100
- keeps watching when a run fails. Pairs with `template`: add an operation and its handler
101
- stub appears, while the code already written into the existing handlers stays put.
102
-
103
- The whole directory holding the input document is watched, so a TypeSpec entry that
104
- imports its siblings and an external `$ref` both trigger a rerun.
105
-
106
- ### Example
107
-
108
- input:
109
-
110
- ```yaml
111
- openapi: 3.1.0
112
- info:
113
- title: Hono Takibi API
114
- version: '1.0.0'
115
- paths:
116
- /:
117
- get:
118
- summary: Welcome
119
- description: Returns a welcome message from Hono Takibi.
120
- responses:
121
- '200':
122
- description: OK
123
- content:
124
- application/json:
125
- schema:
126
- type: object
127
- properties:
128
- message:
129
- type: string
130
- example: Hono Takibi🔥
131
- required:
132
- - message
133
- ```
134
-
135
- output:
136
-
137
- ```ts
138
- import { createRoute, z } from '@hono/zod-openapi'
139
-
140
- export const getRoute = createRoute({
141
- method: 'get',
142
- path: '/',
143
- summary: 'Welcome',
144
- description: 'Returns a welcome message from Hono Takibi.',
145
- responses: {
146
- 200: {
147
- description: 'OK',
148
- content: {
149
- 'application/json': {
150
- schema: z
151
- .object({
152
- message: z.string().openapi({ example: 'Hono Takibi🔥' }),
153
- })
154
- .openapi({ required: ['message'] }),
155
- },
156
- },
157
- },
158
- },
159
- })
160
- ```
161
-
162
- ## Vite Plugin
163
-
164
- Watches your OpenAPI spec and `hono-takibi.config.ts` for changes, then auto-regenerates code on save.
165
-
166
- Requires `hono-takibi.config.ts` in your project root.
167
-
168
- ```ts
169
- // vite.config.ts
170
- import { honoTakibiVite } from 'hono-takibi/vite-plugin'
171
- import { defineConfig } from 'vite'
172
-
173
- export default defineConfig({
174
- plugins: [honoTakibiVite()],
175
- })
176
- ```
177
-
178
- ![](https://raw.githubusercontent.com/nakita628/hono-takibi/refs/heads/main/assets/vite/hono-takibi-vite.gif)
179
-
180
- ## Template & Test Generation
181
-
182
- Generate a complete app structure with handler stubs and test files:
183
-
184
- ```ts
185
- export default defineConfig({
186
- input: 'openapi.yaml',
187
- output: './src/routes.ts',
188
- template: {
189
- test: true,
190
- pathAlias: '@/',
191
- testFramework: 'bun', // "vitest" (default) | "vite-plus" | "bun"
192
- },
193
- })
194
- ```
195
-
196
- This generates:
197
-
198
- - `src/index.ts` - App entry point with route registrations
199
- - `src/handlers/*.ts` - Handler stubs, one file per tag (the first `tags` entry of each operation, lower camel case; the first path segment when an operation has no tag)
200
- - `src/handlers/*.test.ts` - Test files with `@faker-js/faker` mock data (imports from `vitest`, `vite-plus/test`, or `bun:test`)
201
-
202
- Re-running after updating your OpenAPI spec is safe — your hand-written handler logic and test customizations are preserved. Only new routes are added as stubs. The generator never deletes a file under `handlers/` and never re-stubs a handler that already exists in that directory: a handler you moved into another file (e.g. split by concern) is regenerated in place, files that hold no `*RouteHandler` export / `.openapi(xxxRoute)` registration / `*Route` export stay untouched, and their `export * from` lines in `handlers/index.ts` are kept. When a route leaves the spec, its handler declaration and route import are removed from whichever file holds them, but the file itself — and anything hand-written in it — remains; delete it by hand once nothing else is in it. Only top-level files in `handlers/` are scanned, not subdirectories.
203
-
204
- ### Handler Generation Modes
205
-
206
- #### `routeHandler: false` (default)
207
-
208
- Each handler creates its own sub-router and registers routes:
209
-
210
- ```ts
211
- // src/handlers/health.ts
212
- import { OpenAPIHono } from '@hono/zod-openapi'
213
- import { getHealthRoute } from '@/routes'
214
-
215
- const app = new OpenAPIHono()
216
-
217
- export const healthHandler = app.openapi(getHealthRoute, (c) => {})
218
- ```
219
-
220
- The app mounts handlers via `.route()`:
221
-
222
- ```ts
223
- // src/index.ts
224
- import { OpenAPIHono } from '@hono/zod-openapi'
225
- import { healthHandler } from './handlers'
226
-
227
- const app = new OpenAPIHono()
228
-
229
- export const api = app.route('/', healthHandler)
230
-
231
- export default app
232
- ```
233
-
234
- If you split routes into hand-written files in this mode, name each sub-router export `<fileBasename>Handler` (e.g. `export const sharesHandler = ...` in `shares.ts`) — that is the name the generator merges into and the app mounts.
235
-
236
- #### `routeHandler: true`
237
-
238
- Handlers export typed `RouteHandler` functions, and `index.ts` centralizes route registration:
239
-
240
- ```ts
241
- // src/handlers/health.ts
242
- import type { RouteHandler } from '@hono/zod-openapi'
243
- import type { getHealthRoute } from '../routes'
244
-
245
- export const getHealthRouteHandler: RouteHandler<typeof getHealthRoute> = async (c) => {}
246
- ```
247
-
248
- ```ts
249
- // src/index.ts
250
- import { OpenAPIHono } from '@hono/zod-openapi'
251
- import { getHealthRoute } from './routes'
252
- import { getHealthRouteHandler } from './handlers'
253
-
254
- const app = new OpenAPIHono()
255
-
256
- export const api = app.openapi(getHealthRoute, getHealthRouteHandler)
257
-
258
- export default app
259
- ```
260
-
261
- #### `define: true`
262
-
263
- ```ts
264
- export default defineConfig({
265
- input: 'openapi.yaml',
266
- template: { define: true },
267
- })
268
- ```
269
-
270
- ```ts
271
- // src/routes/users.ts
272
- export const getUsersIdRoute = defineOpenAPIRoute({
273
- route: createRoute({
274
- method: 'get',
275
- path: '/users/{id}',
276
- request: { params: z.object({ id: z.string() }) },
277
- responses: {
278
- 200: { description: 'ok', content: { 'application/json': { schema: UserSchema } } },
279
- },
280
- }),
281
- handler: async (c) => {},
282
- addRoute: true,
283
- })
284
- ```
285
-
286
- The app entry defaults to `src/index.ts` (override with `output`, which must be an `index.ts` path such as `./server/index.ts`). Route files always go to `routes/` next to the app entry, and component schemas to `components/index.ts` (override with `components.output`). When `output` is omitted, `components.output` also anchors the layout: `components: { output: './server/components/index.ts' }` puts the app entry at `server/index.ts` and routes at `server/routes/`.
287
-
288
- ## Client Library Integrations
289
-
290
- Supported: SWR, TanStack Query, Preact Query, Solid Query, Vue Query, Svelte Query, Angular Query, RPC Client.
291
-
292
- ```ts
293
- export default defineConfig({
294
- input: 'openapi.yaml',
295
- 'tanstack-query': {
296
- output: './src/tanstack-query.ts',
297
- import: '../lib',
298
- client: 'client',
299
- },
300
- })
301
- ```
302
-
303
- ### Infinite Query (`x-pagination`)
304
-
305
- Set `x-pagination: true` on a GET operation to generate infinite query hooks.
306
-
307
- ```yaml
308
- paths:
309
- /posts:
310
- get:
311
- x-pagination: true
312
- ```
313
-
314
- ### Generated hooks
315
-
316
- Every GET operation yields a key getter, an options factory, and a hook; every other method yields a mutation key getter, a `mutationOptions` factory, and a mutation hook.
317
-
318
- ```ts
319
- getUsersKey() // ['users'] — one per path prefix
320
- getUsersIdQueryKey(args) // ['users', '/users/:id', args] — header params are left out
321
- getItemsInfiniteQueryKey(args) // ['items', '/items', 'infinite', args]
322
- getPostUsersMutationKey() // ['users', '/users', 'POST']
323
-
324
- useUsersId(args, { query: { staleTime: 1_000 }, options: { headers } }, queryClient)
325
- usePostUsers({ mutation: { mutationKey: ['custom'], onSuccess } }, queryClient)
326
- ```
327
-
328
- - `options.query` is the library's options type without `queryKey` / `queryFn` (the hook supplies both); `options.mutation` leaves out `mutationFn`, and a `mutationKey` you pass wins over the generated one.
329
- - Query hooks spread their options factory, so `useUsersId(args, { query })` is `useQuery({ ...getUsersIdQueryOptions(args), ...query })`. The factories take the hooks' `<TData, TError>` (and `TPageParam` for infinite queries) for that reason; leave them off and a direct `getUsersIdQueryOptions(args)` call keeps the default types, ready for `prefetchQuery` / `getQueryData`. Vue Query hooks keep the inline form instead.
330
- - `options.options` is Hono's `ClientRequestOptions` (headers, fetch, init).
331
- - The trailing argument is the framework's own: a `QueryClient` (an accessor of one in Solid and Svelte), or `{ injector }` in Angular.
332
- - Vue hooks accept `Ref` / getter arguments and re-key the query when they change.
333
- - SWR mutations revalidate only their own key; pass `swrKey: getGetUsersKey()` to revalidate the list instead.
334
-
335
- ## Test & Mock Generation
336
-
337
- ### Test Generation
338
-
339
- ```ts
340
- export default defineConfig({
341
- input: 'openapi.yaml',
342
- test: {
343
- output: './src/test.ts',
344
- import: '.',
345
- testFramework: 'bun', // "vitest" (default) | "vite-plus" | "bun"
346
- },
347
- })
348
- ```
349
-
350
- ### Mock Server Generation
351
-
352
- ```ts
353
- export default defineConfig({
354
- input: 'openapi.yaml',
355
- mock: {
356
- output: './src/mock.ts',
357
- },
358
- })
359
- ```
360
-
361
- Each route answers its success response by default. Like [Prism](https://stoplight.io/open-source/prism), a request can pick any response or named example the document declares with the `Prefer` header (or the `__code` / `__example` query):
362
-
363
- ```bash
364
- curl -H 'Prefer: code=404' http://localhost:3000/orders/1 # the 404 response
365
- curl -H 'Prefer: example=pending' http://localhost:3000/orders/1 # a named example
366
- curl -H 'Prefer: code=404, example=gone' http://localhost:3000/orders/1
367
- curl 'http://localhost:3000/orders/1?__code=503'
368
- ```
369
-
370
- A code falls back to its `4XX` range, then `default`. A code or example the operation does not declare answers `500` with an `application/problem+json` body saying what is missing.
371
-
372
- ## API Reference Docs
373
-
374
- Generate API reference Markdown with [hono-cli](https://github.com/honojs/cli) `hono request` commands:
375
-
376
- ```ts
377
- export default defineConfig({
378
- input: 'openapi.yaml',
379
- docs: {
380
- output: './docs/api.md',
381
- entry: 'src/index.ts',
382
- },
383
- })
384
- ```
385
-
386
- Set `curl: true` with `baseUrl` to generate `curl` commands for a running server:
387
-
388
- ```ts
389
- export default defineConfig({
390
- input: 'openapi.yaml',
391
- docs: {
392
- output: './docs/api.md',
393
- curl: true,
394
- baseUrl: 'http://localhost:3000',
395
- },
396
- })
397
- ```
398
-
399
- ## Full Config Reference
400
-
401
- Some options are mutually exclusive: `output` ↔ `routes`, `template.define` ↔ `routes`, `components.output` ↔ per-type components, `template.define` ↔ `routeHandler`.
402
-
403
- Every generator needs its own `output` path. `routes`, `webhooks` and the
404
- `components.*` sections take `split`, and a split directory belongs to the generator —
405
- its `.ts` files are removed before each run, so keep hand-written code elsewhere. Every
406
- other generator, `rpc` and the client hooks included, writes a single file. `basePath`,
407
- `client` and `import` are checked here because they are spliced into the generated code
408
- verbatim.
409
-
410
- ```ts
411
- import { defineConfig } from 'hono-takibi'
412
-
413
- export default defineConfig({
414
- input: 'openapi.yaml',
415
-
416
- output: './src/routes.ts', // single-file mode; with template.define, the app entry (an index.ts path, default ./src/index.ts)
417
- basePath: '/api',
418
- readonly: true,
419
- // format: {}, // oxfmt FormatConfig
420
-
421
- template: {
422
- test: true,
423
- routeHandler: false, // true: RouteHandler exports
424
- define: false, // true: defineOpenAPIRoute output
425
- pathAlias: '@/',
426
- testFramework: 'vitest', // "vitest" | "vite-plus" | "bun"
427
- },
428
-
429
- exportSchemas: true,
430
- exportSchemasTypes: true,
431
- exportResponses: true,
432
- exportParameters: true,
433
- exportParametersTypes: true,
434
- exportExamples: true,
435
- exportRequestBodies: true,
436
- exportHeaders: true,
437
- exportHeadersTypes: true,
438
- exportSecuritySchemes: true,
439
- exportLinks: true,
440
- exportCallbacks: true,
441
- exportPathItems: true,
442
- exportMediaTypes: true,
443
- exportMediaTypesTypes: true,
45
+ ## Documentation
444
46
 
445
- routes: {
446
- output: './src/routes',
447
- split: true,
448
- import: '@packages/routes',
449
- },
450
-
451
- webhooks: {
452
- output: './src/webhooks',
453
- split: true,
454
- import: '@packages/webhooks',
455
- },
456
-
457
- // `output` (single file) and the per-type fields below (split) are mutually exclusive.
458
- // `exportTypes` applies only to schemas / parameters / headers / mediaTypes.
459
- components: {
460
- output: './src/components/index.ts',
461
-
462
- schemas: {
463
- output: './src/schemas',
464
- exportTypes: true,
465
- split: true,
466
- import: '../schemas',
467
- },
468
- responses: {
469
- output: './src/responses',
470
- split: true,
471
- import: '../responses',
472
- },
473
- parameters: {
474
- output: './src/parameters',
475
- exportTypes: true,
476
- split: true,
477
- import: '../parameters',
478
- },
479
- examples: {
480
- output: './src/examples',
481
- split: true,
482
- import: '../examples',
483
- },
484
- requestBodies: {
485
- output: './src/requestBodies',
486
- split: true,
487
- import: '../requestBodies',
488
- },
489
- headers: {
490
- output: './src/headers',
491
- exportTypes: true,
492
- split: true,
493
- import: '../headers',
494
- },
495
- securitySchemes: {
496
- output: './src/securitySchemes',
497
- split: true,
498
- import: '../securitySchemes',
499
- },
500
- links: {
501
- output: './src/links',
502
- split: true,
503
- import: '../links',
504
- },
505
- callbacks: {
506
- output: './src/callbacks',
507
- split: true,
508
- import: '../callbacks',
509
- },
510
- pathItems: {
511
- output: './src/pathItems',
512
- split: true,
513
- import: '../pathItems',
514
- },
515
- mediaTypes: {
516
- output: './src/mediaTypes',
517
- exportTypes: true,
518
- split: true,
519
- import: '../mediaTypes',
520
- },
521
- },
522
-
523
- type: {
524
- output: './src/types.ts',
525
- readonly: true,
526
- },
527
-
528
- rpc: {
529
- output: './src/rpc.ts',
530
- import: '../lib',
531
- client: 'client',
532
- parseResponse: true,
533
- docs: false, // operation summary/description as JSDoc
534
- },
535
-
536
- swr: {
537
- output: './src/swr.ts',
538
- import: '../lib',
539
- client: 'client',
540
- },
541
- 'tanstack-query': {
542
- output: './src/tanstack-query.ts',
543
- import: '../lib',
544
- client: 'client',
545
- },
546
- 'preact-query': {
547
- output: './src/preact-query.ts',
548
- import: '../lib',
549
- client: 'client',
550
- },
551
- 'solid-query': {
552
- output: './src/solid-query.ts',
553
- import: '../lib',
554
- client: 'client',
555
- },
556
- 'vue-query': {
557
- output: './src/vue-query.ts',
558
- import: '../lib',
559
- client: 'client',
560
- },
561
- 'svelte-query': {
562
- output: './src/svelte-query.ts',
563
- import: '../lib',
564
- client: 'client',
565
- },
566
- 'angular-query': {
567
- output: './src/angular-query.ts',
568
- import: '../lib',
569
- client: 'client',
570
- },
571
-
572
- test: {
573
- output: './src/test.ts',
574
- import: '.',
575
- testFramework: 'vitest', // "vitest" | "vite-plus" | "bun"
576
- },
577
-
578
- mock: {
579
- output: './src/mock.ts',
580
- useExamples: true, // true: response examples | 'all': also schema/property examples | false
581
- locale: 'en',
582
- seed: 42, // optional: same body per route on every request (snapshot-friendly)
583
- delay: false,
584
- arrayMin: 1,
585
- arrayMax: 10,
586
- },
587
-
588
- docs: {
589
- output: './docs/api.md',
590
- entry: 'src/index.ts',
591
- curl: false, // true: curl commands (requires baseUrl); false: hono request
592
- baseUrl: 'http://localhost:3000',
593
- },
594
- })
595
- ```
596
-
597
- ## Vendor Extensions (x-\*)
598
-
599
- hono-takibi reads `x-*` vendor extensions on your OpenAPI / JSON Schema to customize the generated Zod. Each extension maps 1:1 to a Zod feature.
600
-
601
- ### Custom Validation Error Messages
602
-
603
- Use `x-*` vendor extensions to attach custom Zod error messages, with **one extension per JSON Schema keyword** (1:1 mapping). The extension name follows the pattern `x-<jsonSchemaKeyword>-message` (e.g. `x-minLength-message`, `x-pattern-message`), plus four generic forms: `x-error-message`, `x-required-message`, `x-const-message`, `x-enum-message`.
604
-
605
- ```yaml
606
- name:
607
- type: string
608
- minLength: 1
609
- maxLength: 50
610
- x-error-message: 'Name must be a string'
611
- x-minLength-message: 'Name cannot be empty'
612
- x-maxLength-message: 'Name must be at most 50 characters'
613
- ```
614
-
615
- ```ts
616
- z.string({ error: 'Name must be a string' })
617
- .min(1, { error: 'Name cannot be empty' })
618
- .max(50, { error: 'Name must be at most 50 characters' })
619
- ```
620
-
621
- All custom message extensions follow the `x-<keyword>-message` naming convention and map directly to Zod validator error messages.
622
-
623
- #### Common (any schema type)
624
-
625
- | Extension | Applies to |
626
- | -------------------- | -------------------------------------------------------------- |
627
- | `x-error-message` | All schemas (fallback when keyword-specific message is absent) |
628
- | `x-required-message` | Required properties |
629
- | `x-const-message` | `const` |
630
- | `x-enum-message` | `enum` |
631
-
632
- #### Numeric (number / integer)
633
-
634
- | Extension | Applies to |
635
- | ---------------------------- | ------------------ |
636
- | `x-minimum-message` | `minimum` |
637
- | `x-maximum-message` | `maximum` |
638
- | `x-exclusiveMinimum-message` | `exclusiveMinimum` |
639
- | `x-exclusiveMaximum-message` | `exclusiveMaximum` |
640
- | `x-multipleOf-message` | `multipleOf` |
641
-
642
- #### String
643
-
644
- | Extension | Applies to |
645
- | --------------------- | ------------------------------------------ |
646
- | `x-minLength-message` | `minLength` |
647
- | `x-maxLength-message` | `maxLength` |
648
- | `x-pattern-message` | `pattern` |
649
- | `x-length-message` | Exact length (`minLength` === `maxLength`) |
650
-
651
- #### Array
652
-
653
- | Extension | Applies to |
654
- | ----------------------- | ------------- |
655
- | `x-minItems-message` | `minItems` |
656
- | `x-maxItems-message` | `maxItems` |
657
- | `x-uniqueItems-message` | `uniqueItems` |
658
- | `x-contains-message` | `contains` |
659
- | `x-minContains-message` | `minContains` |
660
- | `x-maxContains-message` | `maxContains` |
661
-
662
- #### Object
663
-
664
- | Extension | Applies to |
665
- | -------------------------------- | ---------------------- |
666
- | `x-minProperties-message` | `minProperties` |
667
- | `x-maxProperties-message` | `maxProperties` |
668
- | `x-additionalProperties-message` | `additionalProperties` |
669
- | `x-propertyNames-message` | `propertyNames` |
670
- | `x-patternProperties-message` | `patternProperties` |
671
- | `x-dependentRequired-message` | `dependentRequired` |
672
- | `x-dependentSchemas-message` | `dependentSchemas` |
673
-
674
- #### Combinators
675
-
676
- | Extension | Applies to |
677
- | ----------------------- | ---------------------------------------------------------------------------------------------------------------- |
678
- | `x-allOf-message` | `allOf` |
679
- | `x-anyOf-message` | `anyOf` |
680
- | `x-oneOf-message` | `oneOf` |
681
- | `x-not-message` | `not` |
682
- | `x-implication-message` | Implication pattern (`A → B`) encoded as `anyOf:[{not:A},{required:B}]`; takes precedence over `x-anyOf-message` |
683
-
684
- #### Conditional
685
-
686
- | Extension | Applies to |
687
- | ---------------- | ---------- |
688
- | `x-if-message` | `if` |
689
- | `x-then-message` | `then` |
690
- | `x-else-message` | `else` |
691
-
692
- #### Typeless / Array Applicator
693
-
694
- | Extension | Applies to |
695
- | --------------------------------- | ------------------------------- |
696
- | `x-properties-message` | `properties` (typeless schemas) |
697
- | `x-prefixItems-message` | `prefixItems` |
698
- | `x-items-message` | `items` |
699
- | `x-unevaluatedProperties-message` | `unevaluatedProperties` |
700
- | `x-unevaluatedItems-message` | `unevaluatedItems` |
701
-
702
- ### Behavior Extensions
703
-
704
- #### String Pre-validation Transforms
705
-
706
- | Extension | Generated | Value |
707
- | --------------- | ----------------------------- | --------------------------------------- |
708
- | `x-trim` | `z.string().trim()` | `true` |
709
- | `x-toLowerCase` | `z.string().toLowerCase()` | `true` |
710
- | `x-toUpperCase` | `z.string().toUpperCase()` | `true` |
711
- | `x-normalize` | `z.string().normalize('NFC')` | `'NFC'` / `'NFD'` / `'NFKC'` / `'NFKD'` |
712
-
713
- ```yaml
714
- homepage:
715
- type: string
716
- format: url
717
- x-trim: true
718
- ```
719
-
720
- ```ts
721
- z.string().trim().pipe(z.url())
722
- ```
723
-
724
- #### String Validation Checks
725
-
726
- | Extension | Generated | Value |
727
- | ------------- | ------------------------ | ------ |
728
- | `x-lowercase` | `z.string().lowercase()` | `true` |
729
- | `x-uppercase` | `z.string().uppercase()` | `true` |
730
-
731
- ```yaml
732
- slug:
733
- type: string
734
- x-lowercase: true
735
- ```
736
-
737
- ```ts
738
- z.string().lowercase()
739
- ```
740
-
741
- #### Preprocess
742
-
743
- **`x-preprocess`**
744
-
745
- ```yaml
746
- username:
747
- type: string
748
- x-preprocess: 'z.preprocess((val) => typeof val === "string" ? val.trim() : val, z.string())'
749
- ```
750
-
751
- ```ts
752
- z.preprocess((val) => (typeof val === 'string' ? val.trim() : val), z.string())
753
- ```
754
-
755
- #### Type Coercion
756
-
757
- **`x-coerce`**
758
-
759
- ```yaml
760
- asNumber:
761
- type: number
762
- x-coerce: true
763
- asDate:
764
- type: string
765
- format: date-time
766
- x-coerce: true
767
- ```
768
-
769
- ```ts
770
- z.coerce.number()
771
- z.coerce.date()
772
- ```
773
-
774
- **`x-stringbool`**
775
-
776
- ```yaml
777
- notify:
778
- type: boolean
779
- x-stringbool: true
780
- ```
781
-
782
- ```ts
783
- z.stringbool()
784
- ```
785
-
786
- ```yaml
787
- notify:
788
- type: boolean
789
- x-stringbool:
790
- truthy: ['yes', 'on']
791
- falsy: ['no', 'off']
792
- case: 'sensitive'
793
- ```
794
-
795
- ```ts
796
- z.stringbool({ truthy: ['yes', 'on'], falsy: ['no', 'off'], case: 'sensitive' })
797
- ```
798
-
799
- #### Codec
800
-
801
- **`x-codec`**
802
-
803
- ```yaml
804
- updatedAt:
805
- type: string
806
- format: date-time
807
- x-codec: 'z.codec(z.iso.datetime(), z.date(), { decode: (isoString) => new Date(isoString), encode: (date) => date.toISOString() })'
808
- ```
809
-
810
- ```ts
811
- z.codec(z.iso.datetime(), z.date(), {
812
- decode: (isoString) => new Date(isoString),
813
- encode: (date) => date.toISOString(),
814
- })
815
- ```
816
-
817
- #### Custom Validation
818
-
819
- **`x-refine`**
820
-
821
- ```yaml
822
- password:
823
- type: string
824
- x-refine: '.refine((val) => val.length >= 8, { message: "Password must be at least 8 characters" }).refine((val) => /[A-Z]/.test(val), { message: "Password must contain an uppercase letter" })'
825
- ```
826
-
827
- ```ts
828
- z.string()
829
- .refine((val) => val.length >= 8, { message: 'Password must be at least 8 characters' })
830
- .refine((val) => /[A-Z]/.test(val), { message: 'Password must contain an uppercase letter' })
831
- ```
832
-
833
- **`x-superRefine`**
834
-
835
- ```yaml
836
- normalizedEmail:
837
- type: string
838
- format: email
839
- x-superRefine: '.superRefine((val, ctx) => { if (val.endsWith("@blocked.example")) ctx.addIssue({ code: "custom", message: "Blocked domain" }) })'
840
- ```
841
-
842
- ```ts
843
- z.email().superRefine((val, ctx) => {
844
- if (val.endsWith('@blocked.example')) {
845
- ctx.addIssue({ code: 'custom', message: 'Blocked domain' })
846
- }
847
- })
848
- ```
849
-
850
- #### Transform & Pipe
851
-
852
- **`x-transform`**
853
-
854
- ```yaml
855
- code:
856
- type: string
857
- x-transform: 'z.string().transform((val) => val.toUpperCase())'
858
- ```
859
-
860
- ```ts
861
- z.string().transform((val) => val.toUpperCase())
862
- ```
863
-
864
- **`x-pipe`**
865
-
866
- ```yaml
867
- port:
868
- type: string
869
- x-pipe: 'z.string().pipe(z.number().int().positive())'
870
- ```
871
-
872
- ```ts
873
- z.string().pipe(z.number().int().positive())
874
- ```
875
-
876
- #### Default & Fallback Values
877
-
878
- **`x-prefault`**
879
-
880
- ```yaml
881
- greeting:
882
- type: string
883
- x-prefault: 'hello'
884
- ```
885
-
886
- ```ts
887
- z.string().prefault('hello')
888
- ```
889
-
890
- **`x-catch`**
891
-
892
- ```yaml
893
- retries:
894
- type: integer
895
- x-catch: 0
896
- ```
897
-
898
- ```ts
899
- z.int().catch(0)
900
- ```
901
-
902
- #### Immutability
903
-
904
- **`x-readonly`**
905
-
906
- ```yaml
907
- config:
908
- type: object
909
- properties:
910
- name:
911
- type: string
912
- x-readonly: true
913
- ```
914
-
915
- ```ts
916
- z.object({ name: z.string() }).readonly()
917
- ```
918
-
919
- #### String Content Checks
920
-
921
- **`x-startsWith` / `x-endsWith` / `x-includes`**
922
-
923
- ```yaml
924
- url:
925
- type: string
926
- x-startsWith: 'https://'
927
- x-endsWith: '.com'
928
- path:
929
- type: string
930
- x-includes: '/api/'
931
- ```
932
-
933
- ```ts
934
- z.string().startsWith('https://').endsWith('.com')
935
- z.string().includes('/api/')
936
- ```
937
-
938
- #### Format-Specific Options
939
-
940
- ```yaml
941
- htmlEmail:
942
- type: string
943
- format: email
944
- x-emailPattern: 'html5' # email pattern preset
945
- uuidV7:
946
- type: string
947
- format: uuid
948
- x-uuidVersion: v7 # uuid version
949
- httpsUrl:
950
- type: string
951
- format: uri
952
- x-urlProtocol: '^https$' # url protocol regex
953
- x-urlNormalize: true
954
- preciseDatetime:
955
- type: string
956
- format: date-time
957
- x-isoPrecision: 3 # iso datetime precision / offset / local
958
- x-isoOffset: true
959
- ```
960
-
961
- | Extension | Maps to | Values |
962
- | ---------------- | ------------------------------- | ----------------------------------------------------- |
963
- | `x-emailPattern` | `z.email({ pattern })` | `html5` / `rfc5322` / `unicode` |
964
- | `x-emailRegex` | `z.email({ pattern: /.../ })` | custom regex string |
965
- | `x-uuidVersion` | `z.uuid({ version })` | `v1` / `v2` / `v3` / `v4` / `v5` / `v6` / `v7` / `v8` |
966
- | `x-urlProtocol` | `z.url({ protocol: /.../ })` | regex string |
967
- | `x-urlHostname` | `z.url({ hostname: /.../ })` | regex string |
968
- | `x-urlNormalize` | `z.url({ normalize })` | `true` / `false` |
969
- | `x-isoPrecision` | `z.iso.datetime({ precision })` | fractional second digits |
970
- | `x-isoOffset` | `z.iso.datetime({ offset })` | `true` / `false` |
971
- | `x-isoLocal` | `z.iso.datetime({ local })` | `true` / `false` |
972
- | `x-macDelimiter` | `z.mac({ delimiter })` | `:` / `-` / `.` |
973
- | `x-jwtAlg` | `z.jwt({ alg })` | `HS256` etc. |
974
- | `x-hashAlg` | `z.hash(alg, ...)` | `sha256` etc. |
975
- | `x-hashEnc` | `z.hash(alg, { enc })` | `hex` / `base64` / `base64url` |
976
-
977
- ### Branded Types (x-brand)
978
-
979
- Use the `x-brand` vendor extension to generate [Zod branded types](https://zod.dev/api?id=branded-types), creating nominal types that are structurally identical but semantically distinct:
980
-
981
- ```yaml
982
- components:
983
- schemas:
984
- Cat:
985
- type: object
986
- properties:
987
- name:
988
- type: string
989
- required:
990
- - name
991
- x-brand: Cat
992
- Dog:
993
- type: object
994
- properties:
995
- name:
996
- type: string
997
- required:
998
- - name
999
- x-brand: Dog
1000
- ```
1001
-
1002
- ```ts
1003
- // Generated output
1004
- const CatSchema = z.object({ name: z.string() }).brand<'Cat'>().openapi('Cat')
1005
-
1006
- const DogSchema = z.object({ name: z.string() }).brand<'Dog'>().openapi('Dog')
1007
- ```
47
+ - [Getting Started](https://hono-takibi.dev/docs)
48
+ - [Configuration](https://hono-takibi.dev/docs/guides/config)
49
+ - [Template](https://hono-takibi.dev/docs/guides/template)
50
+ - [Client](https://hono-takibi.dev/docs/guides/client)
51
+ - [Test & Mock](https://hono-takibi.dev/docs/guides/test-mock)
52
+ - [API Docs](https://hono-takibi.dev/docs/guides/api-docs)
53
+ - [Vendor Extensions](https://hono-takibi.dev/docs/guides/vendor)
54
+ - [Vite Plugin](https://hono-takibi.dev/docs/guides/vite-plugin)
1008
55
 
1009
56
  ## Projects Using Hono Takibi
1010
57
 
1011
58
  - **[resend-local](https://github.com/y-hiraoka/resend-local)** — A local emulator for the Resend email API.
1012
59
 
1013
- ## Contributing
1014
-
1015
- We welcome feedback and contributions to improve the tool!
1016
-
1017
- If you find any issues with the generated code or have suggestions for improvements, please:
1018
-
1019
- - Open an issue at [GitHub Issues](https://github.com/nakita628/hono-takibi/issues)
1020
- - Submit a pull request with your improvements
1021
-
1022
- Lint and tests run from the repo root:
1023
-
1024
- ```bash
1025
- pnpm check # format, lint, type checks, then `pnpm lint`
1026
- pnpm lint # what the Lint workflow runs
1027
- pnpm lint:actions # actionlint (syntax) and zizmor (security) over .github/workflows, when installed
1028
- pnpm test # unit tests, then the generated cases under test/
1029
- ```
1030
-
1031
- `actionlint` and `zizmor` are not npm packages: install them with `pipx install actionlint-py` and `pipx install zizmor` to run them locally; without them the script only prints a note. The Lint workflow always runs both.
1032
-
1033
60
  ## License
1034
61
 
1035
62
  Distributed under the MIT License. See [LICENSE](https://github.com/nakita628/hono-takibi?tab=MIT-1-ov-file) for more information.
package/dist/cli.js CHANGED
@@ -61,7 +61,7 @@ function runConfigPass(configPath, reload) {
61
61
  import("./index.js"),
62
62
  import("./openapi-DQRxq2_O.js").then((n) => n.t),
63
63
  import("./format-Bm9LZ_ki.js").then((n) => n.r),
64
- import("./shared-BTyk3wSO.js").then((n) => n.i)
64
+ import("./shared-DVLeJFoN.js").then((n) => n.i)
65
65
  ]));
66
66
  const config = yield* readConfig(configPath, reload);
67
67
  const jobs = makeJob(yield* parseOpenAPI(config.input), config);
@@ -167,7 +167,7 @@ function generate(args) {
167
167
  })]
168
168
  });
169
169
  if (input !== void 0 && output !== void 0) {
170
- const [{ parseOpenAPI }, { takibi }] = yield* Effect.promise(() => Promise.all([import("./openapi-DQRxq2_O.js").then((n) => n.t), import("./core-Zb9XMy-3.js").then((n) => n.t)]));
170
+ const [{ parseOpenAPI }, { takibi }] = yield* Effect.promise(() => Promise.all([import("./openapi-DQRxq2_O.js").then((n) => n.t), import("./core-BIzYFvM2.js").then((n) => n.t)]));
171
171
  return yield* Console.log(yield* takibi(yield* parseOpenAPI(input), output));
172
172
  }
173
173
  const resolvedConfig = configPath ?? DEFAULT_CONFIG_FILE;
@@ -1655,6 +1655,77 @@ function collectInlineRouteNames(code) {
1655
1655
  return [...extractOpenApiCalls(code).keys()];
1656
1656
  }
1657
1657
  /**
1658
+ * Collects the non-exported top-level declarations of a generated handler file by name:
1659
+ * `const app = new OpenAPIHono()` and the `function mockXxx() {…}` helpers the exported
1660
+ * handler statements depend on.
1661
+ */
1662
+ function collectSupportStatements(file) {
1663
+ const map = /* @__PURE__ */ new Map();
1664
+ for (const stmt of file.getStatements()) if (Node.isVariableStatement(stmt)) {
1665
+ if (stmt.isExported()) continue;
1666
+ for (const decl of stmt.getDeclarations()) map.set(decl.getName(), stmt.getText());
1667
+ } else if (Node.isFunctionDeclaration(stmt)) {
1668
+ const name = stmt.getName();
1669
+ if (name !== void 0 && !stmt.isExported()) map.set(name, stmt.getText());
1670
+ }
1671
+ return map;
1672
+ }
1673
+ /**
1674
+ * Lists every name a file declares at the top level, including imported bindings.
1675
+ */
1676
+ function collectDeclaredNames(file) {
1677
+ const names = /* @__PURE__ */ new Set();
1678
+ for (const decl of file.getVariableDeclarations()) names.add(decl.getName());
1679
+ for (const fn of file.getFunctions()) {
1680
+ const name = fn.getName();
1681
+ if (name !== void 0) names.add(name);
1682
+ }
1683
+ for (const cls of file.getClasses()) {
1684
+ const name = cls.getName();
1685
+ if (name !== void 0) names.add(name);
1686
+ }
1687
+ for (const en of file.getEnums()) names.add(en.getName());
1688
+ for (const imp of file.getImportDeclarations()) {
1689
+ const def = imp.getDefaultImport();
1690
+ if (def) names.add(def.getText());
1691
+ const ns = imp.getNamespaceImport();
1692
+ if (ns) names.add(ns.getText());
1693
+ for (const named of imp.getNamedImports()) names.add((named.getAliasNode() ?? named.getNameNode()).getText());
1694
+ }
1695
+ return names;
1696
+ }
1697
+ function collectIdentifiers(code) {
1698
+ return new Set(parseSnippet(code).getDescendantsOfKind(SyntaxKind.Identifier).map((id) => id.getText()));
1699
+ }
1700
+ /**
1701
+ * Picks the generated support declarations the merged handler body needs but the existing
1702
+ * file lacks, in generated order.
1703
+ *
1704
+ * Why: when the merge adds a handler statement (e.g. switching from `*RouteHandler` stubs to an
1705
+ * inline sub-router, or a fresh mock route), only the exported statement used to be copied, so
1706
+ * `export const usersHandler = app.openapi(…)` landed in a file with no `app`. A user who chained
1707
+ * off their own `router` must not get an unused `app` injected, so a declaration is copied only
1708
+ * when the merged body actually references it (transitively, as mocks call nested mocks).
1709
+ */
1710
+ function missingSupportStatements(existingFile, generatedFile, mergedBody) {
1711
+ const declared = collectDeclaredNames(existingFile);
1712
+ const missing = [...collectSupportStatements(generatedFile)].filter(([name]) => !declared.has(name));
1713
+ if (missing.length === 0) return [];
1714
+ const referenced = collectIdentifiers(mergedBody);
1715
+ const picked = /* @__PURE__ */ new Set();
1716
+ let changed = true;
1717
+ while (changed) {
1718
+ changed = false;
1719
+ for (const [name, text] of missing) {
1720
+ if (picked.has(name) || !referenced.has(name)) continue;
1721
+ picked.add(name);
1722
+ changed = true;
1723
+ for (const id of collectIdentifiers(text)) referenced.add(id);
1724
+ }
1725
+ }
1726
+ return missing.filter(([name]) => picked.has(name)).map(([, text]) => text);
1727
+ }
1728
+ /**
1658
1729
  * Merges generated handler code with existing handler code.
1659
1730
  *
1660
1731
  * Merge rules:
@@ -1664,6 +1735,8 @@ function collectInlineRouteNames(code) {
1664
1735
  * sub-router exports (`xxxHandler`) are deleted the same way only when the generated file is
1665
1736
  * itself an inline handler file; any other `*Handler` export is the user's and is kept
1666
1737
  * - Non-handler code (helpers, constants, comments): keep existing
1738
+ * - Generated support declarations (`const app = new OpenAPIHono()`, `mockXxx` functions) that the
1739
+ * merged handlers reference but the existing file lacks: add, right after the imports
1667
1740
  * - Imports: sync with generated (remove deleted route imports, add new ones, keep user imports)
1668
1741
  *
1669
1742
  * Uses AST for analysis only. The existing file's original text (including comments)
@@ -1693,8 +1766,11 @@ function mergeHandlerFile(existingCode, generatedCode) {
1693
1766
  const bodyStart = getBodyStart(existingFile);
1694
1767
  const body = applyRangeOps(existingCode, bodyStart, [...deleteOps, ...mergeOps].filter(([start]) => start >= bodyStart).toSorted(([a], [b]) => a - b)).replaceAll(/\n{3,}/gu, "\n\n");
1695
1768
  const newHandlerStatements = [...generatedHandlers.entries()].filter(([name]) => !existingHandlers.has(name)).map(([, stmt]) => stmt.getText());
1769
+ const mergedImports = mergeImports(existingFile, generatedFile);
1770
+ const supportStatements = missingSupportStatements(existingFile, generatedFile, `${body}\n${newHandlerStatements.join("\n")}`);
1696
1771
  return joinSections([
1697
- mergeImports(existingFile, generatedFile).join("\n"),
1772
+ mergedImports.join("\n"),
1773
+ supportStatements.join("\n\n"),
1698
1774
  body.trim(),
1699
1775
  newHandlerStatements.join("\n\n")
1700
1776
  ]);
@@ -1961,7 +2037,8 @@ function mergeInlineHandler(existingText, generatedText) {
1961
2037
  const existingCalls = extractOpenApiCalls(existingText);
1962
2038
  const firstCallMatch = generatedText.match(/\.openapi\s*\(/u);
1963
2039
  if (firstCallMatch?.index === void 0) return generatedText;
1964
- return `${generatedText.slice(0, firstCallMatch.index).trimEnd()}\n${[...generatedCalls.entries()].map(([routeName, genCall]) => existingCalls.get(routeName) ?? genCall).join("\n")}`;
2040
+ const existingFirstCall = existingText.match(/\.openapi\s*\(/u);
2041
+ return `${existingCalls.size > 0 && existingFirstCall?.index !== void 0 ? existingText.slice(0, existingFirstCall.index).trimEnd() : generatedText.slice(0, firstCallMatch.index).trimEnd()}\n${[...generatedCalls.entries()].map(([routeName, genCall]) => existingCalls.get(routeName) ?? genCall).join("\n")}`;
1965
2042
  }
1966
2043
  /**
1967
2044
  * Extracts top-level `function mockXxx(...) { ... }` definitions from test code.
@@ -1,7 +1,7 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
2
2
  import { a as unlink, i as readdir } from "./file-CwKqigE9.js";
3
3
  import { o as GenerateError } from "./rpc-CQFRTmcC.js";
4
- import { _ as links, a as defineTemplate, b as callbacks, c as mock, d as responses, f as requestBodies, g as mediaTypes, h as components, i as template, l as securitySchemes, m as parameters, n as webhooks, o as takibi, p as pathItems, r as test, s as route, u as schemas, v as headers, y as examples } from "./core-Zb9XMy-3.js";
4
+ import { _ as links, a as defineTemplate, b as callbacks, c as mock, d as responses, f as requestBodies, g as mediaTypes, h as components, i as template, l as securitySchemes, m as parameters, n as webhooks, o as takibi, p as pathItems, r as test, s as route, u as schemas, v as headers, y as examples } from "./core-BIzYFvM2.js";
5
5
  import { t as hooks } from "./hooks-kkOg8Baa.js";
6
6
  import { t as docs } from "./docs-Bo4-6xBy.js";
7
7
  import { rpc } from "./core/rpc/index.js";
@@ -3,7 +3,7 @@ import { t as fileSystemLayer } from "../file-CwKqigE9.js";
3
3
  import { t as FormatOptions } from "../format-Bm9LZ_ki.js";
4
4
  import { z as isRecord } from "../utils-BtWoIX8v.js";
5
5
  import { n as parseOpenAPI } from "../openapi-DQRxq2_O.js";
6
- import { n as cleanSplitOutputs, r as makeJob, t as appEntryOutput } from "../shared-BTyk3wSO.js";
6
+ import { n as cleanSplitOutputs, r as makeJob, t as appEntryOutput } from "../shared-DVLeJFoN.js";
7
7
  import { Effect, FileSystem, Option, Result } from "effect";
8
8
  import path from "node:path";
9
9
  import crypto from "node:crypto";
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "hono-takibi",
3
- "version": "0.14.0",
3
+ "version": "0.15.0",
4
4
  "description": "Hono Takibi is a code generator from OpenAPI to @hono/zod-openapi",
5
5
  "keywords": [
6
6
  "hono",
7
7
  "openapi"
8
8
  ],
9
- "homepage": "https://github.com/nakita628/hono-takibi",
9
+ "homepage": "https://hono-takibi.dev/",
10
10
  "bugs": {
11
11
  "url": "https://github.com/nakita628/hono-takibi/issues"
12
12
  },
@@ -15,6 +15,7 @@
15
15
  "type": "git",
16
16
  "url": "git+https://github.com/nakita628/hono-takibi.git"
17
17
  },
18
+ "funding": "https://github.com/sponsors/nakita628",
18
19
  "bin": {
19
20
  "hono-takibi": "dist/cli.js"
20
21
  },