hono-takibi 0.19.0 → 0.20.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
@@ -4,7 +4,7 @@ import { NodeRuntime, NodeServices } from "@effect/platform-node";
4
4
  import { Console, Effect, FileSystem, Option, Path, Ref, Schema, Stream } from "effect";
5
5
  import { Argument, CliError, Command, Flag } from "effect/cli";
6
6
  //#region package.json
7
- var version = "0.19.0";
7
+ var version = "0.20.0";
8
8
  var description = "Hono Takibi is a code generator from OpenAPI to @hono/zod-openapi";
9
9
  //#endregion
10
10
  //#region src/cli/index.ts
@@ -41,7 +41,7 @@ function runJobs(config) {
41
41
  const [{ parseOpenAPI }, { FormatOptions }, { cleanSplitOutputs, makeJob, packageRoots }] = yield* Effect.promise(() => Promise.all([
42
42
  import("./openapi-DQRxq2_O.js").then((n) => n.t),
43
43
  import("./format-CuHABcKC.js").then((n) => n.r),
44
- import("./shared-DBOBTH7X.js").then((n) => n.a)
44
+ import("./shared-_h_FDhSi.js").then((n) => n.a)
45
45
  ]));
46
46
  const openAPI = yield* parseOpenAPI(config.input);
47
47
  const jobs = makeJob(openAPI, config, yield* packageRoots(openAPI, config));
@@ -79,7 +79,7 @@ function reportJobs(config, previous) {
79
79
  onFailure: (error) => Console.error(`❌ ${error.message}`),
80
80
  onSuccess: (report) => Console.log(report)
81
81
  }));
82
- const { outsideSources } = yield* Effect.promise(() => import("./shared-DBOBTH7X.js").then((n) => n.a));
82
+ const { outsideSources } = yield* Effect.promise(() => import("./shared-_h_FDhSi.js").then((n) => n.a));
83
83
  const inputDirectory = path.dirname(path.resolve(config.input));
84
84
  return {
85
85
  inputDirectory,
@@ -206,7 +206,7 @@ function generate(args) {
206
206
  })]
207
207
  });
208
208
  if (input !== void 0 && output !== void 0) {
209
- const [{ parseOpenAPI }, { takibi }] = yield* Effect.promise(() => Promise.all([import("./openapi-DQRxq2_O.js").then((n) => n.t), import("./core-CHLeBQ6y.js").then((n) => n.t)]));
209
+ const [{ parseOpenAPI }, { takibi }] = yield* Effect.promise(() => Promise.all([import("./openapi-DQRxq2_O.js").then((n) => n.t), import("./core-D-vKEwJs.js").then((n) => n.t)]));
210
210
  return yield* Console.log(yield* takibi(yield* parseOpenAPI(input), output));
211
211
  }
212
212
  const resolvedConfig = configPath ?? DEFAULT_CONFIG_FILE;
@@ -1,2 +1,2 @@
1
- import { t as docs } from "../../docs-y1jSJoJg.js";
1
+ import { t as docs } from "../../docs-NIDBdFyt.js";
2
2
  export { docs };
@@ -1,6 +1,6 @@
1
1
  import { t as OpenAPI } from "../../index-tsPqeV6H.js";
2
2
  import { n as GenerateError, t as FormatError } from "../../index-D_gf3Xzx.js";
3
- import { t as Grouping } from "../../index-Dn5Bw8ov.js";
3
+ import { t as Grouping } from "../../index-CMoB1dLg.js";
4
4
  //#region src/core/hooks/index.d.ts
