hono-takibi 0.23.0 → 0.25.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/dist/cli.js CHANGED
@@ -1,17 +1,17 @@
1
1
  #!/usr/bin/env node
2
- import { l as INPUT_EXTENSIONS } from "./constants-Bz8YiPum.js";
2
+ import { l as INPUT_EXTENSIONS } from "./constants-CxrXPVxh.js";
3
3
  import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
4
4
  import * as NodeServices from "@effect/platform-node/NodeServices";
5
5
  import { Console, Effect, FileSystem, Option, Path, Ref, Schema, Stream } from "effect";
6
6
  import { Argument, CliError, Command, Flag } from "effect/cli";
7
7
  //#region package.json
8
- var version = "0.23.0";
8
+ var version = "0.25.0";
9
9
  var description = "Hono Takibi is a code generator from OpenAPI to @hono/zod-openapi";
10
10
  //#endregion
11
11
  //#region src/cli/index.ts
12
12
  const COMMAND_NAME = "hono-takibi";
13
13
  const DEFAULT_CONFIG_FILE = "hono-takibi.config.ts";
14
- const DocumentPathSchema = Schema.String.pipe(Schema.refine(Schema.is(Schema.TemplateLiteral([Schema.String, Schema.Literals(INPUT_EXTENSIONS)])), { message: "an OpenAPI (.yaml, .json) or TypeSpec (.tsp) document" })).annotate({
14
+ const DocumentPathSchema = Schema.String.pipe(Schema.refine(Schema.is(Schema.TemplateLiteral([Schema.String, Schema.Literals(INPUT_EXTENSIONS)])), { message: "an OpenAPI (.yaml, .yml, .json) or TypeSpec (.tsp) document" })).annotate({
15
15
  title: "Input document",
16
16
  description: "OpenAPI or TypeSpec document the one-shot mode generates from.",
17
17
  examples: [
@@ -26,7 +26,7 @@ const TypeScriptPathSchema = Schema.String.pipe(Schema.refine(Schema.is(Schema.T
26
26
  examples: ["./src/routes.ts", "src/api/routes.ts"]
27
27
  });
28
28
  const commandLine = {
29
- input: Argument.File("input", { mustExist: true }).pipe(Argument.withSchema(DocumentPathSchema), Argument.withDescription("OpenAPI (.yaml, .json) or TypeSpec (.tsp) document to generate from"), Argument.withMetavar("input.{yaml,json,tsp}"), Argument.optional),
29
+ input: Argument.File("input", { mustExist: true }).pipe(Argument.withSchema(DocumentPathSchema), Argument.withDescription("OpenAPI (.yaml, .yml, .json) or TypeSpec (.tsp) document to generate from"), Argument.withMetavar("input.{yaml,yml,json,tsp}"), Argument.optional),
30
30
  output: Flag.String("output").pipe(Flag.withAlias("o"), Flag.withSchema(TypeScriptPathSchema), Flag.withDescription("TypeScript file the generated routes are written to"), Flag.withMetavar("output.ts"), Flag.optional),
31
31
  config: Flag.File("config", { mustExist: true }).pipe(Flag.withAlias("c"), Flag.withDescription(`Config file to run (default: ./${DEFAULT_CONFIG_FILE})`), Flag.withMetavar("file"), Flag.optional),
32
32
  watch: Flag.Boolean("watch").pipe(Flag.withAlias("w"), Flag.withDescription("Rerun the config on every change to its documents or itself"), Flag.withDefault(false))
@@ -40,9 +40,9 @@ function loadConfig(configPath, reload) {
40
40
  function runJobs(config) {
41
41
  return Effect.gen(function* () {
42
42
  const [{ parseOpenAPI }, { FormatOptions }, { cleanSplitOutputs, makeJob, packageRoots }] = yield* Effect.promise(() => Promise.all([
43
- import("./openapi-DEZCoJlc.js").then((n) => n.t),
43
+ import("./openapi-t_u-tF52.js").then((n) => n.t),
44
44
  import("./format-CuHABcKC.js").then((n) => n.r),
45
- import("./shared-BxcbHfBt.js").then((n) => n.a)
45
+ import("./shared-Tq3KgO4s.js").then((n) => n.a)
46
46
  ]));
47
47
  const openAPI = yield* parseOpenAPI(config.input);
48
48
  const jobs = makeJob(openAPI, config, yield* packageRoots(openAPI, config));
@@ -80,7 +80,7 @@ function reportJobs(config, previous) {
80
80
  onFailure: (error) => Console.error(`❌ ${error.message}`),
81
81
  onSuccess: (report) => Console.log(report)
82
82
  }));
83
- const { outsideSources } = yield* Effect.promise(() => import("./shared-BxcbHfBt.js").then((n) => n.a));
83
+ const { outsideSources } = yield* Effect.promise(() => import("./shared-Tq3KgO4s.js").then((n) => n.a));
84
84
  const inputDirectory = path.dirname(path.resolve(config.input));
85
85
  return {
86
86
  inputDirectory,
@@ -207,7 +207,7 @@ function generate(args) {
207
207
  })]
208
208
  });
209
209
  if (input !== void 0 && output !== void 0) {
210
- const [{ parseOpenAPI }, { takibi }] = yield* Effect.promise(() => Promise.all([import("./openapi-DEZCoJlc.js").then((n) => n.t), import("./core-BhMCMrQ6.js").then((n) => n.t)]));
210
+ const [{ parseOpenAPI }, { takibi }] = yield* Effect.promise(() => Promise.all([import("./openapi-t_u-tF52.js").then((n) => n.t), import("./core-rnNgBu4D.js").then((n) => n.t)]));
211
211
  return yield* Console.log(yield* takibi(yield* parseOpenAPI(input), output));
212
212
  }
213
213
  const resolvedConfig = configPath ?? DEFAULT_CONFIG_FILE;
@@ -13,9 +13,10 @@ const COMPONENT_NAMES = [
13
13
  "pathItems",
14
14
  "mediaTypes"
15
15
  ];
16
- /** The extensions of an input document: OpenAPI as YAML or JSON, or a TypeSpec entry. */
16
+ /** The extensions of an input document: OpenAPI as YAML (`.yaml` or `.yml`) or JSON, or a TypeSpec entry. */
17
17
  const INPUT_EXTENSIONS = [
18
18
  ".yaml",
19
+ ".yml",
19
20
  ".json",
20
21
  ".tsp"
21
22
  ];
@@ -1,4 +1,4 @@
1
- import { t as OpenAPI } from "../../index-tsPqeV6H.js";
1
+ import { t as OpenAPI } from "../../index-B3ze4n_I.js";
2
2
  import { Effect } from "effect";
3
3
  //#region src/core/docs/index.d.ts
4
4
  export declare function docs(openAPI: OpenAPI, output: string, entry?: string, basePath?: string, curl?: boolean, baseUrl?: string): Effect.Effect<string, import("effect/PlatformError").PlatformError, import("effect/FileSystem").FileSystem>;
@@ -1 +1 @@
1
- export { t as docs } from "../../docs-C5t1NRQ8.js";
1
+ export { t as docs } from "../../docs-BApYjFQG.js";
@@ -1,6 +1,6 @@
1
- import { t as OpenAPI } from "../../index-tsPqeV6H.js";
1
+ import { t as OpenAPI } from "../../index-B3ze4n_I.js";
2
2
  import { n as GenerateError, t as FormatError } from "../../index-D_gf3Xzx.js";
3
- import { t as Grouping } from "../../index-3BQ2KpP9.js";
3
+ import { t as Grouping } from "../../index-j7o04Qt1.js";
4
4
  //#region src/core/hooks/index.d.ts
5
5
  declare const HOOK_CONFIGS: {
6
6
  readonly swr: {
@@ -1 +1 @@
1
- export { t as hooks } from "../../hooks-CR7angVC.js";
1
+ export { t as hooks } from "../../hooks-RrTkHWCS.js";
@@ -1,6 +1,6 @@
1
- import { t as OpenAPI } from "../../index-tsPqeV6H.js";
1
+ import { t as OpenAPI } from "../../index-B3ze4n_I.js";
2
2
  import { n as GenerateError, t as FormatError } from "../../index-D_gf3Xzx.js";
3
- import { t as Grouping } from "../../index-3BQ2KpP9.js";
3
+ import { t as Grouping } from "../../index-j7o04Qt1.js";
4
4
  import { Effect } from "effect";
5
5
  //#region src/core/rpc/index.d.ts
6
6
  /**
@@ -1,7 +1,7 @@
1
- import { s as HTTP_METHODS } from "../../constants-Bz8YiPum.js";
1
+ import { s as HTTP_METHODS } from "../../constants-CxrXPVxh.js";
2
2
  import { i as GenerateError } from "../../format-CuHABcKC.js";
3
- import { L as isOpenAPIPaths, f as methodPath, l as makeInferRequestType, q as isRecord, z as isOperationLike } from "../../utils-vw99OasL.js";
4
- import { c as makeGroupClientName, i as parsePathItem, l as operationTags, n as makeOperationDeps, r as operationHasArgs, t as formatPath } from "../../rpc-Bgtv3nGI.js";
3
+ import { B as isOperationLike, J as isRecord, R as isOpenAPIPaths, p as methodPath, u as makeInferRequestType } from "../../utils-v71BPo5C.js";
4
+ import { c as makeGroupClientName, i as parsePathItem, l as operationTags, n as makeOperationDeps, r as operationHasArgs, t as formatPath } from "../../rpc-BOAnGH-n.js";
5
5
  import { t as emit } from "../../emit-uwlZZeRM.js";
6
6
  import { Effect } from "effect";
7
7
  import { dirname } from "node:path";
@@ -1,4 +1,4 @@
1
- import { t as OpenAPI } from "../../index-tsPqeV6H.js";
1
+ import { t as OpenAPI } from "../../index-B3ze4n_I.js";
2
2
  import { t as FormatError } from "../../index-D_gf3Xzx.js";
3
3
  import { Effect } from "effect";
4
4
  //#region src/core/type/index.d.ts
@@ -1,5 +1,5 @@
1
- import "../../constants-Bz8YiPum.js";
2
- import { B as isParameter, F as isMediaWithSchema, L as isOpenAPIPaths, Q as isSchemaArray, R as isOperation, V as isParameterArray, X as isRequestBody, _ as toIdentifierPascalCase, g as statusCodeToNumber, it as isStringRef, j as isHttpMethod, u as makeSafeKey } from "../../utils-vw99OasL.js";
1
+ import "../../constants-CxrXPVxh.js";
2
+ import { $ as isSchemaArray, H as isParameterArray, I as isMediaWithSchema, M as isHttpMethod, R as isOpenAPIPaths, V as isParameter, Z as isRequestBody, _ as statusCodeToNumber, at as isStringRef, d as makeSafeKey, v as toIdentifierPascalCase, z as isOperation } from "../../utils-v71BPo5C.js";
3
3
  import { t as emit } from "../../emit-uwlZZeRM.js";
4
4
  import { Effect } from "effect";
5
5
  import path from "node:path";
@@ -1,13 +1,13 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
2
- import { n as COMPONENT_NAMES, p as TEXT_MEDIA_TYPE, r as COMPONENT_REF_PREFIX, s as HTTP_METHODS, u as JSON_MEDIA_TYPE } from "./constants-Bz8YiPum.js";
2
+ import { n as COMPONENT_NAMES, p as TEXT_MEDIA_TYPE, r as COMPONENT_REF_PREFIX, s as HTTP_METHODS, u as JSON_MEDIA_TYPE } from "./constants-CxrXPVxh.js";
3
3
  import { i as GenerateError, n as fmt } from "./format-CuHABcKC.js";
4
- import { $ as isSchemaObject, B as isParameter, D as isCallbacks, F as isMediaWithSchema, G as isPathItemEntry, J as isRefObject, K as isPathItemRef, L as isOpenAPIPaths, N as isInlineMedia, Q as isSchemaArray, R as isOperation, T as hasRequestBodyContent, W as isPathItem, _ as toIdentifierPascalCase, at as isValidIdent, b as zodToOpenAPISchema, c as makeBarrel, d as makeStringLiteral, f as methodPath, g as statusCodeToNumber, i as ensureSuffix, j as isHttpMethod, m as renderNamedImport, nt as isSecurityScheme, p as normalizeTypes, r as cyclicNodes, s as escapeRegexLiteral, tt as isSecurityArray, u as makeSafeKey, v as uncapitalize, w as hasNumericConstraint, y as uncapitalizeWord } from "./utils-vw99OasL.js";
5
- import { A as resolvePathItem, C as makeCallback, D as makeRouteProperties, E as makeRouteEntries, O as makeWebhookEntries, S as zodToOpenAPI, T as makeRef, _ as descendantsWhere, a as responsesCode, b as parseSource, c as headersCode, d as makeExportConst, f as makeImports, g as declarationOf, h as ast, i as schemasCode, k as resolveParameter, l as makeSplitSchemaFile, m as analyzeCircularSchemas, n as routeCode, o as requestBodiesCode, p as makeModuleSpec, r as componentsCode, s as parametersCode, t as zodOpenAPIHono, u as makeConst, v as identifierNames, w as makePathItem, x as textOf, y as parseModule } from "./openapi-KOHVzQbz.js";
6
- import { a as entryNames, c as makeGroupClientName, l as operationTags, o as freeName, s as groupNameOf } from "./rpc-Bgtv3nGI.js";
4
+ import { $ as isSchemaArray, D as hasRequestBodyContent, E as hasNumericConstraint, G as isPathItem, I as isMediaWithSchema, K as isPathItemEntry, M as isHttpMethod, P as isInlineMedia, R as isOpenAPIPaths, V as isParameter, Y as isRefObject, _ as statusCodeToNumber, a as ensureSuffix, b as uncapitalizeWord, c as escapeRegexLiteral, d as makeSafeKey, et as isSchemaObject, f as makeStringLiteral, h as renderNamedImport, k as isCallbacks, l as makeBarrel, m as normalizeTypes, nt as isSecurityArray, ot as isValidIdent, p as methodPath, q as isPathItemRef, r as cyclicNodes, rt as isSecurityScheme, v as toIdentifierPascalCase, x as zodToOpenAPISchema, y as uncapitalize, z as isOperation } from "./utils-v71BPo5C.js";
5
+ import { A as resolvePathItem, C as makeCallback, D as makeRouteProperties, E as makeRouteEntries, O as makeWebhookEntries, S as zodToOpenAPI, T as makeRef, _ as descendantsWhere, a as responsesCode, b as parseSource, c as headersCode, d as makeExportConst, f as makeImports, g as declarationOf, h as ast, i as schemasCode, k as resolveParameter, l as makeSplitSchemaFile, m as analyzeCircularSchemas, n as routeCode, o as requestBodiesCode, p as makeModuleSpec, r as componentsCode, s as parametersCode, t as zodOpenAPIHono, u as makeConst, v as identifierNames, w as makePathItem, x as textOf, y as parseModule } from "./openapi-CuyeukCF.js";
6
+ import { a as entryNames, c as makeGroupClientName, l as operationTags, o as freeName, s as groupNameOf } from "./rpc-BOAnGH-n.js";
7
7
  import { i as readdir, n as mkdir, o as writeFile, r as readFile } from "./file-K6j5IJXi.js";
8
8
  import { t as emit } from "./emit-uwlZZeRM.js";
9
- import { t as hooks } from "./hooks-CR7angVC.js";
10
- import { t as docs } from "./docs-C5t1NRQ8.js";
9
+ import { t as hooks } from "./hooks-RrTkHWCS.js";
10
+ import { t as docs } from "./docs-BApYjFQG.js";
11
11
  import { rpc } from "./core/rpc/index.js";
12
12
  import { type } from "./core/type/index.js";
13
13
  import { Effect } from "effect";
@@ -1,5 +1,5 @@
1
- import { d as MULTIPART_MEDIA_TYPE, s as HTTP_METHODS } from "./constants-Bz8YiPum.js";
2
- import { J as isRefObject, Q as isSchemaArray, o as escapeHtml, q as isRecord } from "./utils-vw99OasL.js";
1
+ import { d as MULTIPART_MEDIA_TYPE, s as HTTP_METHODS } from "./constants-CxrXPVxh.js";
2
+ import { $ as isSchemaArray, J as isRecord, Y as isRefObject, i as decodePercent, s as escapeHtml } from "./utils-v71BPo5C.js";
3
3
  import { n as mkdir, o as writeFile } from "./file-K6j5IJXi.js";
4
4
  import { Effect } from "effect";
5
5
  import path from "node:path";
@@ -50,13 +50,6 @@ function toText(value) {
50
50
  function toSingleLine(value) {
51
51
  return value.replaceAll(/\s+/gu, " ").trim();
52
52
  }
53
- function decodePercent(value) {
54
- try {
55
- return decodeURIComponent(value);
56
- } catch {
57
- return value;
58
- }
59
- }
60
53
  /**
61
54
  * Decodes one JSON Pointer segment of a URI fragment: percent-encoding first,
62
55
  * then `~1` and `~0` (RFC 6901 §6).
@@ -121,6 +114,10 @@ function schemaAnchor(name, doc) {
121
114
  anchors.set(name, anchor);
122
115
  return anchor;
123
116
  }
117
+ /** A `$ref` to a schema under `components.schemas`: linked in a table, listed under Schemas. */
118
+ function isComponentRef(schema) {
119
+ return schema.$ref !== void 0 && componentSchemaName(schema.$ref) !== void 0;
120
+ }
124
121
  function makeSchemaLink(name, doc) {
125
122
  return `[${name}](#schema${schemaAnchor(name, doc)})`;
126
123
  }
@@ -935,11 +932,12 @@ function flattenFields(schema, doc, prefix, options, inheritedRequired = [], ins
935
932
  const required = [...inheritedRequired, ...collectRequired(current, doc)];
936
933
  const requiredSet = new Set(required);
937
934
  const nestedRows = (propSchema) => {
938
- if (!options.deep) return [];
935
+ if (!options.deep || isComponentRef(propSchema)) return [];
939
936
  const prop = expandSchema(propSchema, doc, within);
940
937
  if (!prop) return [];
941
938
  if (hasFields(prop.schema)) return flattenFields(prop.schema, doc, nestedPrefix, options, [], prop.inside);
942
939
  const item = isArraySchema(prop.schema) ? arrayItemSchema(prop.schema) : void 0;
940
+ if (item && isComponentRef(item)) return [];
943
941
  const resolvedItem = item ? expandSchema(item, doc, prop.inside) : void 0;
944
942
  if (resolvedItem && hasFields(resolvedItem.schema)) return flattenFields(resolvedItem.schema, doc, nestedPrefix, options, [], resolvedItem.inside);
945
943
  return [];
@@ -958,7 +956,7 @@ function flattenFields(schema, doc, prefix, options, inheritedRequired = [], ins
958
956
  const inherited = (current.allOf ?? []).flatMap((part) => flattenFields(part, doc, prefix, options, required, within));
959
957
  const own = isObjectSchema(current) ? Object.entries(current.properties).filter(([, propSchema]) => isSchemaLike(propSchema) && !isHiddenProperty(propSchema, doc, options.direction)).flatMap(([key, propSchema]) => [makeRow(key, propSchema, requiredSet.has(key)), ...nestedRows(propSchema)]) : [];
960
958
  const extra = isSchemaLike(current.additionalProperties) ? [makeRow("**additionalProperties**", current.additionalProperties, false), ...nestedRows(current.additionalProperties)] : [];
961
- const variants = variantsOf(current).flatMap((variant) => [makeRow(`*${variant.keyword}*`, variant.schema, false), ...flattenFields(variant.schema, doc, prefix, options, required, within)]);
959
+ const variants = variantsOf(current).flatMap((variant) => [makeRow(`*${variant.keyword}*`, variant.schema, false), ...isComponentRef(variant.schema) ? [] : flattenFields(variant.schema, doc, prefix, options, required, within)]);
962
960
  const rows = [
963
961
  ...inherited,
964
962
  ...own,
@@ -976,6 +974,7 @@ function flattenFields(schema, doc, prefix, options, inheritedRequired = [], ins
976
974
  description: "none",
977
975
  enums: []
978
976
  }] : [];
977
+ if (isComponentRef(item)) return anonymous;
979
978
  const resolvedItem = expandSchema(item, doc, within);
980
979
  if (!(resolvedItem && hasFields(resolvedItem.schema))) return anonymous;
981
980
  return [...anonymous, ...flattenFields(resolvedItem.schema, doc, "»", {
@@ -1,6 +1,6 @@
1
- import { t as OpenAPI } from "../../../index-tsPqeV6H.js";
1
+ import { t as OpenAPI } from "../../../index-B3ze4n_I.js";
2
2
  //#region src/generator/zod-openapi-hono/openapi/index.d.ts
3
- export declare function zodOpenAPIHono(openapi: OpenAPI, options?: {
3
+ export declare function zodOpenAPIHono(document: OpenAPI, options?: {
4
4
  readonly readonly?: boolean;
5
5
  readonly exportSchemas?: boolean;
6
6
  readonly exportSchemasTypes?: boolean;
@@ -1 +1 @@
1
- export { t as zodOpenAPIHono } from "../../../openapi-KOHVzQbz.js";
1
+ export { t as zodOpenAPIHono } from "../../../openapi-CuyeukCF.js";
@@ -1,7 +1,7 @@
1
- import { s as HTTP_METHODS } from "./constants-Bz8YiPum.js";
1
+ import { s as HTTP_METHODS } from "./constants-CxrXPVxh.js";
2
2
  import { i as GenerateError } from "./format-CuHABcKC.js";
3
- import { L as isOpenAPIPaths, _ as toIdentifierPascalCase, f as methodPath, n as capitalize, q as isRecord, x as hasNoContentResponse, z as isOperationLike } from "./utils-vw99OasL.js";
4
- import { c as makeGroupClientName, i as parsePathItem, l as operationTags, n as makeOperationDeps, r as operationHasArgs, t as formatPath } from "./rpc-Bgtv3nGI.js";
3
+ import { B as isOperationLike, C as hasNoContentResponse, J as isRecord, R as isOpenAPIPaths, n as capitalize, p as methodPath, v as toIdentifierPascalCase } from "./utils-v71BPo5C.js";
4
+ import { c as makeGroupClientName, i as parsePathItem, l as operationTags, n as makeOperationDeps, r as operationHasArgs, t as formatPath } from "./rpc-BOAnGH-n.js";
5
5
  import { t as emit } from "./emit-uwlZZeRM.js";
6
6
  import { Effect } from "effect";
7
7
  import path from "node:path";
@@ -418,8 +418,8 @@ type Schema$1 = {
418
418
  readonly 'x-coerce'?: boolean;
419
419
  /**
420
420
  * Opt into `z.stringbool()` for boolean schemas. Use `true` for the default
421
- * truthy/falsy lists, or pass an object to customize. Mutually exclusive
422
- * with `x-coerce: true` on the same schema (build error).
421
+ * truthy/falsy lists, or pass an object to customize. Beside it, `x-coerce`
422
+ * has nothing left to read: `z.stringbool()` is what the schema emits.
423
423
  * @see https://zod.dev/api?id=stringbool
424
424
  */
425
425
  readonly 'x-stringbool'?: true | {
@@ -6,7 +6,7 @@ declare const HOOK_LIBRARIES: readonly ['swr', 'tanstack-query', 'preact-query',
6
6
  //#endregion
7
7
  //#region src/config/index.d.ts
8
8
  declare const ConfigSchema: Schema.decodeTo<Schema.toType<Schema.Struct<{
9
- readonly input: Schema.declare<`${string}.json` | `${string}.tsp` | `${string}.yaml`, `${string}.json` | `${string}.tsp` | `${string}.yaml`>;
9
+ readonly input: Schema.declare<`${string}.json` | `${string}.tsp` | `${string}.yaml` | `${string}.yml`, `${string}.json` | `${string}.tsp` | `${string}.yaml` | `${string}.yml`>;
10
10
  readonly output: Schema.optionalKey<Schema.declare<`${string}.ts`, `${string}.ts`>>;
11
11
  readonly basePath: Schema.withDecodingDefault<Schema.String, never>;
12
12
  readonly readonly: Schema.optionalKey<Schema.Boolean>;
@@ -220,7 +220,7 @@ declare const ConfigSchema: Schema.decodeTo<Schema.toType<Schema.Struct<{
220
220
  readonly baseUrl: Schema.optionalKey<Schema.String>;
221
221
  }>]>>;
222
222
  }>>, Schema.Struct<{
223
- readonly input: Schema.declare<`${string}.json` | `${string}.tsp` | `${string}.yaml`, `${string}.json` | `${string}.tsp` | `${string}.yaml`>;
223
+ readonly input: Schema.declare<`${string}.json` | `${string}.tsp` | `${string}.yaml` | `${string}.yml`, `${string}.json` | `${string}.tsp` | `${string}.yaml` | `${string}.yml`>;
224
224
  readonly output: Schema.optionalKey<Schema.declare<`${string}.ts`, `${string}.ts`>>;
225
225
  readonly basePath: Schema.withDecodingDefault<Schema.String, never>;
226
226
  readonly readonly: Schema.optionalKey<Schema.Boolean>;
@@ -441,7 +441,7 @@ declare const ConfigError_base: Schema.Class<ConfigError, Schema.TaggedStruct<"C
441
441
  }>, import("effect/Cause").YieldableError>;
442
442
  declare class ConfigError extends ConfigError_base {}
443
443
  declare function parseConfig(config: unknown): Effect.Effect<{
444
- readonly input: `${string}.json` | `${string}.tsp` | `${string}.yaml`;
444
+ readonly input: `${string}.json` | `${string}.tsp` | `${string}.yaml` | `${string}.yml`;
445
445
  readonly output?: `${string}.ts`;
446
446
  readonly basePath: string;
447
447
  readonly readonly?: boolean;
@@ -656,7 +656,7 @@ declare function parseConfig(config: unknown): Effect.Effect<{
656
656
  };
657
657
  }, ConfigError, never>;
658
658
  declare function readConfig(configPath?: string, reload?: boolean): Effect.Effect<{
659
- readonly input: `${string}.json` | `${string}.tsp` | `${string}.yaml`;
659
+ readonly input: `${string}.json` | `${string}.tsp` | `${string}.yaml` | `${string}.yml`;
660
660
  readonly output?: `${string}.ts`;
661
661
  readonly basePath: string;
662
662
  readonly readonly?: boolean;
@@ -1,5 +1,5 @@
1
- import "./index-DhipYt_q.js";
2
- import "./index-tsPqeV6H.js";
1
+ import "./index-CtUxilW-.js";
2
+ import "./index-B3ze4n_I.js";
3
3
  import { Effect } from "effect";
4
4
  //#region src/helper/group.d.ts
5
5
  /**
package/dist/index.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { a as parseConfig, i as defineConfig, n as ConfigError, o as readConfig, r as ConfigInput, t as Config } from "./index-DhipYt_q.js";
1
+ import { a as parseConfig, i as defineConfig, n as ConfigError, o as readConfig, r as ConfigInput, t as Config } from "./index-CtUxilW-.js";
2
2
  export { Config, ConfigError, ConfigInput, defineConfig, parseConfig, readConfig };
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
- import { c as IDENTIFIER_PATTERN, l as INPUT_EXTENSIONS, n as COMPONENT_NAMES, o as HOOK_LIBRARIES } from "./constants-Bz8YiPum.js";
1
+ import { c as IDENTIFIER_PATTERN, l as INPUT_EXTENSIONS, n as COMPONENT_NAMES, o as HOOK_LIBRARIES } from "./constants-CxrXPVxh.js";
2
2
  import { Effect, FileSystem, Schema, SchemaIssue, SchemaTransformation } from "effect";
3
3
  import { posix, resolve } from "node:path";
4
4
  import { pathToFileURL } from "node:url";
5
5
  //#region src/config/index.ts
6
6
  const ConfigSchema = Schema.Struct({
7
- input: Schema.declare(Schema.is(Schema.TemplateLiteral([Schema.String, Schema.Literals(INPUT_EXTENSIONS)])), { message: "must be .yaml | .json | .tsp" }).annotate({
7
+ input: Schema.declare(Schema.is(Schema.TemplateLiteral([Schema.String, Schema.Literals(INPUT_EXTENSIONS)])), { message: "must be .yaml | .yml | .json | .tsp" }).annotate({
8
8
  title: "Input document",
9
9
  description: "OpenAPI or TypeSpec entry document that every generator reads.",
10
10
  examples: [
@@ -1,5 +1,5 @@
1
- import { i as FORM_MEDIA_TYPES, r as COMPONENT_REF_PREFIX, s as HTTP_METHODS, t as ARROW_FUNCTION_PATTERN } from "./constants-Bz8YiPum.js";
2
- import { $ as isSchemaObject, A as isHeader, B as isParameter, C as hasNotProperty, D as isCallbacks, E as hasTypelessConstraint, G as isPathItemEntry, I as isOffsetTime, J as isRefObject, K as isPathItemRef, M as isInheritedName, O as isDiscriminableBranch, P as isMedia, Q as isSchemaArray, R as isOperation, S as hasNoUserChain, U as isParameterRef, W as isPathItem, Y as isRefOnly, Z as isResponses, _ as toIdentifierPascalCase, a as error, at as isValidIdent, b as zodToOpenAPISchema, d as makeStringLiteral, f as methodPath, h as requestParamsArray, i as ensureSuffix, k as isExamplesInput, m as renderNamedImport, p as normalizeTypes, q as isRecord, r as cyclicNodes, rt as isSingleSchema, s as escapeRegexLiteral, t as baseError, u as makeSafeKey, v as uncapitalize } from "./utils-vw99OasL.js";
1
+ import { i as FORM_MEDIA_TYPES, r as COMPONENT_REF_PREFIX, s as HTTP_METHODS, t as ARROW_FUNCTION_PATTERN } from "./constants-CxrXPVxh.js";
2
+ import { $ as isSchemaArray, A as isExamplesInput, F as isMedia, G as isPathItem, J as isRecord, K as isPathItemEntry, L as isOffsetTime, N as isInheritedName, O as hasTypelessConstraint, Q as isResponses, S as discriminatedBranches, T as hasNotProperty, V as isParameter, W as isParameterRef, X as isRefOnly, Y as isRefObject, a as ensureSuffix, c as escapeRegexLiteral, d as makeSafeKey, et as isSchemaObject, f as makeStringLiteral, g as requestParamsArray, h as renderNamedImport, i as decodePercent, it as isSingleSchema, j as isHeader, k as isCallbacks, m as normalizeTypes, o as error, ot as isValidIdent, p as methodPath, q as isPathItemRef, r as cyclicNodes, t as baseError, v as toIdentifierPascalCase, w as hasNoUserChain, x as zodToOpenAPISchema, y as uncapitalize, z as isOperation } from "./utils-v71BPo5C.js";
3
3
  import path from "node:path";
4
4
  import { parseSync, visitorKeys } from "oxc-parser";
5
5
  //#region src/helper/wire.ts
@@ -24,7 +24,7 @@ function resolveSchemaRef(ref, schemas) {
24
24
  if (!ref.startsWith(COMPONENT_REF_PREFIX.schemas)) return void 0;
25
25
  const name = ref.slice(COMPONENT_REF_PREFIX.schemas.length);
26
26
  if (name.includes("/")) return void 0;
27
- return schemas?.[decodeURIComponent(name)];
27
+ return schemas?.[decodePercent(name)];
28
28
  }
29
29
  function primitiveKind(value) {
30
30
  if (value === null) return null;
@@ -545,10 +545,10 @@ function makeRef($ref) {
545
545
  }
546
546
  ];
547
547
  const propertiesMatch = $ref.match(/^#\/components\/schemas\/([^/]+)\/properties\/(.+)$/u);
548
- if (propertiesMatch) return `z.lazy(()=>${toIdentifierPascalCase(ensureSuffix(decodeURIComponent(propertiesMatch[1]), "Schema"))})`;
548
+ if (propertiesMatch) return `z.lazy(()=>${toIdentifierPascalCase(ensureSuffix(decodePercent(propertiesMatch[1]), "Schema"))})`;
549
549
  const rawRef = $ref.split("/").at(-1);
550
550
  if (!rawRef) return "Schema";
551
- const decodedRef = decodeURIComponent(rawRef);
551
+ const decodedRef = decodePercent(rawRef);
552
552
  const match = COMPONENT_SUFFIX_MAP.find(({ prefix }) => $ref.startsWith(prefix));
553
553
  return toIdentifierPascalCase(ensureSuffix(decodedRef, match?.suffix ?? "Schema"));
554
554
  }
@@ -1136,7 +1136,7 @@ function wrap(zod, schema, meta, options) {
1136
1136
  const style = parameter === void 0 ? void 0 : wireStyle(parameter, typeList.includes("array"));
1137
1137
  const readers = [...options?.readers ?? [], ...style === void 0 ? [] : [style]];
1138
1138
  const acceptBothArities = (inner) => readers.reduceRight((read, reader) => `z.preprocess(${reader},${read})`, inner);
1139
- const isNullable = schema.nullable === true || (Array.isArray(schema.type) ? schema.type.includes("null") : schema.type === "null");
1139
+ const isNullable = schema.nullable === true || typeList.includes("null") || schema.default === null;
1140
1140
  const build = (core) => {
1141
1141
  const typed = isNullable ? `${acceptBothArities(core)}.nullable()` : acceptBothArities(core);
1142
1142
  const n = options?.nullRead === "first" ? `z.preprocess(${WIRE_NULL},${typed})` : options?.nullRead === "last" ? `((schema)=>z.union([schema,z.preprocess(${WIRE_NULL},schema)]))(${typed})` : typed;
@@ -1938,7 +1938,6 @@ function string(schema, options) {
1938
1938
  //#endregion
1939
1939
  //#region src/generator/zod-to-openapi/index.ts
1940
1940
  function zodToOpenAPI(schema, meta, options) {
1941
- if (schema === void 0) throw new Error("Schema is undefined");
1942
1941
  if (schema === true) return wrap("z.any()", {}, meta, options);
1943
1942
  if (schema === false) return wrap("z.never()", {}, meta, options);
1944
1943
  const nullRead = options?.coerce === true && options.json !== true ? nullReading(schema, options.schemas) : void 0;
@@ -2075,16 +2074,7 @@ function zodToOpenAPI(schema, meta, options) {
2075
2074
  const discriminator = schema.discriminator?.propertyName;
2076
2075
  const oneOfMessage = schema["x-oneOf-message"] ?? schema["x-error-message"];
2077
2076
  const oneOfErrorArg = oneOfMessage ? `,${error(oneOfMessage)}` : "";
2078
- const branches = schema.oneOf.map((s) => s.$ref === void 0 ? s : isRefOnly(s) && s.$ref.startsWith(COMPONENT_REF_PREFIX.schemas) ? options?.schemas?.[decodeURIComponent(s.$ref.slice(COMPONENT_REF_PREFIX.schemas.length))] : void 0);
2079
- const literalsPerBranch = branches.map((branch) => {
2080
- if (discriminator === void 0 || branch === void 0) return void 0;
2081
- if (!isDiscriminableBranch(branch, discriminator)) return void 0;
2082
- const property = branch.properties?.[discriminator];
2083
- if (property === void 0 || typeof property === "boolean") return void 0;
2084
- return typeof property.const === "string" ? [property.const] : property.enum ?? [];
2085
- });
2086
- const literals = literalsPerBranch.flatMap((values) => values ?? []);
2087
- return done(discriminator !== void 0 && branches.length >= 2 && literalsPerBranch.every((values) => values !== void 0) && new Set(literals).size === literals.length ? `z.discriminatedUnion(${makeStringLiteral(discriminator)},[${oneOfSchemas.join(",")}]${oneOfErrorArg})` : `z.xor([${oneOfSchemas.join(",")}]${oneOfErrorArg})`, schema);
2077
+ return done(discriminator !== void 0 && discriminatedBranches(schema, options?.schemas) !== void 0 ? `z.discriminatedUnion(${makeStringLiteral(discriminator)},[${oneOfSchemas.join(",")}]${oneOfErrorArg})` : `z.xor([${oneOfSchemas.join(",")}]${oneOfErrorArg})`, schema);
2088
2078
  }
2089
2079
  if (schema.not !== void 0) {
2090
2080
  const notMessage = schema["x-not-message"] ?? schema["x-error-message"];
@@ -2168,11 +2158,9 @@ function zodToOpenAPI(schema, meta, options) {
2168
2158
  if (t.includes("boolean")) {
2169
2159
  const errorMessage = schema["x-error-message"];
2170
2160
  const requiredMessage = schema["x-required-message"];
2171
- const xCoerce = schema["x-coerce"] === true;
2172
2161
  const xStringbool = schema["x-stringbool"];
2173
- if (xCoerce && xStringbool !== void 0) throw new Error("x-coerce and x-stringbool are mutually exclusive on a boolean schema. Remove one.");
2174
- const arg = baseError(errorMessage, xCoerce ? void 0 : requiredMessage);
2175
2162
  if (xStringbool !== void 0) {
2163
+ const arg = baseError(errorMessage, requiredMessage);
2176
2164
  const opts = xStringbool === true ? null : xStringbool;
2177
2165
  const optsObj = opts ? {
2178
2166
  ...opts.truthy !== void 0 ? { truthy: opts.truthy } : {},
@@ -2183,6 +2171,8 @@ function zodToOpenAPI(schema, meta, options) {
2183
2171
  const combinedArg = optsStr && arg ? `${optsStr.slice(0, -1)},${arg.slice(1)}` : optsStr || arg;
2184
2172
  return done(combinedArg ? `z.stringbool(${combinedArg})` : "z.stringbool()", schema);
2185
2173
  }
2174
+ const xCoerce = schema["x-coerce"] === true;
2175
+ const arg = baseError(errorMessage, xCoerce ? void 0 : requiredMessage);
2186
2176
  const baseFn = xCoerce ? "z.coerce.boolean" : effective?.coerce ? "z.stringbool" : "z.boolean";
2187
2177
  return done(arg ? `${baseFn}(${arg})` : `${baseFn}()`, schema);
2188
2178
  }
@@ -2419,18 +2409,24 @@ function findCyclicSchemas(names, deps) {
2419
2409
  const nameDeps = new Map(names.map((n) => [n, (deps.get(n) ?? []).map((v) => var2name.get(v)).filter((x) => x !== void 0)]));
2420
2410
  return cyclicNodes(nameDeps);
2421
2411
  }
2412
+ /** Every schema under `schema`, itself first: the shapes a schema nests another in. */
2413
+ function nestedSchemas(schema) {
2414
+ if (schema === void 0 || typeof schema === "boolean") return [];
2415
+ const items = isSchemaArray(schema.items) ? schema.items : [schema.items];
2416
+ return [schema, ...[
2417
+ ...Object.values(schema.properties ?? {}),
2418
+ ...Object.values(schema.patternProperties ?? {}),
2419
+ ...schema.prefixItems ?? [],
2420
+ ...items,
2421
+ schema.additionalProperties,
2422
+ ...schema.allOf ?? [],
2423
+ ...schema.anyOf ?? [],
2424
+ ...schema.oneOf ?? [],
2425
+ schema.not
2426
+ ].flatMap(nestedSchemas)];
2427
+ }
2422
2428
  function findDiscriminatedBranches(schemas, schemaNames) {
2423
- return new Set(schemaNames.flatMap((n) => {
2424
- const schema = schemas[n];
2425
- const discriminator = schema?.discriminator?.propertyName;
2426
- if (discriminator === void 0 || schema?.oneOf === void 0) return [];
2427
- return schema.oneOf.flatMap((branch) => {
2428
- if (!(isRefOnly(branch) && branch.$ref?.startsWith(COMPONENT_REF_PREFIX.schemas))) return [];
2429
- const name = decodeURIComponent(branch.$ref.slice(COMPONENT_REF_PREFIX.schemas.length));
2430
- const target = schemas[name];
2431
- return target && isDiscriminableBranch(target, discriminator) ? [name] : [];
2432
- });
2433
- }));
2429
+ return new Set(schemaNames.flatMap((n) => nestedSchemas(schemas[n])).flatMap((schema) => discriminatedBranches(schema, schemas) ?? []).flatMap(({ name }) => name === void 0 ? [] : [name]));
2434
2430
  }
2435
2431
  function analyzeCircularSchemas(schemas, schemaNames, readonly) {
2436
2432
  const varNameSet = new Set(schemaNames.map((n) => toIdentifierPascalCase(ensureSuffix(n, "Schema"))));
@@ -2591,30 +2587,38 @@ function makeImports(code, fromFile, components, split = false, honoExtras = [])
2591
2587
  //#region src/helper/type.ts
2592
2588
  function makeTypeString(schema, selfTypeName, cyclicGroup, readonly) {
2593
2589
  if (!schema) return "unknown";
2590
+ const types = normalizeType(schema);
2591
+ const isNullable = schema.nullable === true || types.includes("null") || schema.default === null || (schema.enum?.includes(null) ?? false);
2592
+ const baseType = makeNonNullTypeString(schema, types.filter((t) => t !== "null"), selfTypeName, cyclicGroup, readonly);
2593
+ if (!isNullable || baseType === "null") return baseType;
2594
+ return `(${baseType}|null)`;
2595
+ }
2596
+ function makeNonNullTypeString(schema, types, selfTypeName, cyclicGroup, readonly) {
2594
2597
  if (schema.$ref) return makeRefTypeString(schema.$ref, selfTypeName);
2595
2598
  if (schema.oneOf && schema.oneOf.length > 0) return makeUnionTypeString(schema.oneOf, selfTypeName, cyclicGroup, "|", readonly);
2596
2599
  if (schema.anyOf && schema.anyOf.length > 0) return makeUnionTypeString(schema.anyOf, selfTypeName, cyclicGroup, "|", readonly);
2597
2600
  if (schema.allOf && schema.allOf.length > 0) return makeUnionTypeString(schema.allOf, selfTypeName, cyclicGroup, "&", readonly);
2598
- if (schema.enum && schema.enum.length > 0) return schema.enum.map((v) => typeof v === "string" ? makeStringLiteral(v) : String(v)).join("|");
2601
+ if (schema.enum && schema.enum.length > 0) {
2602
+ const values = schema.enum.filter((v) => v !== null);
2603
+ if (values.length === 0) return "null";
2604
+ return values.map((v) => typeof v === "string" ? makeStringLiteral(v) : String(v)).join("|");
2605
+ }
2599
2606
  if (schema.const !== void 0) {
2600
2607
  if (typeof schema.const === "string") return makeStringLiteral(schema.const);
2601
2608
  if (typeof schema.const === "number" || typeof schema.const === "boolean") return String(schema.const);
2602
2609
  return JSON.stringify(schema.const);
2603
2610
  }
2604
- const types = normalizeType(schema);
2605
- const isNullable = schema.nullable === true || types.includes("null");
2606
- const baseType = makeBaseTypeString(schema, types.filter((t) => t !== "null"), selfTypeName, cyclicGroup, readonly);
2607
- return isNullable ? `(${baseType}|null)` : baseType;
2611
+ return makeBaseTypeString(schema, types, selfTypeName, cyclicGroup, readonly);
2608
2612
  }
2609
2613
  function makeRefTypeString(ref, selfTypeName) {
2610
2614
  const propertiesMatch = ref.match(/^#\/components\/schemas\/([^/]+)\/properties\//u);
2611
2615
  if (propertiesMatch) {
2612
- const parentName = toIdentifierPascalCase(decodeURIComponent(propertiesMatch[1]));
2616
+ const parentName = toIdentifierPascalCase(decodePercent(propertiesMatch[1]));
2613
2617
  if (parentName === selfTypeName) return `${parentName}Type`;
2614
2618
  return `z.infer<typeof ${parentName}Schema>`;
2615
2619
  }
2616
2620
  const rawRef = ref.split("/").at(-1) ?? "";
2617
- const refName = toIdentifierPascalCase(decodeURIComponent(rawRef));
2621
+ const refName = toIdentifierPascalCase(decodePercent(rawRef));
2618
2622
  if (refName === selfTypeName) return `${refName}Type`;
2619
2623
  return `z.infer<typeof ${refName}Schema>`;
2620
2624
  }
@@ -2633,15 +2637,18 @@ function makeBaseTypeString(schema, types, selfTypeName, cyclicGroup, readonly)
2633
2637
  function makeSingleTypeString(schema, type, selfTypeName, cyclicGroup, readonly) {
2634
2638
  if (type === "string") return "string";
2635
2639
  if (type === "number") return "number";
2636
- if (type === "integer") return "number";
2640
+ if (type === "integer") return isBigintFormat(schema) ? "bigint" : "number";
2637
2641
  if (type === "boolean") return "boolean";
2638
2642
  if (type === "null") return "null";
2639
2643
  if (type === "array") return makeArrayTypeString(schema, selfTypeName, cyclicGroup, readonly);
2640
2644
  if (type === "object") return makeObjectTypeString(schema, selfTypeName, cyclicGroup, readonly);
2641
2645
  return "unknown";
2642
2646
  }
2647
+ function isBigintFormat(schema) {
2648
+ return schema.format === "int64" || schema.format === "uint64" || schema.format === "bigint";
2649
+ }
2643
2650
  function wrapForArrayElement(type) {
2644
- return type.startsWith("readonly ") ? `(${type})` : type;
2651
+ return type.startsWith("readonly ") || type.includes("|") && !type.startsWith("(") ? `(${type})` : type;
2645
2652
  }
2646
2653
  function makeArrayTypeString(schema, selfTypeName, cyclicGroup, readonly) {
2647
2654
  const prefix = readonly ? "readonly " : "";
@@ -2657,18 +2664,6 @@ function makeArrayTypeString(schema, selfTypeName, cyclicGroup, readonly) {
2657
2664
  if (firstItem !== void 0) return `${prefix}${wrapForArrayElement(makeTypeString(firstItem, selfTypeName, cyclicGroup, readonly))}[]`;
2658
2665
  return `${prefix}unknown[]`;
2659
2666
  }
2660
- if (items.$ref) {
2661
- const propertiesMatch = items.$ref.match(/^#\/components\/schemas\/([^/]+)\/properties\//u);
2662
- if (propertiesMatch) {
2663
- const parentName = toIdentifierPascalCase(decodeURIComponent(propertiesMatch[1]));
2664
- if (parentName === selfTypeName) return `${prefix}${parentName}Type[]`;
2665
- return `${prefix}z.infer<typeof ${parentName}Schema>[]`;
2666
- }
2667
- const rawRef = items.$ref.split("/").at(-1) ?? "";
2668
- const refName = toIdentifierPascalCase(decodeURIComponent(rawRef));
2669
- if (refName === selfTypeName) return `${prefix}${refName}Type[]`;
2670
- return `${prefix}z.infer<typeof ${refName}Schema>[]`;
2671
- }
2672
2667
  return `${prefix}${wrapForArrayElement(makeTypeString(items, selfTypeName, cyclicGroup, readonly))}[]`;
2673
2668
  }
2674
2669
  function makeObjectTypeString(schema, selfTypeName, cyclicGroup, readonly) {
@@ -3074,13 +3069,70 @@ function routeCode(openapi, readonly) {
3074
3069
  return makeRouteEntries(openapi, readonly).map((entry) => entry.code).join("\n\n");
3075
3070
  }
3076
3071
  //#endregion
3072
+ //#region src/helper/pointer.ts
3073
+ /**
3074
+ * Inlines every `$ref` whose pointer names no component, so that what reaches the
3075
+ * generators is either a component (`#/components/<section>/<name>`, emitted as the
3076
+ * identifier it is declared under) or the schema itself.
3077
+ *
3078
+ * A bundler keeps internal references as they are, and a document may refer to an inline
3079
+ * schema wherever it sits: `#/paths/~1partners~1upsert/put/requestBody/content/
3080
+ * application~1json/schema` (freee), or `#/components/parameters/Page/schema`. Named after
3081
+ * its last segment, such a reference became `SchemaSchema`, which nothing declares. The
3082
+ * target is already in the document, so it is written in place of the reference, with the
3083
+ * keywords beside the `$ref` (a `description`) kept over the target's own. A pointer that
3084
+ * names nothing, or that comes back to itself, is left as written.
3085
+ */
3086
+ function inlinePointerRefs(document) {
3087
+ const inline = (node, inlining) => {
3088
+ if (Array.isArray(node)) return node.map((item) => inline(item, inlining));
3089
+ if (!isRecord(node)) return node;
3090
+ const walked = (record) => Object.fromEntries(Object.entries(record).map(([key, value]) => [key, inline(value, inlining)]));
3091
+ const { $ref, ...beside } = node;
3092
+ if (typeof $ref === "string" && isInlinePointer($ref) && !inlining.has($ref)) {
3093
+ const target = resolvePointer(document, $ref);
3094
+ if (isRecord(target)) {
3095
+ const inlined = inline(target, /* @__PURE__ */ new Set([...inlining, $ref]));
3096
+ if (isRecord(inlined)) return {
3097
+ ...inlined,
3098
+ ...walked(beside)
3099
+ };
3100
+ }
3101
+ }
3102
+ return walked(node);
3103
+ };
3104
+ return {
3105
+ ...document,
3106
+ ...Object.fromEntries(Object.entries(document).map(([key, value]) => [key, inline(value, /* @__PURE__ */ new Set())]))
3107
+ };
3108
+ }
3109
+ /** A local pointer that does not name a component, nor a property of a component schema. */
3110
+ function isInlinePointer(ref) {
3111
+ if (!ref.startsWith("#/")) return false;
3112
+ const segments = pointerSegments(ref);
3113
+ if (segments[0] !== "components") return true;
3114
+ if (segments.length === 3) return false;
3115
+ return !(segments[1] === "schemas" && segments[3] === "properties" && segments.length > 4);
3116
+ }
3117
+ /** The segments of a JSON Pointer fragment, decoded: percent-encoding, then `~1` and `~0` (RFC 6901 §6). */
3118
+ function pointerSegments(ref) {
3119
+ return ref.slice(2).split("/").map((segment) => decodePercent(segment).replaceAll("~1", "/").replaceAll("~0", "~"));
3120
+ }
3121
+ function resolvePointer(document, ref) {
3122
+ return pointerSegments(ref).reduce((node, segment) => {
3123
+ if (Array.isArray(node)) return node[Number(segment)];
3124
+ if (isRecord(node)) return Object.hasOwn(node, segment) ? node[segment] : void 0;
3125
+ }, document);
3126
+ }
3127
+ //#endregion
3077
3128
  //#region src/generator/zod-openapi-hono/openapi/webhooks/index.ts
3078
3129
  function webhookCode(openapi, readonly) {
3079
3130
  return makeWebhookEntries(openapi, readonly).map((entry) => entry.code).join("\n\n");
3080
3131
  }
3081
3132
  //#endregion
3082
3133
  //#region src/generator/zod-openapi-hono/openapi/index.ts
3083
- function zodOpenAPIHono(openapi, options = {}) {
3134
+ function zodOpenAPIHono(document, options = {}) {
3135
+ const openapi = inlinePointerRefs(document);
3084
3136
  const components = openapi.components ? componentsCode(openapi.components, options) : "";
3085
3137
  const routes = routeCode(openapi, options.readonly);
3086
3138
  const webhooks = webhookCode(openapi, options.readonly);
@@ -24,7 +24,11 @@ function parseOpenAPI(input) {
24
24
  if (!document) throw new Error(`TypeSpec emitted no OpenAPI document: ${input}`);
25
25
  return document;
26
26
  },
27
- catch: (error) => new OpenAPIError({ message: error instanceof Error ? error.message : String(error) })
27
+ catch: (error) => {
28
+ if (!(error instanceof Error)) return new OpenAPIError({ message: String(error) });
29
+ const code = "ioErrorCode" in error ? error.ioErrorCode : void 0;
30
+ return new OpenAPIError({ message: (!error.message.trim() || error.message.trimEnd().endsWith(":")) && typeof code === "string" && code ? `${error.message}${code}` : error.message });
31
+ }
28
32
  });
29
33
  }
30
34
  //#endregion
@@ -1,5 +1,5 @@
1
- import { i as FORM_MEDIA_TYPES, u as JSON_MEDIA_TYPE } from "./constants-Bz8YiPum.js";
2
- import { H as isParameterObject, J as isRefObject, at as isValidIdent, et as isSchemaProperty, q as isRecord, z as isOperationLike } from "./utils-vw99OasL.js";
1
+ import { i as FORM_MEDIA_TYPES, u as JSON_MEDIA_TYPE } from "./constants-CxrXPVxh.js";
2
+ import { B as isOperationLike, J as isRecord, U as isParameterObject, Y as isRefObject, ot as isValidIdent, tt as isSchemaProperty } from "./utils-v71BPo5C.js";
3
3
  //#region src/helper/group.ts
4
4
  const RESERVED = /* @__PURE__ */ new Set([
5
5
  "arguments",
@@ -1,10 +1,10 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
2
- import { n as COMPONENT_NAMES, o as HOOK_LIBRARIES } from "./constants-Bz8YiPum.js";
2
+ import { n as COMPONENT_NAMES, o as HOOK_LIBRARIES } from "./constants-CxrXPVxh.js";
3
3
  import { i as GenerateError } from "./format-CuHABcKC.js";
4
- import { C as isInsideDirectory, E as makeGeneratedImport, S as appEntryOutput, T as makeAppEntryImport, _ as headers, a as takibi, b as client, c as securitySchemes, d as requestBodies, f as pathItems, g as links, h as mediaTypes, i as defineTemplate, l as schemas, m as components, n as webhooks, o as route, p as parameters, r as template, s as mock, u as responses, v as examples, w as makeAppEntryFile, x as handlerGroupOf, y as callbacks } from "./core-BhMCMrQ6.js";
4
+ import { C as isInsideDirectory, E as makeGeneratedImport, S as appEntryOutput, T as makeAppEntryImport, _ as headers, a as takibi, b as client, c as securitySchemes, d as requestBodies, f as pathItems, g as links, h as mediaTypes, i as defineTemplate, l as schemas, m as components, n as webhooks, o as route, p as parameters, r as template, s as mock, u as responses, v as examples, w as makeAppEntryFile, x as handlerGroupOf, y as callbacks } from "./core-rnNgBu4D.js";
5
5
  import { a as unlink, i as readdir, t as exists } from "./file-K6j5IJXi.js";
6
- import { t as hooks } from "./hooks-CR7angVC.js";
7
- import { t as docs } from "./docs-C5t1NRQ8.js";
6
+ import { t as hooks } from "./hooks-RrTkHWCS.js";
7
+ import { t as docs } from "./docs-BApYjFQG.js";
8
8
  import { rpc } from "./core/rpc/index.js";
9
9
  import { type } from "./core/type/index.js";
10
10
  import { Effect, FileSystem, Schema } from "effect";
@@ -1,4 +1,4 @@
1
- import { c as IDENTIFIER_PATTERN, r as COMPONENT_REF_PREFIX, s as HTTP_METHODS, t as ARROW_FUNCTION_PATTERN } from "./constants-Bz8YiPum.js";
1
+ import { c as IDENTIFIER_PATTERN, r as COMPONENT_REF_PREFIX, s as HTTP_METHODS, t as ARROW_FUNCTION_PATTERN } from "./constants-CxrXPVxh.js";
2
2
  //#region src/guard/index.ts
3
3
  function isRecord(v) {
4
4
  return typeof v === "object" && v !== null && !Array.isArray(v);
@@ -40,6 +40,44 @@ function isDiscriminableBranch(branch, discriminator) {
40
40
  if (typeof property.const === "string") return true;
41
41
  return Array.isArray(property.enum) && property.enum.length > 0 && property.enum.every((v) => typeof v === "string");
42
42
  }
43
+ /**
44
+ * The branches of a discriminated `oneOf`, resolved, when `z.discriminatedUnion` stands for
45
+ * it; `undefined` when the `oneOf` is emitted as `z.xor`. The two are equivalent only when
46
+ * every branch is a plain object that `required`s the discriminator and pins it to string
47
+ * literals (see `isDiscriminableBranch`), and no two branches share a literal.
48
+ */
49
+ function decodePercentRef(value) {
50
+ try {
51
+ return decodeURIComponent(value);
52
+ } catch {
53
+ return value;
54
+ }
55
+ }
56
+ function discriminatedBranches(schema, schemas) {
57
+ const discriminator = schema.discriminator?.propertyName;
58
+ if (discriminator === void 0 || schema.oneOf === void 0 || schema.oneOf.length < 2) return;
59
+ const resolved = schema.oneOf.map((s) => {
60
+ if (s.$ref === void 0) return {
61
+ branch: s,
62
+ name: void 0
63
+ };
64
+ if (!(isRefOnly(s) && s.$ref.startsWith(COMPONENT_REF_PREFIX.schemas))) return void 0;
65
+ const name = decodePercentRef(s.$ref.slice(COMPONENT_REF_PREFIX.schemas.length));
66
+ const branch = schemas?.[name];
67
+ return branch === void 0 ? void 0 : {
68
+ branch,
69
+ name
70
+ };
71
+ });
72
+ const literalsPerBranch = resolved.map((entry) => {
73
+ if (entry === void 0 || !isDiscriminableBranch(entry.branch, discriminator)) return void 0;
74
+ const property = entry.branch.properties?.[discriminator];
75
+ if (property === void 0 || typeof property === "boolean") return void 0;
76
+ return typeof property.const === "string" ? [property.const] : property.enum ?? [];
77
+ });
78
+ const literals = literalsPerBranch.flatMap((values) => values ?? []);
79
+ return literalsPerBranch.every((values) => values !== void 0) && new Set(literals).size === literals.length ? resolved.filter((entry) => entry !== void 0) : void 0;
80
+ }
43
81
  function isParameterRef(ref) {
44
82
  return ref.startsWith(COMPONENT_REF_PREFIX.parameters);
45
83
  }
@@ -222,9 +260,29 @@ function normalizeTypes(t) {
222
260
  */
223
261
  function methodPath(method, path) {
224
262
  const hasTrailingSlash = path !== "/" && path.endsWith("/");
225
- const apiPath = path.replaceAll(/[^A-Za-z0-9]/gu, " ").trim().split(/\s+/u).map((str) => `${str.charAt(0).toUpperCase()}${str.slice(1)}`).join("");
263
+ const apiPath = path.split("/").filter((segment) => segment !== "").map((segment) => /[A-Za-z0-9]/u.test(segment) ? segment.replaceAll(/[^A-Za-z0-9]/gu, " ") : Array.from(segment, symbolWord).join(" ")).join(" ").trim().split(/\s+/u).map((str) => `${str.charAt(0).toUpperCase()}${str.slice(1)}`).join("");
226
264
  return apiPath ? `${method}${apiPath}${hasTrailingSlash ? "Index" : ""}` : method;
227
265
  }
266
+ const SYMBOL_WORDS = {
267
+ "-": "Dash",
268
+ _: "Underscore",
269
+ ".": "Dot",
270
+ "~": "Tilde",
271
+ "@": "At",
272
+ $: "Dollar",
273
+ "!": "Bang",
274
+ "*": "Star",
275
+ "+": "Plus",
276
+ ",": "Comma",
277
+ ";": "Semicolon",
278
+ "=": "Equals",
279
+ ":": "Colon",
280
+ "%": "Percent"
281
+ };
282
+ /** The word a path segment of punctuation alone is named by, one per character. */
283
+ function symbolWord(char) {
284
+ return SYMBOL_WORDS[char] ?? `U${(char.codePointAt(0) ?? 0).toString(16).toUpperCase()}`;
285
+ }
228
286
  /**
229
287
  * Generates an array of Zod validator strings from OpenAPI parameter objects.
230
288
  */
@@ -424,6 +482,18 @@ function ensureSuffix(text, suffix) {
424
482
  return `${text}${suffix}`;
425
483
  }
426
484
  /**
485
+ * Undoes the percent-encoding of one `$ref` segment. A segment that is not valid
486
+ * percent-encoding (`Foo%ZZ`) is kept as it is: no `$ref` makes the generator throw, it
487
+ * just names a component that is not there.
488
+ */
489
+ function decodePercent(value) {
490
+ try {
491
+ return decodeURIComponent(value);
492
+ } catch {
493
+ return value;
494
+ }
495
+ }
496
+ /**
427
497
  * Generates a Zod schema constant and optional inferred type alias.
428
498
  *
429
499
  *
@@ -546,4 +616,4 @@ function cyclicNodes(deps) {
546
616
  return result;
547
617
  }
548
618
  //#endregion
549
- export { isSchemaObject as $, isHeader as A, isParameter as B, hasNotProperty as C, isCallbacks as D, hasTypelessConstraint as E, isMediaWithSchema as F, isPathItemEntry as G, isParameterObject as H, isOffsetTime as I, isRefObject as J, isPathItemRef as K, isOpenAPIPaths as L, isInheritedName as M, isInlineMedia as N, isDiscriminableBranch as O, isMedia as P, isSchemaArray as Q, isOperation as R, hasNoUserChain as S, hasRequestBodyContent as T, isParameterRef as U, isParameterArray as V, isPathItem as W, isRequestBody as X, isRefOnly as Y, isResponses as Z, toIdentifierPascalCase as _, error as a, isValidIdent as at, zodToOpenAPISchema as b, makeBarrel as c, makeStringLiteral as d, isSchemaProperty as et, methodPath as f, statusCodeToNumber as g, requestParamsArray as h, ensureSuffix as i, isStringRef as it, isHttpMethod as j, isExamplesInput as k, makeInferRequestType as l, renderNamedImport as m, capitalize as n, isSecurityScheme as nt, escapeHtml as o, normalizeTypes as p, isRecord as q, cyclicNodes as r, isSingleSchema as rt, escapeRegexLiteral as s, baseError as t, isSecurityArray as tt, makeSafeKey as u, uncapitalize as v, hasNumericConstraint as w, hasNoContentResponse as x, uncapitalizeWord as y, isOperationLike as z };
619
+ export { isSchemaArray as $, isExamplesInput as A, isOperationLike as B, hasNoContentResponse as C, hasRequestBodyContent as D, hasNumericConstraint as E, isMedia as F, isPathItem as G, isParameterArray as H, isMediaWithSchema as I, isRecord as J, isPathItemEntry as K, isOffsetTime as L, isHttpMethod as M, isInheritedName as N, hasTypelessConstraint as O, isInlineMedia as P, isResponses as Q, isOpenAPIPaths as R, discriminatedBranches as S, hasNotProperty as T, isParameterObject as U, isParameter as V, isParameterRef as W, isRefOnly as X, isRefObject as Y, isRequestBody as Z, statusCodeToNumber as _, ensureSuffix as a, isStringRef as at, uncapitalizeWord as b, escapeRegexLiteral as c, makeSafeKey as d, isSchemaObject as et, makeStringLiteral as f, requestParamsArray as g, renderNamedImport as h, decodePercent as i, isSingleSchema as it, isHeader as j, isCallbacks as k, makeBarrel as l, normalizeTypes as m, capitalize as n, isSecurityArray as nt, error as o, isValidIdent as ot, methodPath as p, isPathItemRef as q, cyclicNodes as r, isSecurityScheme as rt, escapeHtml as s, baseError as t, isSchemaProperty as tt, makeInferRequestType as u, toIdentifierPascalCase as v, hasNoUserChain as w, zodToOpenAPISchema as x, uncapitalize as y, isOperation as z };
@@ -1,10 +1,10 @@
1
- import { l as INPUT_EXTENSIONS } from "../constants-Bz8YiPum.js";
1
+ import { l as INPUT_EXTENSIONS } from "../constants-CxrXPVxh.js";
2
2
  import { parseConfig } from "../index.js";
3
3
  import { t as FormatOptions } from "../format-CuHABcKC.js";
4
- import { q as isRecord } from "../utils-vw99OasL.js";
5
- import { C as isInsideDirectory, S as appEntryOutput } from "../core-BhMCMrQ6.js";
6
- import { n as parseOpenAPI } from "../openapi-DEZCoJlc.js";
7
- import { i as packageRoots, n as makeJob, r as outsideSources, t as cleanSplitOutputs } from "../shared-BxcbHfBt.js";
4
+ import { J as isRecord } from "../utils-v71BPo5C.js";
5
+ import { C as isInsideDirectory, S as appEntryOutput } from "../core-rnNgBu4D.js";
6
+ import { n as parseOpenAPI } from "../openapi-t_u-tF52.js";
7
+ import { i as packageRoots, n as makeJob, r as outsideSources, t as cleanSplitOutputs } from "../shared-Tq3KgO4s.js";
8
8
  import { Effect, FileSystem, Option, Result } from "effect";
9
9
  import path from "node:path";
10
10
  import crypto from "node:crypto";
@@ -173,7 +173,7 @@ function runAllGenerationTasks(config) {
173
173
  /**
174
174
  * Adds glob patterns to the Vite file watcher.
175
175
  *
176
- * Watches the input file and related files (.yaml, .json, .tsp) in the
176
+ * Watches the input file and related files (.yaml, .yml, .json, .tsp) in the
177
177
  * same directory for changes.
178
178
  */
179
179
  function addInputGlobsToWatcher(server, absoluteInputPath) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hono-takibi",
3
- "version": "0.23.0",
3
+ "version": "0.25.0",
4
4
  "description": "Hono Takibi is a code generator from OpenAPI to @hono/zod-openapi",
5
5
  "keywords": [
6
6
  "hono",