5
5
  declare const HOOK_CONFIGS: {
6
6
  readonly swr: {
@@ -1,2 +1,2 @@
1
- import { t as hooks } from "../../hooks-xBFksKgW.js";
1
+ import { t as hooks } from "../../hooks-GhEZu5l6.js";
2
2
  export { hooks };
@@ -1,6 +1,6 @@
1
1
  import { t as OpenAPI } from "../../index-tsPqeV6H.js";
2
2
  import { n as GenerateError, t as FormatError } from "../../index-D_gf3Xzx.js";
3
- import { t as Grouping } from "../../index-Dn5Bw8ov.js";
3
+ import { t as Grouping } from "../../index-CMoB1dLg.js";
4
4
  import { Effect } from "effect";
5
5
  //#region src/core/rpc/index.d.ts
6
6
  /**
@@ -1,8 +1,8 @@
1
1
  import { s as HTTP_METHODS } from "../../constants-Bz8YiPum.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-BCaOY0bs.js";
3
+ import { L as isOpenAPIPaths, f as methodPath, l as makeInferRequestType, q as isRecord, z as isOperationLike } from "../../utils-vw99OasL.js";
4
4
  import { t as emit } from "../../emit-uwlZZeRM.js";
5
- import { a as groupClientName, i as parsePathItem, n as makeOperationDeps, r as operationHasArgs, s as operationTags, t as formatPath } from "../../rpc-b2oph6wk.js";
5
+ import { i as parsePathItem, l as operationTags, n as makeOperationDeps, r as operationHasArgs, s as groupClientName, t as formatPath } from "../../rpc-D_ka_cCX.js";
6
6
  import { Effect } from "effect";
7
7
  import { dirname } from "node:path";
8
8
  //#region src/core/rpc/index.ts
@@ -1,5 +1,5 @@
1
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, g as statusCodeToNumber, it as isStringRef, j as isHttpMethod, u as makeSafeKey } from "../../utils-BCaOY0bs.js";
2
+ import { B as isParameter, F as isMediaWithSchema, L as isOpenAPIPaths, Q as isSchemaArray, R as isOperation, V as isParameterArray, X as isRequestBody, g as statusCodeToNumber, it as isStringRef, j as isHttpMethod, u as makeSafeKey } from "../../utils-vw99OasL.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
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";
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, U as isParameterRef, 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, tt as isSecurityArray, u as makeSafeKey, v as uncapitalize, w as hasNumericConstraint, y as uncapitalizeWord } from "./utils-BCaOY0bs.js";
5
- import { C as warnUnroutablePath, S as makeRequest, _ as makeCallback, a as responsesCode, b as makePathItem, c as headersCode, d as makeExportConst, f as makeImports, g as zodToOpenAPI, h as ast, i as schemasCode, 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 makeCallbacks, x as makeRef, y as makeOperationResponses } from "./openapi-BlxQC7Xn.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, U as isParameterRef, 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 { C as warnUnroutablePath, S as makeRequest, _ as makeCallback, a as responsesCode, b as makePathItem, c as headersCode, d as makeExportConst, f as makeImports, g as zodToOpenAPI, h as ast, i as schemasCode, 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 makeCallbacks, x as makeRef, y as makeOperationResponses } from "./openapi-C2BSoZRM.js";
6
6
  import { i as readdir, n as mkdir, o as writeFile, r as readFile } from "./file-K6j5IJXi.js";
7
7
  import { t as emit } from "./emit-uwlZZeRM.js";
8
- import { a as groupClientName, o as isGroupName } from "./rpc-b2oph6wk.js";
9
- import { t as hooks } from "./hooks-xBFksKgW.js";
10
- import { t as docs } from "./docs-y1jSJoJg.js";
8
+ import { a as entryNames, c as groupNameOf, l as operationTags, o as freeName, s as groupClientName } from "./rpc-D_ka_cCX.js";
9
+ import { t as hooks } from "./hooks-GhEZu5l6.js";
10
+ import { t as docs } from "./docs-NIDBdFyt.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";
@@ -898,33 +898,30 @@ function mergeDefineFile(existingCode, generatedCode) {
898
898
  newRouteStatements.join("\n\n")
899
899
  ]);
900
900
  }
901
+ const DEFAULT_ENTRY = { app: "app" };
901
902
  /**
902
903
  * Merges generated app file (index.ts) with existing user-modified version.
903
904
  *
904
905
  * Merge rules:
905
- * - `export const api = app.openapi(...)` chain: replaced with generated version (reflects current routes)
906
- * - `export const books = app.openapi(...)` groups of a split app: replaced with the
907
- * generated version, added before `api` when new, removed when no longer generated
906
+ * - What the generator owns, `export const api = app.openapi(...)` of an app that is not
907
+ * split and `export const books = app.openapi(...)` of each group of one that is: replaced
908
+ * with the generated version where it stands, placed after the statement the generator
909
+ * wrote before it when new, removed when no longer generated. A chain the user put between
910
+ * `app` and the routes, `.basePath('/api')`, is kept.
908
911
  * - Imports: sync with generated (remove deleted route/handler imports, add new ones, keep user imports)
909
912
  * - Everything else (middleware, comments, helpers): keep existing
910
913
  *
911
914
  * Uses AST for analysis only. The existing file's original text is preserved by slicing.
912
915
  */
913
- function mergeAppFile(existingCode, generatedCode) {
916
+ function mergeAppFile(existingCode, generatedCode, names = DEFAULT_ENTRY) {
914
917
  const { existingFile, generatedFile } = makeSourcePair(existingCode, generatedCode);
915
- const existingApiStmt = findApiStatement(existingFile);
916
- const generatedApiStmt = findApiStatement(generatedFile);
917
- const generatedApiText = injectChainPrefix(generatedApiStmt?.getText() ?? "", extractChainPrefix(existingApiStmt?.getText() ?? ""));
918
- const generatedOwned = [...[...findGroupStatements(generatedFile)].map(([name, stmt]) => [
918
+ const generatedStatements = [...findOwnedStatements(generatedFile, names.app, /* @__PURE__ */ new Set())].toSorted(([, a], [, b]) => a.getStart() - b.getStart());
919
+ const existingOwned = findOwnedStatements(existingFile, names.app, new Set(generatedStatements.map(([name]) => name)));
920
+ const generatedOwned = generatedStatements.map(([name, stmt]) => [
919
921
  name,
920
922
  stmt.getStart(),
921
- stmt.getText()
922
- ]), ...generatedApiStmt ? [[
923
- "api",
924
- generatedApiStmt.getStart(),
925
- generatedApiText
926
- ]] : []].toSorted(([, a], [, b]) => a - b);
927
- const existingOwned = new Map([...findGroupStatements(existingFile), ...existingApiStmt ? [["api", existingApiStmt]] : []]);
923
+ injectChainPrefix(stmt.getText(), extractChainPrefix(existingOwned.get(name)?.getText() ?? "", names.app), names.app)
924
+ ]);
928
925
  const placed = placeOwned(generatedOwned, existingOwned);
929
926
  const bodyStart = getBodyStart(existingFile);
930
927
  const ops = [...existingOwned].flatMap(([name, stmt]) => {
@@ -934,19 +931,24 @@ function mergeAppFile(existingCode, generatedCode) {
934
931
  stmt.getEnd(),
935
932
  text
936
933
  ]];
937
- return name === "api" ? [] : [[
934
+ return [[
938
935
  stmt.getFullStart(),
939
936
  stmt.getEnd(),
940
937
  ""
941
938
  ]];
942
939
  }).filter(([start]) => start >= bodyStart).toSorted(([a], [b]) => a - b);
943
- const [firstOwned] = generatedOwned;
940
+ const [firstStatement] = generatedStatements;
941
+ const generatedOwnedText = firstStatement === void 0 ? void 0 : generatedStatements.map(([, stmt], index) => {
942
+ const next = generatedStatements[index + 1]?.[1];
943
+ const between = generatedCode.slice(stmt.getEnd(), next?.getStart());
944
+ return `${generatedOwned[index]?.[2] ?? ""}${between}`;
945
+ }).join("");
944
946
  const body = makeAppBody({
945
947
  existingCode,
946
948
  bodyStart,
947
- hasApi: existingApiStmt !== void 0,
949
+ hasOwned: existingOwned.size > 0,
948
950
  ops,
949
- generatedOwnedText: firstOwned === void 0 || generatedApiStmt === void 0 ? void 0 : `${generatedCode.slice(firstOwned[1], generatedApiStmt.getStart())}${generatedApiText}${generatedCode.slice(generatedApiStmt.getEnd())}`
951
+ generatedOwnedText
950
952
  }).trim() || generatedCode.slice(getBodyStart(generatedFile)).trim();
951
953
  return joinSections([mergeImports(existingFile, generatedFile).join("\n"), body]);
952
954
  }
@@ -954,7 +956,8 @@ function mergeAppFile(existingCode, generatedCode) {
954
956
  * The text each statement of the file is replaced by, by name. A statement the file already
955
957
  * has is replaced where it stands. A new one is placed after the statement the generator
956
958
  * wrote before it, so that the order of the document is kept; the ones written before any
957
- * the file has go in front of the first.
959
+ * the file has go in front of the first. When the file has none of them, they stand where
960
+ * its first owned statement did, which is replaced, not removed.
958
961
  */
959
962
  function placeOwned(generatedOwned, existingOwned) {
960
963
  const placed = /* @__PURE__ */ new Map();
@@ -968,36 +971,47 @@ function placeOwned(generatedOwned, existingOwned) {
968
971
  } else if (anchor === void 0) head.push(text);
969
972
  else placed.set(anchor, `${placed.get(anchor) ?? ""}\n\n${text}`);
970
973
  }
974
+ const [first] = existingOwned.keys();
975
+ if (head.length > 0 && first !== void 0) placed.set(first, head.join("\n\n"));
971
976
  return placed;
972
977
  }
973
- const GROUP_INITIALIZER = /^app\s*\.(?:openapi\(|openapiRoutes\(|route\(\s*'\/'\s*,\s*[\w$]+Handler\s*\))/u;
978
+ function ownedShape(app) {
979
+ const routes = String.raw`\.(?:openapi\(|openapiRoutes\(|route\(\s*'\/'\s*,\s*[\w$]+Handler\s*\))`;
980
+ const name = escapeRegexLiteral(app);
981
+ return {
982
+ written: new RegExp(String.raw`^${name}\s*(?:$|${routes})`, "u"),
983
+ chained: new RegExp(String.raw`^${name}\b(?:\s*$|[\s\S]*?${routes})`, "u")
984
+ };
985
+ }
974
986
  /**
975
- * The groups of a split app, by name: `export const books = app.openapi(...)`. What tells
976
- * one from an export the user wrote is what it is made of.
987
+ * The statements of the file the generator owns, by name: `export const api = app.openapi(...)`
988
+ * of an app that is not split, `export const books = app.openapi(...)` of a group. What
989
+ * tells one from an export the user wrote is what it is made of, as the generator writes
990
+ * it; one of a name the generator writes this time is the generator's also with a chain the
991
+ * user put into it.
977
992
  */
978
- function findGroupStatements(file) {
993
+ function findOwnedStatements(file, app, written) {
994
+ const shape = ownedShape(app);
979
995
  return new Map(file.getVariableStatements().filter((stmt) => stmt.isExported() && stmt.getDeclarations().length === 1).flatMap((stmt) => {
980
996
  const [decl] = stmt.getDeclarations();
981
- const made = decl?.getInitializer()?.getText() ?? "";
982
- return decl !== void 0 && decl.getName() !== "api" && GROUP_INITIALIZER.test(made) ? [[decl.getName(), stmt]] : [];
997
+ if (decl === void 0) return [];
998
+ const made = decl.getInitializer()?.getText() ?? "";
999
+ return (written.has(decl.getName()) ? shape.chained : shape.written).test(made) ? [[decl.getName(), stmt]] : [];
983
1000
  }));
984
1001
  }
985
- function findApiStatement(file) {
986
- return file.getVariableStatements().find((stmt) => stmt.isExported() && stmt.getDeclarations().some((decl) => decl.getName() === "api"));
987
- }
988
- function injectChainPrefix(generatedApiText, chainPrefix) {
989
- if (!chainPrefix) return generatedApiText;
990
- return generatedApiText.replace(/\bapp(\s*)\.(?=\s*(?:openapiRoutes|openapi|route)\s*\()/u, (_, ws) => `app${chainPrefix}${ws}.`);
1002
+ function injectChainPrefix(generatedText, chainPrefix, app) {
1003
+ if (!chainPrefix) return generatedText;
1004
+ return generatedText.replace(new RegExp(String.raw`\b${escapeRegexLiteral(app)}(\s*)\.(?=\s*(?:openapiRoutes|openapi|route)\s*\()`, "u"), (_, ws) => `${app}${chainPrefix}${ws}.`);
991
1005
  }
992
1006
  /**
993
- * Builds the merged app body by either replacing the existing api statement in place,
994
- * or — when existing has no api but is incomplete (lacks `export default`) — appending
995
- * the generated api block plus any trailing exports. When existing keeps `export default`
996
- * but no api, treats the omission as intentional and leaves the body untouched.
1007
+ * Builds the merged app body by replacing the owned statements where they stand, or — when
1008
+ * the file has none of them but is incomplete (lacks `export default`) — appending the
1009
+ * generated ones plus what follows them. When the file keeps `export default` but none of
1010
+ * them, treats the omission as intentional and leaves the body untouched.
997
1011
  */
998
1012
  function makeAppBody(args) {
999
1013
  const { existingCode, bodyStart } = args;
1000
- if (args.hasApi) return applyRangeOps(existingCode, bodyStart, args.ops);
1014
+ if (args.hasOwned) return applyRangeOps(existingCode, bodyStart, args.ops);
1001
1015
  const slice = existingCode.slice(bodyStart);
1002
1016
  if (slice.trim().length === 0 || args.generatedOwnedText === void 0) return slice;
1003
1017
  if (/\bexport\s+default\b/u.test(slice)) return slice;
@@ -1139,8 +1153,8 @@ function formatImportLine(moduleSpecifier, info) {
1139
1153
  * this returns `.basePath('/api')`.
1140
1154
  * Returns empty string if there is no prefix chain.
1141
1155
  */
1142
- function extractChainPrefix(apiStmtText) {
1143
- const initMatch = apiStmtText.match(/[=]\s*app\b/u);
1156
+ function extractChainPrefix(apiStmtText, app) {
1157
+ const initMatch = apiStmtText.match(new RegExp(String.raw`[=]\s*${escapeRegexLiteral(app)}\b`, "u"));
1144
1158
  if (initMatch?.index === void 0) return "";
1145
1159
  const afterApp = apiStmtText.slice(initMatch.index + initMatch[0].length);
1146
1160
  const routeMatch = afterApp.match(/\.(?:openapiRoutes|openapi|route)\s*\(/u);
@@ -1301,13 +1315,12 @@ function makeHandlerFileName(path, tags) {
1301
1315
  }
1302
1316
  /**
1303
1317
  * The group an operation belongs to: the name of the handler file it is written to, the
1304
- * first tag or else the first segment of the path, `/v2-public/ping` as `v2Public`. An
1305
- * operation belongs to no group, and `undefined` is returned, when the name cannot be an
1306
- * export: the root, a word the language or the generated app has taken.
1318
+ * first tag or else the first segment of the path, `/v2-public/ping` as `v2Public`, and the
1319
+ * root `/` as `__root`. A segment that is a word of the language is prefixed the same way,
1320
+ * `/delete` as `__delete`.
1307
1321
  */
1308
1322
  function handlerGroupOf(path, tags) {
1309
- const name = makeHandlerFileName(path, tags).replace(/\.ts$/u, "");
1310
- return isGroupName(name) ? name : void 0;
1323
+ return groupNameOf(makeHandlerFileName(path, tags).replace(/\.ts$/u, ""));
1311
1324
  }
1312
1325
  function isTsFileName(file) {
1313
1326
  return file.endsWith(".ts");
@@ -1527,7 +1540,7 @@ function defineOpenAPIRouteHandler(openapi, output, componentsOutput, pathAlias,
1527
1540
  //#endregion
1528
1541
  //#region src/core/client/index.ts
1529
1542
  function capitalizeFirst(name) {
1530
- return `${name.charAt(0).toUpperCase()}${name.slice(1)}`;
1543
+ return name.replace(/^([_$]*)(.)/u, (_, lead, first) => `${lead}${first.toUpperCase()}`);
1531
1544
  }
1532
1545
  function makeBasePathAccess(basePath) {
1533
1546
  return basePath.split("/").filter((segment) => segment !== "").map((segment) => isValidIdent(segment) ? `.${segment}` : `['${segment.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}']`).join("");
@@ -1554,32 +1567,55 @@ function makeBaseUrl(baseUrl) {
1554
1567
  * declared once, so that it is worked out when this file is compiled and not again by every
1555
1568
  * file that calls `hc`.
1556
1569
  */
1557
- function makeClient(name, app, url, access = "") {
1570
+ function makeClient(name, app, url, access = "", imported = app, whole = false) {
1558
1571
  const typeName = capitalizeFirst(name);
1559
- const factory = app === "api" ? "hcWithType" : `hc${capitalizeFirst(app)}WithType`;
1572
+ const factory = whole ? "hcWithType" : `hc${capitalizeFirst(app)}WithType`;
1560
1573
  return [
1561
- `type ${typeName}=ReturnType<typeof hc<typeof ${app}>>`,
1562
- `const ${factory}=(...args:Parameters<typeof hc>):${typeName}=>hc<typeof ${app}>(...args)`,
1574
+ `type ${typeName}=ReturnType<typeof hc<typeof ${imported}>>`,
1575
+ `const ${factory}=(...args:Parameters<typeof hc>):${typeName}=>hc<typeof ${imported}>(...args)`,
1563
1576
  `export const ${name}=${factory}(${url})${access}`
1564
1577
  ].join("\n\n");
1565
1578
  }
1579
+ function ownNames(apps, environment, whole) {
1580
+ return [
1581
+ "hc",
1582
+ ...environment,
1583
+ ...apps.flatMap((app) => whole ? [
1584
+ "client",
1585
+ "Client",
1586
+ "hcWithType"
1587
+ ] : [
1588
+ groupClientName(app),
1589
+ capitalizeFirst(groupClientName(app)),
1590
+ `hc${capitalizeFirst(app)}WithType`
1591
+ ])
1592
+ ];
1593
+ }
1594
+ function importedName(app, apps, own) {
1595
+ return own.includes(app) ? freeName(`${app}App`, [...own, ...apps]) : app;
1596
+ }
1566
1597
  /**
1567
- * Generates the file of typed clients: `client` for the application, and one client for
1568
- * each group of a split application, `booksClient` for `books`.
1598
+ * Generates the file of typed clients: `client` for the application, or one client for
1599
+ * each group of a split application, `booksClient` for `books` and `__rootClient` for `__root`.
1569
1600
  */
1570
1601
  function client(openAPI, output, importPath, baseUrl, basePath, grouping, barrel) {
1571
1602
  return Effect.gen(function* () {
1572
1603
  const paths = openAPI.paths;
1573
1604
  if (!isOpenAPIPaths(paths)) return yield* new GenerateError({ message: "Invalid OpenAPI paths" });
1574
- const apps = grouping === void 0 ? ["api"] : [...new Set(Object.entries(paths).flatMap(([route, pathItem]) => Object.entries(pathItem).flatMap(([method, operation]) => isHttpMethod(method) && isOperation(operation) ? [grouping(route, operation.tags) ?? "api"] : [])))];
1605
+ const whole = grouping === void 0;
1606
+ const apps = whole ? ["api"] : [...new Set(Object.entries(paths).flatMap(([route, pathItem]) => Object.entries(pathItem).flatMap(([method, operation]) => isHttpMethod(method) && isOperation(operation) ? [grouping(route, operationTags(operation))] : [])))];
1575
1607
  const { imports: environment, declaration, url } = makeBaseUrl(baseUrl);
1608
+ const own = ownNames(apps, typeof baseUrl === "string" ? [] : "import" in baseUrl ? [baseUrl.name] : ["baseUrl"], whole);
1576
1609
  const imports = [
1577
1610
  "import{hc}from'hono/client'",
1578
- `import type{${apps.join(",")}}from'${importPath}'`,
1611
+ `import type{${apps.map((name) => {
1612
+ const imported = importedName(name, apps, own);
1613
+ return imported === name ? name : `${name} as ${imported}`;
1614
+ }).join(",")}}from'${importPath}'`,
1579
1615
  ...environment
1580
1616
  ].join("\n");
1581
1617
  const access = makeBasePathAccess(basePath);
1582
- const code = `${imports}\n\n${[...declaration, ...apps.map((name) => makeClient(name === "api" ? "client" : groupClientName(name), name, url, access))].join("\n\n")}\n`;
1618
+ const code = `${imports}\n\n${[...declaration, ...apps.map((name) => makeClient(whole ? "client" : groupClientName(name), name, url, access, importedName(name, apps, own), whole))].join("\n\n")}\n`;
1583
1619
  yield* emit(code, path.dirname(output), output);
1584
1620
  if (barrel !== void 0) {
1585
1621
  const line = `export * from './${path.basename(output, ".ts")}'`;
@@ -1702,6 +1738,7 @@ function mediaTypes(mediaTypes, output, split, readonly, components) {
1702
1738
  const keys = Object.keys(mediaTypes);
1703
1739
  if (keys.length === 0) return "No mediaTypes found";
1704
1740
  const importCode = renderNamedImport(["z"], "@hono/zod-openapi");
1741
+ const options = readonly === true ? { readonly: true } : void 0;
1705
1742
  if (split) {
1706
1743
  const outDir = path.join(path.dirname(output), path.basename(output, ".ts"));
1707
1744
  yield* Effect.all([...keys.map((k) => {
@@ -1714,8 +1751,8 @@ function mediaTypes(mediaTypes, output, split, readonly, components) {
1714
1751
  return emit(makeImports(body, filePath, components, split), path.dirname(filePath), filePath);
1715
1752
  }
1716
1753
  if (typeof v === "object" && v !== null && "schema" in v) {
1717
- const zodCode = zodToOpenAPI(v.schema);
1718
- const schemaCode = zodToOpenAPISchema(name, zodCode, true, false, true, readonly);
1754
+ const zodCode = zodToOpenAPI(v.schema, void 0, options);
1755
+ const schemaCode = zodToOpenAPISchema(name, zodCode, true, false, true);
1719
1756
  return emit(makeImports(schemaCode, filePath, components, split), path.dirname(filePath), filePath);
1720
1757
  }
1721
1758
  const body = `export const ${name} = z.unknown()\n`;
@@ -1731,8 +1768,8 @@ function mediaTypes(mediaTypes, output, split, readonly, components) {
1731
1768
  return `export const ${name} = ${toIdentifierPascalCase(ensureSuffix(refKey, "MediaTypeSchema"))}`;
1732
1769
  }
1733
1770
  if (typeof v === "object" && v !== null && "schema" in v) {
1734
- const zodCode = zodToOpenAPI(v.schema);
1735
- return zodToOpenAPISchema(name, zodCode, true, false, true, readonly);
1771
+ const zodCode = zodToOpenAPI(v.schema, void 0, options);
1772
+ return zodToOpenAPISchema(name, zodCode, true, false, true);
1736
1773
  }
1737
1774
  return `export const ${name} = z.unknown()`;
1738
1775
  }).join("\n\n")}\n`;
@@ -2541,6 +2578,24 @@ function takibi(openAPI, output, componentsOptions = {}) {
2541
2578
  }
2542
2579
  //#endregion
2543
2580
  //#region src/generator/zod-openapi-hono/app/index.ts
2581
+ /** The handler files the operations of a document are written to, in document order. */
2582
+ function handlerFilesOf(openapi) {
2583
+ return [...new Set(Object.entries(openapi.paths).flatMap(([path, pathItem]) => Object.entries(pathItem).flatMap(([method, operation]) => isHttpMethod(method) && isOperation(operation) ? [makeHandlerFileName(path, operation.tags)] : [])))];
2584
+ }
2585
+ /**
2586
+ * The groups of a split app, in the order their first route stands in the document: the
2587
+ * handler files where the handlers register their routes themselves, and the group of each
2588
+ * path otherwise, `__root` among them when the root has a route. Empty when the app is not
2589
+ * split.
2590
+ *
2591
+ * `app` and the merge of its file name the bindings of the entry from these, through
2592
+ * `entryNames`, so that no group is shadowed by one.
2593
+ */
2594
+ function appGroups(openapi, inline, inlineHandlerFileNames, split) {
2595
+ if (!split) return [];
2596
+ const names = inline ? (inlineHandlerFileNames ?? handlerFilesOf(openapi)).map((file) => groupNameOf(basename(file, ".ts"))) : Object.entries(openapi.paths).flatMap(([path, pathItem]) => Object.keys(pathItem).flatMap((method) => isHttpMethod(method) ? [handlerGroupOf(path)] : []));
2597
+ return [...new Set(names)];
2598
+ }
2544
2599
  /**
2545
2600
  * Generates a Hono app with OpenAPI integration.
2546
2601
  *
@@ -2566,50 +2621,50 @@ function app(openapi, output, basePath, pathAlias, routeImport, routeHandler = f
2566
2621
  const routeMappings = getRouteMaps();
2567
2622
  const routeBasename = output.endsWith("/index.ts") ? basename(output.replace(/\/index\.ts$/u, "")) : basename(output, ".ts");
2568
2623
  const aliasPrefix = pathAlias?.endsWith("/") ? pathAlias.slice(0, -1) : pathAlias;
2569
- const appInit = basePath !== "/" ? `const app=new OpenAPIHono().basePath('${basePath}')` : "const app=new OpenAPIHono()";
2624
+ const groups = appGroups(openapi, !define && !routeHandler, inlineHandlerFileNames, split);
2625
+ const { app: appVar, hono } = entryNames(groups);
2626
+ const honoImport = `import{${hono === "OpenAPIHono" ? hono : `OpenAPIHono as ${hono}`}}from'@hono/zod-openapi'`;
2627
+ const appInit = basePath !== "/" ? `const ${appVar}=new ${hono}().basePath('${basePath}')` : `const ${appVar}=new ${hono}()`;
2628
+ const appExport = `export default ${appVar}`;
2570
2629
  if (define) {
2571
2630
  const routeNames = [...new Set(routeMappings.map((m) => m.routeName))];
2572
2631
  const handlerModule = handlerModuleOverride ?? (aliasPrefix ? `${aliasPrefix}/handlers` : "./handlers");
2573
- const importSection = [`import{OpenAPIHono}from'@hono/zod-openapi'`, routeNames.length > 0 ? `import{${routeNames.join(",")}}from'${handlerModule}'` : ""].filter(Boolean).join("\n");
2574
- if (split) {
2575
- const groups = [...new Set(routeMappings.map(({ path }) => handlerGroupOf(path) ?? "api"))];
2576
- return [
2577
- importSection,
2578
- appInit,
2579
- ...(groups.includes("api") ? groups : [...groups, "api"]).map((name) => {
2580
- const routes = [...new Set(routeMappings.filter(({ path }) => (handlerGroupOf(path) ?? "api") === name).map(({ routeName }) => routeName))];
2581
- return routes.length > 0 ? `export const ${name}=app.openapiRoutes([${routes.join(",")}] as const)` : `export const ${name}=app`;
2582
- }),
2583
- "export default app"
2584
- ].join("\n\n");
2585
- }
2632
+ const importSection = [honoImport, routeNames.length > 0 ? `import{${routeNames.join(",")}}from'${handlerModule}'` : ""].filter(Boolean).join("\n");
2633
+ if (split) return [
2634
+ importSection,
2635
+ appInit,
2636
+ ...groups.map((name) => {
2637
+ const routes = [...new Set(routeMappings.filter(({ path }) => handlerGroupOf(path) === name).map(({ routeName }) => routeName))];
2638
+ return `export const ${name}=${appVar}.openapiRoutes([${routes.join(",")}] as const)`;
2639
+ }),
2640
+ appExport
2641
+ ].join("\n\n");
2586
2642
  return [
2587
2643
  importSection,
2588
2644
  appInit,
2589
- routeNames.length > 0 ? `export const api=app.openapiRoutes([${routeNames.join(",")}] as const)` : "",
2590
- "export default app"
2645
+ routeNames.length > 0 ? `export const api=${appVar}.openapiRoutes([${routeNames.join(",")}] as const)` : "",
2646
+ appExport
2591
2647
  ].filter(Boolean).join("\n\n");
2592
2648
  }
2593
2649
  if (!routeHandler) {
2594
- const handlerFileNames = inlineHandlerFileNames ?? [...new Set(Object.entries(openapi.paths).flatMap(([path, pathItem]) => Object.entries(pathItem).flatMap(([method, operation]) => isHttpMethod(method) && isOperation(operation) ? [makeHandlerFileName(path, operation.tags)] : [])))];
2650
+ const handlerFileNames = inlineHandlerFileNames ?? handlerFilesOf(openapi);
2595
2651
  const handlerExportNames = handlerFileNames.map((fn) => `${basename(fn, ".ts")}Handler`);
2596
2652
  const handlerModule = handlerModuleOverride ?? (aliasPrefix ? `${aliasPrefix}/handlers` : "./handlers");
2597
- const importSection = [`import{OpenAPIHono}from'@hono/zod-openapi'`, handlerExportNames.length > 0 ? `import{${handlerExportNames.join(",")}}from'${handlerModule}'` : ""].filter(Boolean).join("\n");
2653
+ const importSection = [honoImport, handlerExportNames.length > 0 ? `import{${handlerExportNames.join(",")}}from'${handlerModule}'` : ""].filter(Boolean).join("\n");
2598
2654
  if (split) {
2599
2655
  const files = handlerFileNames.map((file) => basename(file, ".ts"));
2600
- const groups = [...new Set(files.map((file) => isGroupName(file) ? file : "api"))];
2601
2656
  return [
2602
2657
  importSection,
2603
2658
  appInit,
2604
- ...(groups.includes("api") ? groups : [...groups, "api"]).map((name) => `export const ${name}=app${files.filter((file) => (isGroupName(file) ? file : "api") === name).map((file) => `.route('/',${file}Handler)`).join("")}`),
2605
- "export default app"
2659
+ ...groups.map((name) => `export const ${name}=${appVar}${files.filter((file) => groupNameOf(file) === name).map((file) => `.route('/',${file}Handler)`).join("")}`),
2660
+ appExport
2606
2661
  ].join("\n\n");
2607
2662
  }
2608
2663
  return [
2609
2664
  importSection,
2610
2665
  appInit,
2611
- handlerExportNames.length > 0 ? `export const api=app${handlerExportNames.map((name) => `.route('/',${name})`).join("")}` : "",
2612
- "export default app"
2666
+ handlerExportNames.length > 0 ? `export const api=${appVar}${handlerExportNames.map((name) => `.route('/',${name})`).join("")}` : "",
2667
+ appExport
2613
2668
  ].filter(Boolean).join("\n\n");
2614
2669
  }
2615
2670
  const routeNames = [...new Set(routeMappings.map((m) => m.routeName))];
@@ -2618,22 +2673,21 @@ function app(openapi, output, basePath, pathAlias, routeImport, routeHandler = f
2618
2673
  const handlerNames = [...new Set(routeMappings.map((m) => m.handlerName))];
2619
2674
  const handlerModule = handlerModuleOverride ?? (aliasPrefix ? `${aliasPrefix}/handlers` : "./handlers");
2620
2675
  const importSection = [
2621
- `import{OpenAPIHono}from'@hono/zod-openapi'`,
2676
+ honoImport,
2622
2677
  routesImport,
2623
2678
  handlerNames.length > 0 ? `import{${handlerNames.join(",")}}from'${handlerModule}'` : ""
2624
2679
  ].filter(Boolean).join("\n");
2625
2680
  if (!split) return [
2626
2681
  importSection,
2627
2682
  appInit,
2628
- `export const api=app${routeMappings.map(({ routeName, handlerName }) => `.openapi(${routeName},${handlerName})`).join("\n")}`,
2629
- "export default app"
2683
+ `export const api=${appVar}${routeMappings.map(({ routeName, handlerName }) => `.openapi(${routeName},${handlerName})`).join("\n")}`,
2684
+ appExport
2630
2685
  ].join("\n\n");
2631
- const groups = [...new Set(routeMappings.map(({ path }) => handlerGroupOf(path) ?? "api"))];
2632
2686
  return [
2633
2687
  importSection,
2634
2688
  appInit,
2635
- ...(groups.includes("api") ? groups : [...groups, "api"]).map((name) => `export const ${name}=app${routeMappings.filter(({ path }) => (handlerGroupOf(path) ?? "api") === name).map(({ routeName, handlerName }) => `.openapi(${routeName},${handlerName})`).join("\n")}`),
2636
- "export default app"
2689
+ ...groups.map((name) => `export const ${name}=${appVar}${routeMappings.filter(({ path }) => handlerGroupOf(path) === name).map(({ routeName, handlerName }) => `.openapi(${routeName},${handlerName})`).join("\n")}`),
2690
+ appExport
2637
2691
  ].join("\n\n");
2638
2692
  }
2639
2693
  //#endregion
@@ -2647,7 +2701,7 @@ function defineTemplate(openAPI, output, componentsOutput, basePath, pathAlias,
2647
2701
  return Effect.gen(function* () {
2648
2702
  const [appCode] = yield* Effect.all([fmt(app(openAPI, output, basePath, pathAlias, routeImport, false, true, handlerImport, void 0, split)), defineOpenAPIRouteHandler(openAPI, target, componentsOutput, pathAlias, readonly, componentsPackage)], { concurrency: "unbounded" });
2649
2703
  const existing = yield* readFile(target);
2650
- const merged = existing !== null ? mergeAppFile(existing, appCode) : appCode;
2704
+ const merged = existing !== null ? mergeAppFile(existing, appCode, entryNames(appGroups(openAPI, false, void 0, split))) : appCode;
2651
2705
  const appContent = yield* fmt(merged).pipe(Effect.orElseSucceed(() => merged));
2652
2706
  yield* writeFile(target, appContent);
2653
2707
  return "🔥 Generated code and template files written";
@@ -2662,7 +2716,7 @@ function template(openAPI, output, basePath, pathAlias, routeImport, routeHandle
2662
2716
  const inlineFiles = routeHandler ? void 0 : yield* resolveInlineHandlerFileNames(openAPI, output, pathAlias, routeImport);
2663
2717
  const appCode = yield* fmt(app(openAPI, output, basePath, pathAlias, routeImport, routeHandler, false, void 0, inlineFiles, split));
2664
2718
  const existing = yield* readFile(target);
2665
- const merged = existing !== null ? mergeAppFile(existing, appCode) : appCode;
2719
+ const merged = existing !== null ? mergeAppFile(existing, appCode, entryNames(appGroups(openAPI, !routeHandler, inlineFiles, split))) : appCode;
2666
2720
  const appContent = yield* fmt(merged).pipe(Effect.orElseSucceed(() => merged));
2667
2721
  yield* writeFile(target, appContent);
2668
2722
  return "🔥 Generated code and template files written";
@@ -1,5 +1,5 @@
1
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-BCaOY0bs.js";
2
+ import { J as isRefObject, Q as isSchemaArray, o as escapeHtml, q as isRecord } from "./utils-vw99OasL.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";
@@ -1,2 +1,2 @@
1
- import { t as zodOpenAPIHono } from "../../../openapi-BlxQC7Xn.js";
1
+ import { t as zodOpenAPIHono } from "../../../openapi-C2BSoZRM.js";
2
2
  export { zodOpenAPIHono };
@@ -1,8 +1,8 @@
1
1
  import { s as HTTP_METHODS } from "./constants-Bz8YiPum.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-BCaOY0bs.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
4
  import { t as emit } from "./emit-uwlZZeRM.js";
5
- import { a as groupClientName, i as parsePathItem, n as makeOperationDeps, r as operationHasArgs, s as operationTags, t as formatPath } from "./rpc-b2oph6wk.js";
5
+ import { i as parsePathItem, l as operationTags, n as makeOperationDeps, r as operationHasArgs, s as groupClientName, t as formatPath } from "./rpc-D_ka_cCX.js";
6
6
  import { Effect } from "effect";
7
7
  import path from "node:path";
8
8
  //#region src/helper/query.ts
@@ -0,0 +1,12 @@
1
+ import "./index-B7AwLlPY.js";
2
+ import "./index-tsPqeV6H.js";
3
+ import { Effect } from "effect";
4
+ //#region src/helper/group.d.ts
5
+ /**
6
+ * The group an operation belongs to. Every operation belongs to one: the resource its path
7
+ * or tag names, or `root`. What divides an application depends on how the template writes
8
+ * it.
9
+ */
10
+ type Grouping = (path: string, tags: readonly string[] | undefined) => string;
11
+ //#endregion
12
+ export { Grouping as t };
@@ -1,5 +1,5 @@
1
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-BCaOY0bs.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";
3
3
  import path from "node:path";
4
4
  import { ts } from "ts-morph";
5
5
  //#region src/helper/wire.ts
@@ -2676,16 +2676,16 @@ function headersCode(components, exportHeaders, exportHeadersTypes, readonly) {
2676
2676
  const schemaName = toIdentifierPascalCase(ensureSuffix(k, "HeaderSchema"));
2677
2677
  if ("$ref" in header) {
2678
2678
  const refName = makeRef(header.$ref);
2679
- return zodToOpenAPISchema(schemaName, refName, exportHeaders, exportHeadersTypes, true, readonly);
2679
+ return zodToOpenAPISchema(schemaName, refName, exportHeaders, exportHeadersTypes, true);
2680
2680
  }
2681
2681
  if (isHeader(header)) {
2682
2682
  if (header.schema) {
2683
- const schema = zodToOpenAPI(header.schema, { headers: header });
2684
- return zodToOpenAPISchema(schemaName, schema, exportHeaders, exportHeadersTypes, true, readonly);
2683
+ const schema = zodToOpenAPI(header.schema, { headers: header }, readonly === true ? { readonly: true } : void 0);
2684
+ return zodToOpenAPISchema(schemaName, schema, exportHeaders, exportHeadersTypes, true);
2685
2685
  }
2686
2686
  if (header.content) {
2687
- const content = makeContent(header.content);
2688
- return zodToOpenAPISchema(schemaName, `{${content.join(",")}}`, exportHeaders, exportHeadersTypes, true, readonly);
2687
+ const content = makeContent(header.content, readonly);
2688
+ return zodToOpenAPISchema(schemaName, `{${content.join(",")}}`, exportHeaders, exportHeadersTypes, true);
2689
2689
  }
2690
2690
  }
2691
2691
  return "";
@@ -2782,21 +2782,26 @@ function mediaTypesCode(components, exportMediaTypes, exportMediaTypesTypes, rea
2782
2782
  if (!mediaTypes) return "";
2783
2783
  const entries = Object.entries(mediaTypes);
2784
2784
  if (entries.length === 0) return "";
2785
+ const options = readonly === true ? { readonly: true } : void 0;
2785
2786
  return entries.map(([k, v]) => {
2786
2787
  const name = toIdentifierPascalCase(ensureSuffix(k, "MediaTypeSchema"));
2787
- const zodCode = isRefObject(v) ? makeRef(v.$ref) : isMedia(v) ? zodToOpenAPI(v.schema) : "z.unknown()";
2788
- return zodToOpenAPISchema(name, zodCode, exportMediaTypes, exportMediaTypesTypes, true, readonly);
2788
+ const zodCode = isRefObject(v) ? makeRef(v.$ref) : isMedia(v) ? zodToOpenAPI(v.schema, void 0, options) : "z.unknown()";
2789
+ return zodToOpenAPISchema(name, zodCode, exportMediaTypes, exportMediaTypesTypes, true);
2789
2790
  }).join("\n\n");
2790
2791
  }
2791
2792
  //#endregion
2792
2793
  //#region src/generator/zod-openapi-hono/openapi/components/parameters.ts
2793
2794
  /**
2794
2795
  * Generates TypeScript code for OpenAPI component parameters.
2796
+ *
2797
+ * `readonly` reaches the schema of the parameter, where it is put on the objects and arrays
2798
+ * alone, as a parameter written into a route gets it: a scalar is not wrapped, so a branded
2799
+ * one keeps its brand on its primitive.
2795
2800
  */
2796
2801
  function parametersCode(components, exportParameters, exportParametersTypes, readonly) {
2797
2802
  const { parameters } = components;
2798
2803
  if (!parameters) return "";
2799
- return Object.keys(parameters).map((k) => zodToOpenAPISchema(toIdentifierPascalCase(ensureSuffix(k, "ParamsSchema")), makeParameterSchema(parameters[k], void 0, components.schemas), exportParameters, exportParametersTypes, true, readonly)).join("\n\n");
2804
+ return Object.keys(parameters).map((k) => zodToOpenAPISchema(toIdentifierPascalCase(ensureSuffix(k, "ParamsSchema")), makeParameterSchema(parameters[k], readonly, components.schemas), exportParameters, exportParametersTypes, true)).join("\n\n");
2800
2805
  }
2801
2806
  //#endregion
2802
2807
  //#region src/generator/zod-openapi-hono/openapi/components/pathItems.ts
@@ -1,10 +1,9 @@
1
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-BCaOY0bs.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";
3
3
  //#region src/helper/group.ts
4
4
  const RESERVED = /* @__PURE__ */ new Set([
5
- "api",
6
- "app",
7
- "client",
5
+ "arguments",
6
+ "await",
8
7
  "break",
9
8
  "case",
10
9
  "catch",
@@ -17,6 +16,7 @@ const RESERVED = /* @__PURE__ */ new Set([
17
16
  "do",
18
17
  "else",
19
18
  "enum",
19
+ "eval",
20
20
  "export",
21
21
  "extends",
22
22
  "false",
@@ -24,12 +24,20 @@ const RESERVED = /* @__PURE__ */ new Set([
24
24
  "for",
25
25
  "function",
26
26
  "if",
27
+ "implements",
27
28
  "import",
28
29
  "in",
29
30
  "instanceof",
31
+ "interface",
32
+ "let",
30
33
  "new",
31
34
  "null",
35
+ "package",
36
+ "private",
37
+ "protected",
38
+ "public",
32
39
  "return",
40
+ "static",
33
41
  "super",
34
42
  "switch",
35
43
  "this",
@@ -41,23 +49,61 @@ const RESERVED = /* @__PURE__ */ new Set([
41
49
  "void",
42
50
  "while",
43
51
  "with",
44
- "let",
45
- "static",
46
- "yield",
47
- "await"
52
+ "yield"
48
53
  ]);
54
+ function isGroupName(name) {
55
+ return name !== void 0 && isValidIdent(name) && !RESERVED.has(name) && !name.endsWith("Route") && !name.endsWith("Handler");
56
+ }
49
57
  /**
50
- * Whether a name can be the export of a group: an identifier that is no word the language
51
- * or the generated app has taken.
58
+ * The group of a handler file: its name. A name that cannot be an export, a word of the
59
+ * language like `delete`, is prefixed with `__`, as the file of the root `/` is named
60
+ * `__root` already: a resource is named with letters and digits alone, so a name that
61
+ * starts with `__` is never one, and never in its way.
52
62
  */
53
- function isGroupName(name) {
54
- return name !== void 0 && isValidIdent(name) && !RESERVED.has(name) && !name.startsWith("__") && !name.endsWith("Route") && !name.endsWith("Handler");
63
+ function groupNameOf(file) {
64
+ return isGroupName(file) ? file : `__${file}`;
55
65
  }
56
66
  /** The string tags of an operation, as a {@link Grouping} reads them. */
57
67
  function operationTags(operation) {
58
68
  const tags = "tags" in operation ? operation.tags : void 0;
59
69
  return Array.isArray(tags) ? tags.filter((tag) => typeof tag === "string") : void 0;
60
70
  }
71
+ /**
72
+ * A name free of the ones taken: `base` itself, or `base` followed by the first number from
73
+ * 2 on that no one has. What the generated files bind for themselves (`app`, `hc`) is named
74
+ * this way, so that a group of the same name keeps it.
75
+ *
76
+ * @example
77
+ * ```ts
78
+ * freeName('app', ['books']) // 'app'
79
+ * freeName('app', ['app']) // 'app2'
80
+ * freeName('app', ['app', 'app2']) // 'app3'
81
+ * ```
82
+ */
83
+ function freeName(base, taken) {
84
+ const names = new Set(taken);
85
+ if (!names.has(base)) return base;
86
+ const free = (n) => names.has(`${base}${n}`) ? free(n + 1) : `${base}${n}`;
87
+ return free(2);
88
+ }
89
+ /**
90
+ * The names the app entry binds for itself: `app`, the app the routes are registered on,
91
+ * and `OpenAPIHono`, the import. Neither is an export. Each yields to a group of its name,
92
+ * so that `/app` and `/OpenAPIHono` can be groups: `app2`, `OpenAPIHono2`.
93
+ *
94
+ * @example
95
+ * ```ts
96
+ * entryNames(['books']) // { app: 'app', hono: 'OpenAPIHono' }
97
+ * entryNames(['app', 'OpenAPIHono']) // { app: 'app2', hono: 'OpenAPIHono2' }
98
+ * ```
99
+ */
100
+ function entryNames(groups) {
101
+ const taken = [...groups];
102
+ return {
103
+ app: freeName("app", taken),
104
+ hono: freeName("OpenAPIHono", taken)
105
+ };
106
+ }
61
107
  /** The export a group's client is reached by: `books` through `booksClient`. */
62
108
  function groupClientName(group) {
63
109
  return `${group}Client`;
@@ -173,4 +219,4 @@ function operationHasArgs(item, operation, deps) {
173
219
  return hasParams || hasBody;
174
220
  }
175
221
  //#endregion
176
- export { groupClientName as a, parsePathItem as i, makeOperationDeps as n, isGroupName as o, operationHasArgs as r, operationTags as s, formatPath as t };
222
+ export { entryNames as a, groupNameOf as c, parsePathItem as i, operationTags as l, makeOperationDeps as n, freeName as o, operationHasArgs as r, groupClientName as s, formatPath as t };
@@ -2,9 +2,9 @@ import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
2
2
  import { n as COMPONENT_NAMES, o as HOOK_LIBRARIES } from "./constants-Bz8YiPum.js";
3
3
  import { i as GenerateError } from "./format-CuHABcKC.js";
4
4
  import { a as unlink, i as readdir, t as exists } from "./file-K6j5IJXi.js";
5
- import { C as appEntryImport, E as isInsideDirectory, S as appEntryFile, T as generatedImport, _ 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 appEntryOutput, x as handlerGroupOf, y as callbacks } from "./core-CHLeBQ6y.js";
6
- import { t as hooks } from "./hooks-xBFksKgW.js";
7
- import { t as docs } from "./docs-y1jSJoJg.js";
5
+ import { C as appEntryImport, E as isInsideDirectory, S as appEntryFile, T as generatedImport, _ 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 appEntryOutput, x as handlerGroupOf, y as callbacks } from "./core-D-vKEwJs.js";
6
+ import { t as hooks } from "./hooks-GhEZu5l6.js";
7
+ import { t as docs } from "./docs-NIDBdFyt.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";
@@ -431,15 +431,14 @@ function ensureSuffix(text, suffix) {
431
431
  * zodToOpenAPISchema('User', 'z.object({name: z.string()})', true, true)
432
432
  * // → 'export const UserSchema = z.object({name: z.string()}).openapi("User")\n\nexport type User = z.infer<typeof UserSchema>'
433
433
  *
434
- * @example
435
- * zodToOpenAPISchema('User', 'z.object({name: z.string()})', true, true, false, true)
436
- * // → 'export const UserSchema = z.object({name: z.string()}).readonly().openapi("User")\n\nexport type User = z.infer<typeof UserSchema>'
434
+ * `.readonly()` is no concern of this function: `zodToOpenAPI` puts it on the objects and
435
+ * arrays of a schema when asked, and a scalar never takes it. `Readonly<number>` is `number`,
436
+ * but on a branded scalar `.readonly()` wraps the brand and loses the primitive.
437
437
  */
438
- function zodToOpenAPISchema(schemaName, zodSchema, exportSchema, exportType, notComponentSchema, readonly) {
439
- const readonlyModifier = readonly ? ".readonly()" : "";
440
- const schemaCode = exportSchema ? `export const ${schemaName}=${zodSchema}${readonlyModifier}` : `const ${schemaName}=${zodSchema}${readonlyModifier}`;
438
+ function zodToOpenAPISchema(schemaName, zodSchema, exportSchema, exportType, notComponentSchema) {
439
+ const schemaCode = exportSchema ? `export const ${schemaName}=${zodSchema}` : `const ${schemaName}=${zodSchema}`;
441
440
  const typeName = schemaName.replace(/Schema$/u, "");
442
- const componentSchemaCode = exportSchema ? `export const ${schemaName}=${zodSchema}${readonlyModifier}.openapi('${typeName}')` : `const ${schemaName}=${zodSchema}${readonlyModifier}.openapi('${typeName}')`;
441
+ const componentSchemaCode = exportSchema ? `export const ${schemaName}=${zodSchema}.openapi('${typeName}')` : `const ${schemaName}=${zodSchema}.openapi('${typeName}')`;
443
442
  const zodInferCode = exportType ? `\n\nexport type ${typeName}=z.infer<typeof ${schemaName}>` : "";
444
443
  if (notComponentSchema) return `${schemaCode}${zodInferCode}`;
445
444
  return `${componentSchemaCode}${zodInferCode}`;
@@ -1,10 +1,10 @@
1
1
  import { l as INPUT_EXTENSIONS } from "../constants-Bz8YiPum.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-BCaOY0bs.js";
5
- import { E as isInsideDirectory, w as appEntryOutput } from "../core-CHLeBQ6y.js";
4
+ import { q as isRecord } from "../utils-vw99OasL.js";
5
+ import { E as isInsideDirectory, w as appEntryOutput } from "../core-D-vKEwJs.js";
6
6
  import { n as parseOpenAPI } from "../openapi-DQRxq2_O.js";
7
- import { i as packageRoots, n as makeJob, r as outsideSources, t as cleanSplitOutputs } from "../shared-DBOBTH7X.js";
7
+ import { i as packageRoots, n as makeJob, r as outsideSources, t as cleanSplitOutputs } from "../shared-_h_FDhSi.js";
8
8
  import { Effect, FileSystem, Option, Result } from "effect";
9
9
  import path from "node:path";
10
10
  import crypto from "node:crypto";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hono-takibi",
3
- "version": "0.19.0",
3
+ "version": "0.20.0",
4
4
  "description": "Hono Takibi is a code generator from OpenAPI to @hono/zod-openapi",
5
5
  "keywords": [
6
6
  "hono",
@@ -1,11 +0,0 @@
1
- import "./index-B7AwLlPY.js";
2
- import "./index-tsPqeV6H.js";
3
- import { Effect } from "effect";
4
- //#region src/helper/group.d.ts
5
- /**
6
- * The group an operation belongs to, or `undefined` when it belongs to none and is a route
7
- * of `api`. What divides an application depends on how the template writes it.
8
- */
9
- type Grouping = (path: string, tags: readonly string[] | undefined) => string | undefined;
10
- //#endregion
11
- export { Grouping as t };