hono-takibi 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -338,6 +338,17 @@ export default defineConfig({
338
338
  })
339
339
  ```
340
340
 
341
+ Each route answers its success response by default. Like [Prism](https://stoplight.io/open-source/prism), a request can pick any response or named example the document declares with the `Prefer` header (or the `__code` / `__example` query):
342
+
343
+ ```bash
344
+ curl -H 'Prefer: code=404' http://localhost:3000/orders/1 # the 404 response
345
+ curl -H 'Prefer: example=pending' http://localhost:3000/orders/1 # a named example
346
+ curl -H 'Prefer: code=404, example=gone' http://localhost:3000/orders/1
347
+ curl 'http://localhost:3000/orders/1?__code=503'
348
+ ```
349
+
350
+ A code falls back to its `4XX` range, then `default`. A code or example the operation does not declare answers `500` with an `application/problem+json` body saying what is missing.
351
+
341
352
  ## API Reference Docs
342
353
 
343
354
  Generate API reference Markdown with [hono-cli](https://github.com/honojs/cli) `hono request` commands:
@@ -552,8 +563,9 @@ export default defineConfig({
552
563
 
553
564
  mock: {
554
565
  output: './src/mock.ts',
555
- useExamples: true,
566
+ useExamples: true, // true: response examples | 'all': also schema/property examples | false
556
567
  locale: 'en',
568
+ seed: 42, // optional: same body per route on every request (snapshot-friendly)
557
569
  delay: false,
558
570
  arrayMin: 1,
559
571
  arrayMax: 10,
package/dist/cli.js CHANGED
@@ -71,7 +71,7 @@ function runConfigPass(configPath, reload) {
71
71
  import("./index.js"),
72
72
  import("./openapi-CzAVsFDt.js").then((n) => n.t),
73
73
  import("./format-Bm9LZ_ki.js").then((n) => n.r),
74
- import("./shared-Ck7P2pO5.js").then((n) => n.i)
74
+ import("./shared-BJ4A07Yx.js").then((n) => n.i)
75
75
  ]));
76
76
  const config = yield* readConfig(configPath, reload);
77
77
  const jobs = makeJob(yield* parseOpenAPI(config.input), config);
@@ -204,7 +204,7 @@ function generate(args) {
204
204
  });
205
205
  }
206
206
  if (input !== void 0 && output !== void 0) {
207
- const [{ parseOpenAPI }, { takibi }] = yield* Effect.promise(() => Promise.all([import("./openapi-CzAVsFDt.js").then((n) => n.t), import("./core-BdG_5KX8.js").then((n) => n.t)]));
207
+ const [{ parseOpenAPI }, { takibi }] = yield* Effect.promise(() => Promise.all([import("./openapi-CzAVsFDt.js").then((n) => n.t), import("./core-CpzC5kSm.js").then((n) => n.t)]));
208
208
  return yield* Console.log(yield* takibi(yield* parseOpenAPI(input), output, ONE_SHOT_COMPONENTS));
209
209
  }
210
210
  const resolvedConfig = configPath ?? DEFAULT_CONFIG_FILE;
@@ -1,4 +1,4 @@
1
- import { t as OpenAPI } from "../../index-B2QvGO4j.js";
1
+ import { t as OpenAPI } from "../../index-Dw-w92xu.js";
2
2
  import { Effect } from "effect";
3
3
  //#region src/core/docs/index.d.ts
4
4
  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,2 +1,2 @@
1
- import { t as docs } from "../../docs-MzhmjfNS.js";
1
+ import { t as docs } from "../../docs-C1_fNNJ-.js";
2
2
  export { docs };
@@ -1,4 +1,4 @@
1
- import { t as OpenAPI } from "../../index-B2QvGO4j.js";
1
+ import { t as OpenAPI } from "../../index-Dw-w92xu.js";
2
2
  import { t as FormatError } from "../../index-wD0wV6VQ.js";
3
3
  import { t as GenerateError } from "../../index-6-_xlYFY.js";
4
4
  //#region src/core/hooks/index.d.ts
@@ -1,2 +1,2 @@
1
- import { t as hooks } from "../../hooks-iffNFEYy.js";
1
+ import { t as hooks } from "../../hooks-6j2Z-MPl.js";
2
2
  export { hooks };
@@ -1,4 +1,4 @@
1
- import { t as OpenAPI } from "../../index-B2QvGO4j.js";
1
+ import { t as OpenAPI } from "../../index-Dw-w92xu.js";
2
2
  import { t as FormatError } from "../../index-wD0wV6VQ.js";
3
3
  import { t as GenerateError } from "../../index-6-_xlYFY.js";
4
4
  import { Effect } from "effect";
@@ -1,6 +1,6 @@
1
- import { A as isOperationLike, O as isOpenAPIPaths, R as isRecord, d as methodPath, l as makeInferRequestType } from "../../utils-BDa05U34.js";
1
+ import { f as methodPath, j as isOperationLike, k as isOpenAPIPaths, l as makeInferRequestType, z as isRecord } from "../../utils-DEFpxBMu.js";
2
2
  import { t as emit } from "../../emit-B_3fXoto.js";
3
- import { a as parsePathItem, i as operationHasArgs, o as resolveSplitOutDir, r as makeOperationDeps, s as GenerateError, t as formatPath } from "../../rpc-B95CYct5.js";
3
+ import { a as parsePathItem, i as operationHasArgs, o as resolveSplitOutDir, r as makeOperationDeps, s as GenerateError, t as formatPath } from "../../rpc-D_eeOVGa.js";
4
4
  import { Effect } from "effect";
5
5
  import { dirname, join } from "node:path";
6
6
  //#region src/core/rpc/index.ts
@@ -1,4 +1,4 @@
1
- import { t as OpenAPI } from "../../index-B2QvGO4j.js";
1
+ import { t as OpenAPI } from "../../index-Dw-w92xu.js";
2
2
  import { t as FormatError } from "../../index-wD0wV6VQ.js";
3
3
  import { Effect } from "effect";
4
4
  //#region src/core/type/index.d.ts
@@ -1,4 +1,4 @@
1
- import { E as isMediaWithSchema, M as isParameterArray, O as isOpenAPIPaths, U as isSchemaArray, V as isRequestBody, Y as isStringRef, h as statusCodeToNumber, j as isParameter, k as isOperation, u as makeSafeKey, w as isHttpMethod } from "../../utils-BDa05U34.js";
1
+ import { A as isOperation, D as isMediaWithSchema, H as isRequestBody, M as isParameter, N as isParameterArray, T as isHttpMethod, W as isSchemaArray, X as isStringRef, g as statusCodeToNumber, k as isOpenAPIPaths, u as makeSafeKey } from "../../utils-DEFpxBMu.js";
2
2
  import { t as emit } from "../../emit-B_3fXoto.js";
3
3
  import { Effect } from "effect";
4
4
  import path from "node:path";
@@ -1,12 +1,12 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
2
2
  import { i as readdir, n as mkdir, o as writeFile, r as readFile } from "./file-CwKqigE9.js";
3
3
  import { n as fmt } from "./format-Bm9LZ_ki.js";
4
- import { E as isMediaWithSchema, F as isPathItem, I as isPathItemEntry, K as isSecurityArray, L as isPathItemRef, P as isParameterRef, U as isSchemaArray, W as isSchemaObject, _ as uncapitalize, b as isCallbacks, c as makeBarrel, d as methodPath, g as toIdentifierPascalCase, h as statusCodeToNumber, i as ensureSuffix, j as isParameter, k as isOperation, p as renderNamedImport, q as isSecurityScheme, r as cyclicNodes, s as escapeRegexLiteral, v as uncapitalizeWord, w as isHttpMethod, x as isContentBody, y as zodToOpenAPISchema, z as isRefObject } from "./utils-BDa05U34.js";
4
+ import { A as isOperation, B as isRefObject, D as isMediaWithSchema, F as isParameterRef, G as isSchemaObject, I as isPathItem, J as isSecurityScheme, L as isPathItemEntry, M as isParameter, R as isPathItemRef, S as isContentBody, T as isHttpMethod, W as isSchemaArray, _ as toIdentifierPascalCase, b as zodToOpenAPISchema, c as makeBarrel, d as makeStringLiteral, f as methodPath, g as statusCodeToNumber, i as ensureSuffix, m as renderNamedImport, p as normalizeTypes, q as isSecurityArray, r as cyclicNodes, u as makeSafeKey, v as uncapitalize, x as isCallbacks, y as uncapitalizeWord } from "./utils-DEFpxBMu.js";
5
5
  import { t as emit } from "./emit-B_3fXoto.js";
6
- import { s as GenerateError } from "./rpc-B95CYct5.js";
7
- import { S as makeModuleSpec, _ as makeRef, a as responsesCode, b as makeExportConst, c as headersCode, d as ast, f as zodToOpenAPI, g as makePathItem, h as makeOperationResponses, i as schemasCode, l as makeSplitSchemaFile, m as makeCallbacks, n as routeCode, o as requestBodiesCode, p as makeCallback, r as componentsCode, s as parametersCode, t as zodOpenAPIHono, u as analyzeCircularSchemas, v as makeRequest, x as makeImports, y as makeConst } from "./openapi-B2CqQVWF.js";
8
- import { t as hooks } from "./hooks-iffNFEYy.js";
9
- import { t as docs } from "./docs-MzhmjfNS.js";
6
+ import { s as GenerateError } from "./rpc-D_eeOVGa.js";
7
+ import { S as makeModuleSpec, _ as makeRef, a as responsesCode, b as makeExportConst, c as headersCode, d as ast, f as zodToOpenAPI, g as makePathItem, h as makeOperationResponses, i as schemasCode, l as makeSplitSchemaFile, m as makeCallbacks, n as routeCode, o as requestBodiesCode, p as makeCallback, r as componentsCode, s as parametersCode, t as zodOpenAPIHono, u as analyzeCircularSchemas, v as makeRequest, x as makeImports, y as makeConst } from "./openapi-DhxrYmuQ.js";
8
+ import { t as hooks } from "./hooks-6j2Z-MPl.js";
9
+ import { t as docs } from "./docs-C1_fNNJ-.js";
10
10
  import { rpc } from "./core/rpc/index.js";
11
11
  import { type } from "./core/type/index.js";
12
12
  import { Effect } from "effect";
@@ -43,7 +43,32 @@ const FORMAT_TO_FAKER = {
43
43
  int64: "faker.number.bigInt({ min: 0n, max: 9007199254740991n })",
44
44
  bigint: "faker.number.bigInt({ min: 0n, max: 9007199254740991n })",
45
45
  float: "faker.number.float({ min: 0, max: 1000, fractionDigits: 2 })",
46
- double: "faker.number.float({ min: 0, max: 1000000, fractionDigits: 4 })"
46
+ double: "faker.number.float({ min: 0, max: 1000000, fractionDigits: 4 })",
47
+ uuidv4: "faker.string.uuid({ version: 4 })",
48
+ uuidv6: "faker.string.uuid({ version: 6 })",
49
+ uuidv7: "faker.string.uuid({ version: 7 })",
50
+ guid: "faker.string.uuid()",
51
+ ulid: "faker.string.ulid()",
52
+ nanoid: "faker.string.nanoid()",
53
+ cuid: "`c${faker.string.alphanumeric({ length: 24, casing: 'lower' })}`",
54
+ cuid2: "faker.string.alphanumeric({ length: 24, casing: 'lower' })",
55
+ jwt: "faker.internet.jwt()",
56
+ emoji: "faker.internet.emoji()",
57
+ mac: "faker.internet.mac()",
58
+ hex: "faker.string.hexadecimal({ length: 16, prefix: '' })",
59
+ base64: "btoa(faker.string.alphanumeric(12))",
60
+ base64url: "faker.string.alphanumeric(16)",
61
+ cidrv4: "`${faker.internet.ipv4()}/${faker.number.int({ min: 0, max: 32 })}`",
62
+ cidrv6: "`${faker.internet.ipv6()}/${faker.number.int({ min: 0, max: 128 })}`",
63
+ duration: "`P${faker.number.int({ min: 1, max: 30 })}D`",
64
+ e164: "faker.phone.number({ style: 'international' })",
65
+ httpUrl: "faker.internet.url()",
66
+ "uri-reference": "faker.internet.url()",
67
+ iri: "faker.internet.url()",
68
+ "iri-reference": "faker.internet.url()",
69
+ "idn-email": "faker.internet.email()",
70
+ "idn-hostname": "faker.internet.domainName()",
71
+ decimal: "faker.commerce.price()"
47
72
  };
48
73
  const TYPE_TO_FAKER = {
49
74
  string: "faker.string.alpha({ length: { min: 5, max: 20 } })",
@@ -83,6 +108,78 @@ const PROPERTY_NAME_TO_FAKER = {
83
108
  count: "faker.number.int({ min: 0, max: 1000 })",
84
109
  age: "faker.number.int({ min: 1, max: 120 })"
85
110
  };
111
+ function lookup(table, key) {
112
+ return Object.hasOwn(table, key) ? table[key] : void 0;
113
+ }
114
+ const TYPE_PRIORITY = [
115
+ "string",
116
+ "number",
117
+ "integer",
118
+ "boolean",
119
+ "array",
120
+ "object",
121
+ "date"
122
+ ];
123
+ function isHintCompatible(type, expr) {
124
+ if (type === void 0) return true;
125
+ const isInt = expr.startsWith("faker.number.int(");
126
+ if (type === "integer") return isInt || expr.startsWith("faker.number.bigInt(");
127
+ if (type === "number") return isInt || expr.startsWith("faker.number.float(");
128
+ if (type === "string") return !expr.startsWith("faker.number.");
129
+ return false;
130
+ }
131
+ function propertyNameHint(propertyName) {
132
+ return lookup(PROPERTY_NAME_TO_FAKER, propertyName) ?? lookup(PROPERTY_NAME_TO_FAKER, propertyName.replaceAll(/[_-]+([a-zA-Z0-9])/gu, (_, c) => c.toUpperCase()));
133
+ }
134
+ /**
135
+ * The name of the generated mock factory for a component schema. Kept as
136
+ * `mock<Name>` (dots dropped) whenever that is already an identifier, so
137
+ * existing output is unchanged; any other name (`User-Profile`) goes through
138
+ * the same sanitizer as the schema consts (`toIdentifierPascalCase`), since
139
+ * OpenAPI component names may contain `-`.
140
+ */
141
+ function mockFunctionName(refName) {
142
+ const stripped = refName.replaceAll(".", "");
143
+ return /^[A-Za-z0-9_$]+$/u.test(stripped) ? `mock${stripped}` : `mock${toIdentifierPascalCase(refName)}`;
144
+ }
145
+ /**
146
+ * Rewrites a `pattern` into the string `faker.helpers.fromRegExp` samples.
147
+ *
148
+ * faker reads a `RegExp` argument through `.source`, where `/` is always
149
+ * escaped as `\/`, and copies that backslash into the value — so a regex
150
+ * literal can never produce a value containing `/` that matches the pattern.
151
+ * Passing a string avoids it, but faker only strips `^`/`$` from a `RegExp`,
152
+ * so the anchors (and the no-op `\/` escape) are removed here instead. The
153
+ * result is emitted as an escaped string literal, never as regex-literal code.
154
+ */
155
+ function fakerPattern(pattern) {
156
+ return pattern.replace(/^\^+/u, "").replace(/(?<!\\)(?:\\\\)*\$+$/u, (anchor) => anchor.replaceAll("$", "")).replaceAll(/\\([\s\S])/gu, (match, escaped) => escaped === "/" ? "/" : match);
157
+ }
158
+ function schemaExample(schema) {
159
+ if (schema.example !== void 0) return schema.example;
160
+ return Array.isArray(schema.examples) ? schema.examples[0] : void 0;
161
+ }
162
+ function exampleLiteral(schema) {
163
+ const example = schemaExample(schema);
164
+ if (example === void 0) return void 0;
165
+ const types = normalizeTypes(schema.type);
166
+ if (schema.$ref !== void 0 || types.length === 0 && !schema.enum) return void 0;
167
+ const isAccepted = (type) => types.length === 0 || types.includes(type);
168
+ if (example === null) return types.includes("null") || schema.nullable === true ? "null" : void 0;
169
+ if (schema.enum && !schema.enum.some((member) => member === example)) return void 0;
170
+ const asConst = schema.enum ? " as const" : "";
171
+ if (typeof example === "string") {
172
+ if (!isAccepted("string") || schema.format === "binary") return void 0;
173
+ return `${JSON.stringify(example)}${asConst}`;
174
+ }
175
+ if (typeof example === "number") {
176
+ if (types.includes("integer") && (schema.format === "int64" || schema.format === "bigint")) return Number.isInteger(example) ? `${BigInt(example)}n` : void 0;
177
+ if (!(isAccepted("number") || isAccepted("integer"))) return void 0;
178
+ if (!(isAccepted("number") || Number.isInteger(example))) return void 0;
179
+ return `${JSON.stringify(example)}${asConst}`;
180
+ }
181
+ if (typeof example === "boolean") return isAccepted("boolean") ? `${example}${asConst}` : void 0;
182
+ }
86
183
  function hasNumericConstraint(schema) {
87
184
  return schema.minimum !== void 0 || schema.maximum !== void 0 || schema.exclusiveMinimum !== void 0 || schema.exclusiveMaximum !== void 0 || schema.multipleOf !== void 0;
88
185
  }
@@ -126,35 +223,56 @@ function resolveRef(schema, schemas) {
126
223
  }
127
224
  function isKnownScalar(schema, schemas) {
128
225
  const resolved = resolveRef(schema, schemas);
226
+ const types = normalizeTypes(resolved.type);
129
227
  if (resolved.enum || resolved.const !== void 0) return true;
130
- if (resolved.properties || resolved.type === "object") return false;
228
+ if (resolved.properties || types.includes("object")) return false;
131
229
  if (resolved.allOf && resolved.allOf.length > 0) return resolved.allOf.every((s) => isKnownScalar(s, schemas));
132
- if (resolved.oneOf || resolved.anyOf || resolved.type === "array") return false;
133
- return typeof resolved.type === "string";
230
+ if (resolved.oneOf || resolved.anyOf || types.includes("array")) return false;
231
+ return types.length > 0;
134
232
  }
135
233
  function schemaToFaker(schema, propertyName, options = {}) {
136
- if (options.useExamples && schema.example !== void 0) return JSON.stringify(schema.example);
137
234
  if (schema.const !== void 0) return `${JSON.stringify(schema.const)} as const`;
235
+ if (options.useExamples) {
236
+ const example = exampleLiteral(schema);
237
+ if (example !== void 0) return example;
238
+ }
138
239
  if (schema.enum && schema.enum.length > 0) return `faker.helpers.arrayElement([${schema.enum.map((v) => JSON.stringify(v)).join(", ")}] as const)`;
139
- if (schema.$ref) return `mock${(schema.$ref.split("/").pop() || "unknown").replaceAll(".", "")}()`;
240
+ if (schema.$ref) return `${mockFunctionName(schema.$ref.split("/").pop() || "unknown")}()`;
241
+ if (Array.isArray(schema.type)) {
242
+ const types = schema.type;
243
+ const primary = schema.properties !== void 0 && types.includes("object") ? "object" : TYPE_PRIORITY.find((t) => types.includes(t));
244
+ if (primary === void 0) return types.includes("null") ? "null" : "undefined";
245
+ const value = schemaToFaker({
246
+ ...schema,
247
+ type: primary
248
+ }, propertyName, options);
249
+ return types.includes("null") ? `faker.helpers.arrayElement([${value}, null])` : value;
250
+ }
140
251
  if (schema.type === "array" && schema.items) {
141
252
  const itemSchema = isSchemaArray(schema.items) ? schema.items[0] : schema.items;
142
253
  if (!isSchemaObject(itemSchema)) return "[]";
143
254
  const itemFaker = schemaToFaker(itemSchema, void 0, options);
144
- const min = schema.minItems ?? options.arrayMin ?? 1;
145
- return `Array.from({ length: faker.number.int({ min: ${min}, max: ${schema.maxItems ?? options.arrayMax ?? Math.max(min, 10)} }) }, () => (${itemFaker}))`;
255
+ const min = schema.minItems ?? Math.min(options.arrayMin ?? 1, schema.maxItems ?? Infinity);
256
+ return `Array.from({ length: faker.number.int({ min: ${min}, max: ${schema.maxItems ?? Math.max(options.arrayMax ?? 10, min)} }) }, () => (${itemFaker}))`;
146
257
  }
147
258
  const renderProps = (properties, required) => {
148
259
  const requiredSet = new Set(required);
149
260
  return Object.entries(properties).map(([k, v]) => {
261
+ const key = makeSafeKey(k);
150
262
  const value = schemaToFaker(v, k, options);
151
- if (!(requiredSet.has(k) || v.nullable)) return `${k}: faker.helpers.arrayElement([${value}, undefined])`;
152
- if (v.nullable) return `${k}: faker.helpers.arrayElement([${value}, null])`;
153
- return `${k}: ${value}`;
263
+ const isNullable = v.nullable === true || normalizeTypes(v.type).includes("null");
264
+ if (!(requiredSet.has(k) || isNullable)) return `${key}: faker.helpers.arrayElement([${value}, undefined])`;
265
+ if (v.nullable) return `${key}: faker.helpers.arrayElement([${value}, null])`;
266
+ return `${key}: ${value}`;
154
267
  }).join(", ");
155
268
  };
156
269
  if (schema.type === "object" && schema.properties) return `{ ${renderProps(schema.properties, schema.required)} }`;
157
- if (schema.type === "object" && !schema.properties && schema.additionalProperties) return "{}";
270
+ if (schema.type === "object" && !schema.properties && schema.additionalProperties) {
271
+ if (typeof schema.additionalProperties === "boolean" || schema.propertyNames !== void 0 || schema.patternProperties !== void 0) return "{}";
272
+ const value = schemaToFaker(schema.additionalProperties, void 0, options);
273
+ const max = schema.maxProperties ?? Math.max(schema.minProperties ?? 1, 3);
274
+ return `Object.fromEntries(Array.from({ length: faker.number.int({ min: ${schema.minProperties ?? Math.min(1, max)}, max: ${max} }) }, () => [faker.string.alpha(8), ${value}] satisfies [string, unknown]))`;
275
+ }
158
276
  if (schema.allOf && schema.allOf.length > 0) {
159
277
  if (!schema.properties && schema.allOf.every((s) => isKnownScalar(s, options.schemas))) {
160
278
  const [only] = schema.allOf;
@@ -170,24 +288,24 @@ function schemaToFaker(schema, propertyName, options = {}) {
170
288
  }
171
289
  const union = schema.oneOf && schema.oneOf.length > 0 ? schema.oneOf : schema.anyOf && schema.anyOf.length > 0 ? schema.anyOf : void 0;
172
290
  if (union) return `faker.helpers.arrayElement([${union.map((s) => schemaToFaker(s, propertyName, options)).join(", ")}])`;
173
- if ((schema.type === "integer" || schema.type === "number") && hasNumericConstraint(schema)) return numericFaker(schema, numericRange(schema, schema.type === "integer"));
174
- if (schema.format && FORMAT_TO_FAKER[schema.format]) return FORMAT_TO_FAKER[schema.format];
175
- if (propertyName && PROPERTY_NAME_TO_FAKER[propertyName]) {
176
- const hint = PROPERTY_NAME_TO_FAKER[propertyName];
177
- const isNumberHint = hint.includes("faker.number.");
291
+ const type = typeof schema.type === "string" ? schema.type : void 0;
292
+ if ((type === "integer" || type === "number") && hasNumericConstraint(schema)) return numericFaker(schema, numericRange(schema, type === "integer"));
293
+ const formatHint = schema.format ? lookup(FORMAT_TO_FAKER, schema.format) : void 0;
294
+ if (formatHint && isHintCompatible(type, formatHint)) return formatHint;
295
+ const nameHint = propertyName ? propertyNameHint(propertyName) : void 0;
296
+ if (nameHint && isHintCompatible(type, nameHint)) {
178
297
  const hasStringConstraint = schema.pattern !== void 0 || schema.minLength !== void 0 || schema.maxLength !== void 0;
179
- if (!(schema.type === "string" && (isNumberHint || hasStringConstraint))) return hint;
298
+ if (!(type === "string" && hasStringConstraint)) return nameHint;
180
299
  }
181
- if (schema.type && typeof schema.type === "string" && TYPE_TO_FAKER[schema.type]) {
182
- if (schema.type === "string") {
183
- if (schema.pattern) return `faker.helpers.fromRegExp(/${escapeRegexLiteral(schema.pattern)}/)`;
184
- const min = schema.minLength ?? 5;
185
- return `faker.string.alpha({ length: { min: ${min}, max: ${schema.maxLength ?? Math.max(min, 20)} } })`;
186
- }
187
- if (schema.type === "integer" || schema.type === "number") return numericFaker(schema, numericRange(schema, schema.type === "integer"));
188
- return TYPE_TO_FAKER[schema.type];
300
+ if (type === "string") {
301
+ if (schema.pattern) return `faker.helpers.fromRegExp(${makeStringLiteral(fakerPattern(schema.pattern))})`;
302
+ const min = schema.minLength ?? 5;
303
+ return `faker.string.alpha({ length: { min: ${min}, max: ${schema.maxLength ?? Math.max(min, 20)} } })`;
189
304
  }
190
- return "undefined";
305
+ if (type === "integer" || type === "number") return numericFaker(schema, numericRange(schema, type === "integer"));
306
+ if (type === "object") return "{}";
307
+ if (type === "array") return "[]";
308
+ return (type ? lookup(TYPE_TO_FAKER, type) : void 0) ?? "undefined";
191
309
  }
192
310
  /**
193
311
  * Sentinel path-param value both the test generator (request path) and the mock
@@ -197,7 +315,9 @@ function schemaToFaker(schema, propertyName, options = {}) {
197
315
  function getNonExistentValue(schema, schemas) {
198
316
  if (!schema) return "__non_existent__";
199
317
  const resolved = schema.$ref && schemas ? schemas[schema.$ref.replace("#/components/schemas/", "")] ?? schema : schema;
200
- if (resolved.type === "integer" || resolved.type === "number") return "-1";
318
+ const types = normalizeTypes(resolved.type);
319
+ const primary = TYPE_PRIORITY.find((t) => types.includes(t));
320
+ if (primary === "integer" || primary === "number") return "-1";
201
321
  if (resolved.format === "uuid") return "00000000-0000-0000-0000-000000000000";
202
322
  return "__non_existent__";
203
323
  }
@@ -602,9 +722,9 @@ function makeMockFunction(name, schema, schemas, isCircular, fakerOptions) {
602
722
  ...fakerOptions
603
723
  });
604
724
  const returnType = isCircular ? ": any" : "";
605
- const sanitized = name.replaceAll(".", "");
606
725
  const schemaConst = toIdentifierPascalCase(ensureSuffix(name, "Schema"));
607
- return `function mock${sanitized}()${returnType}{return ${schema["x-brand"] ? `${mockBody} as z.infer<typeof ${schemaConst}>` : mockBody}}`;
726
+ const body = schema["x-brand"] ? `${mockBody} as z.infer<typeof ${schemaConst}>` : mockBody;
727
+ return `function ${mockFunctionName(name)}()${returnType}{return ${body}}`;
608
728
  }
609
729
  function extractSecurityInfo(opSecurity, globalSecurity, securitySchemes) {
610
730
  return (opSecurity ?? globalSecurity ?? []).flatMap((secDef) => Object.keys(secDef).flatMap((schemeName) => {
@@ -702,6 +822,7 @@ function resolveSuccessResponse(responses, componentResponses) {
702
822
  const key = [...priority, ...others][0];
703
823
  if (!key) return void 0;
704
824
  return {
825
+ key,
705
826
  statusCode: statusCodeToNumber(key),
706
827
  response: resolveResponse(responses[key], componentResponses)
707
828
  };
@@ -715,55 +836,156 @@ function makeAuthCheck(security, has401) {
715
836
  const authChecks = security.flatMap((sec) => {
716
837
  if (sec.type === "bearer" || sec.type === "oauth2" || sec.type === "basic") return [`c.req.header('Authorization')`];
717
838
  if (sec.type === "apiKey") {
718
- if (sec.in === "header") return [`c.req.header('${sec.name}')`];
719
- if (sec.in === "query") return [`c.req.query('${sec.name}')`];
720
- if (sec.in === "cookie") return [`getCookie(c, '${sec.name}')`];
839
+ if (sec.in === "header") return [`c.req.header(${makeStringLiteral(sec.name)})`];
840
+ if (sec.in === "query") return [`c.req.query(${makeStringLiteral(sec.name)})`];
841
+ if (sec.in === "cookie") return [`getCookie(c, ${makeStringLiteral(sec.name)})`];
721
842
  }
722
843
  return [];
723
844
  });
724
845
  if (authChecks.length === 0) return "";
725
846
  return `if(!(${authChecks.join(" || ")})){return c.json({ message: 'Unauthorized' }, 401)}`;
726
847
  }
727
- function extractMediaExample(media, components) {
728
- if (media.example !== void 0) return media.example;
729
- if (!media.examples) return void 0;
730
- const first = Object.values(media.examples)[0];
731
- if (!first) return void 0;
732
- if ("$ref" in first && typeof first.$ref === "string") {
733
- const name = first.$ref.split("/").at(-1);
848
+ function exampleEntryValue(entry, components) {
849
+ if ("$ref" in entry && typeof entry.$ref === "string") {
850
+ const name = entry.$ref.split("/").at(-1);
734
851
  const resolved = name ? components?.examples?.[name] : void 0;
735
852
  return resolved && "value" in resolved ? resolved.value : void 0;
736
853
  }
737
- return "value" in first ? first.value : void 0;
854
+ return "value" in entry ? entry.value : void 0;
855
+ }
856
+ function extractMediaExample(media, components) {
857
+ if (media.example !== void 0) return media.example;
858
+ const first = Object.values(media.examples ?? {})[0];
859
+ return first ? exampleEntryValue(first, components) : void 0;
860
+ }
861
+ function jsonMediaType(content) {
862
+ const types = Object.keys(content ?? {});
863
+ return types.includes("application/json") ? "application/json" : types.find((type) => /^application\/(?:[\w.-]+\+)?json(?:;|$)/u.test(type));
864
+ }
865
+ function describeResponse(key, response, components, useExamples) {
866
+ const jsonType = jsonMediaType(response.content);
867
+ const jsonMedia = jsonType ? response.content?.[jsonType] : void 0;
868
+ const textMedia = response.content?.["text/plain"];
869
+ const jsonSchema = jsonMedia && isMediaWithSchema(jsonMedia) ? jsonMedia.schema : void 0;
870
+ return {
871
+ key: /^[1-5]xx$/iu.test(key) ? key.toUpperCase() : key,
872
+ jsonType,
873
+ jsonSchema,
874
+ textSchema: textMedia && isMediaWithSchema(textMedia) ? textMedia.schema : void 0,
875
+ example: useExamples && jsonMedia ? extractMediaExample(jsonMedia, components) : void 0,
876
+ namedExamples: Object.entries(jsonMedia?.examples ?? {}).flatMap(([name, entry]) => {
877
+ const value = exampleEntryValue(entry, components);
878
+ return value === void 0 ? [] : [[name, value]];
879
+ }),
880
+ exampleCast: jsonSchema?.$ref ? toIdentifierPascalCase(ensureSuffix(jsonSchema.$ref.split("/").at(-1) ?? "", "Schema")) : void 0
881
+ };
738
882
  }
739
- function makeHandlerBody(args) {
740
- const { statusCode, jsonSchema, textSchema, schemas, fakerOptions, allRefs, exampleValue, exampleCast } = args;
741
- if (exampleValue !== void 0) {
742
- const cast = exampleCast ? ` as z.infer<typeof ${exampleCast}>` : "";
743
- return `return c.json(${JSON.stringify(exampleValue)}${cast}, ${statusCode})`;
883
+ function responsePayload(response, example, schemas, fakerOptions, allRefs) {
884
+ if (example !== void 0) {
885
+ const cast = response.exampleCast ? ` as z.infer<typeof ${response.exampleCast}>` : "";
886
+ return {
887
+ kind: "json",
888
+ data: `${JSON.stringify(example)}${cast}`
889
+ };
744
890
  }
745
- if (jsonSchema) {
746
- collectRefs(jsonSchema, allRefs);
747
- return `return c.json(${schemaToFaker(jsonSchema, void 0, {
891
+ if (response.jsonSchema) {
892
+ collectRefs(response.jsonSchema, allRefs);
893
+ return {
894
+ kind: "json",
895
+ data: schemaToFaker(response.jsonSchema, void 0, {
896
+ schemas,
897
+ ...fakerOptions
898
+ })
899
+ };
900
+ }
901
+ if (response.textSchema) return {
902
+ kind: "text",
903
+ data: schemaToFaker(response.textSchema, void 0, {
748
904
  schemas,
749
905
  ...fakerOptions
750
- })}, ${statusCode})`;
906
+ })
907
+ };
908
+ return { kind: "none" };
909
+ }
910
+ function makeHandlerBody(statusCode, response, payload) {
911
+ if (payload.kind === "json") {
912
+ const headers = response?.jsonType && response.jsonType !== "application/json" ? `, { 'Content-Type': ${makeStringLiteral(response.jsonType)} }` : "";
913
+ return `return c.json(${payload.data}, ${statusCode}${headers})`;
751
914
  }
752
- if (textSchema) return `return c.text(${schemaToFaker(textSchema, void 0, {
753
- schemas,
754
- ...fakerOptions
755
- })}, ${statusCode})`;
915
+ if (payload.kind === "text") return `return c.text(${payload.data}, ${statusCode})`;
756
916
  if (statusCode === 204) return `return new Response(null, { status: 204 })`;
757
917
  return `return c.body(null, ${statusCode})`;
758
918
  }
919
+ function makeRawHandlerBody(statusExpr, response, payload) {
920
+ if (payload.kind === "json") {
921
+ const type = makeStringLiteral(response.jsonType ?? "application/json");
922
+ return `return preferResponse(${statusExpr}, JSON.stringify(${payload.data}), ${type})`;
923
+ }
924
+ if (payload.kind === "text") return `return preferResponse(${statusExpr}, String(${payload.data}), 'text/plain')`;
925
+ return `return preferResponse(${statusExpr}, null)`;
926
+ }
927
+ const PREFER_HELPERS = `// Reads Prism's \`Prefer: code=<status>, example=<name>\` header (or the \`__code\` /
928
+ // \`__example\` query) and resolves it against the responses the route declares:
929
+ // the exact status, then its \`NXX\` range, then \`default\`. Without a code the
930
+ // example is looked up in the success response. Anything the route does not
931
+ // declare answers 500 problem+json, as Prism does.
932
+ function resolvePrefer(
933
+ req: { header(name: string): string | undefined; query(name: string): string | undefined },
934
+ responses: { readonly [key: string]: readonly string[] },
935
+ success: string,
936
+ ) {
937
+ let code = req.query('__code')
938
+ let example = req.query('__example')
939
+ for (const [, name = '', quoted, bare] of (req.header('Prefer') ?? '').matchAll(
940
+ /([A-Za-z]+)\\s*=\\s*(?:"([^"]*)"|([^\\s,;]*))/gu,
941
+ )) {
942
+ if (name.toLowerCase() === 'code') code ??= quoted ?? bare
943
+ if (name.toLowerCase() === 'example') example ??= quoted ?? bare
944
+ }
945
+ if (code === undefined && example === undefined) return {}
946
+ if (code !== undefined && !/^[2-5]\\d\\d$/u.test(code)) {
947
+ preferProblem(\`Prefer code=\${code} is not a status code between 200 and 599.\`)
948
+ }
949
+ const key =
950
+ code === undefined
951
+ ? success
952
+ : [code, \`\${code.slice(0, 1)}XX\`, 'default'].find((k) => Object.hasOwn(responses, k))
953
+ if (key === undefined) preferProblem(\`No \${code} response is declared for this operation.\`)
954
+ if (example !== undefined && !responses[key]?.includes(example)) {
955
+ preferProblem(\`No example named "\${example}" is declared for the \${key} response.\`)
956
+ }
957
+ return { key, code, example }
958
+ }
959
+
960
+ // Answers with a status the route's types cannot name (a \`4XX\`/\`default\` response
961
+ // picked at runtime); Hono's error handler sends \`res\` with that status.
962
+ function preferResponse(status: number, body: string | null, contentType?: string): never {
963
+ throw new HTTPException(status as ContentfulStatusCode, {
964
+ res: new Response(body, contentType ? { headers: { 'Content-Type': contentType } } : {}),
965
+ })
966
+ }
967
+
968
+ function preferProblem(detail: string): never {
969
+ return preferResponse(
970
+ 500,
971
+ JSON.stringify({ type: 'about:blank', title: 'Mock response unavailable', status: 500, detail }),
972
+ 'application/problem+json',
973
+ )
974
+ }`;
975
+ const SEED_REF_DATE = "2025-01-01T00:00:00.000Z";
759
976
  function delayMiddlewareCode(delay) {
760
977
  const ms = typeof delay === "number" ? `${delay}` : typeof delay === "object" && delay !== null ? `faker.number.int({ min: ${delay.min}, max: ${delay.max} })` : void 0;
761
978
  if (ms === void 0) return "";
762
979
  return `\n\napp.use(async (_c, next) => {\n await new Promise((resolve) => setTimeout(resolve, ${ms}))\n await next()\n})`;
763
980
  }
764
981
  function makeMock(openapi, basePath, options = {}) {
765
- const { useExamples: useExamplesOption, locale, delay, readonly: readonlyOption, ...fakerOptions } = options;
982
+ const { useExamples: useExamplesOption, locale, delay, seed, readonly: readonlyOption, arrayMin, arrayMax } = options;
766
983
  const useExamples = useExamplesOption ?? true;
984
+ const fakerOptions = {
985
+ ...arrayMin !== void 0 ? { arrayMin } : {},
986
+ ...arrayMax !== void 0 ? { arrayMax } : {},
987
+ ...useExamples === "all" ? { useExamples: true } : {}
988
+ };
767
989
  const filteredOpenapi = filterToJsonContentTypes(openapi);
768
990
  const paths = filteredOpenapi.paths;
769
991
  const schemas = openapi.components?.schemas ?? {};
@@ -777,23 +999,25 @@ function makeMock(openapi, basePath, options = {}) {
777
999
  const requiresAuth = security.length > 0;
778
1000
  const success = resolveSuccessResponse(operation.responses, componentResponses);
779
1001
  const statusCode = success?.statusCode ?? 200;
780
- const successResponse = success?.response;
781
- const jsonMedia = successResponse?.content?.["application/json"];
782
- const textMedia = successResponse?.content?.["text/plain"];
783
- const jsonSchema = jsonMedia && isMediaWithSchema(jsonMedia) ? jsonMedia.schema : void 0;
784
- const textSchema = textMedia && isMediaWithSchema(textMedia) ? textMedia.schema : void 0;
785
- const exampleValue = useExamples && jsonMedia ? extractMediaExample(jsonMedia, openapi.components) : void 0;
786
- const exampleCast = exampleValue !== void 0 && jsonSchema?.$ref ? toIdentifierPascalCase(ensureSuffix(jsonSchema.$ref.split("/").at(-1) ?? "", "Schema")) : void 0;
787
- const handlerBody = makeHandlerBody({
788
- statusCode,
789
- jsonSchema,
790
- textSchema,
791
- schemas,
792
- fakerOptions,
793
- allRefs,
794
- exampleValue,
795
- exampleCast
1002
+ const successKey = success?.key ?? "200";
1003
+ const responses = Object.entries(operation.responses ?? {}).flatMap(([key, raw]) => {
1004
+ const response = resolveResponse(raw, componentResponses);
1005
+ return response ? [describeResponse(key, response, openapi.components, useExamples !== false)] : [];
796
1006
  });
1007
+ const successResponse = responses.find((r) => r.key === successKey);
1008
+ const handlerBody = makeHandlerBody(statusCode, successResponse, successResponse ? responsePayload(successResponse, successResponse.example, schemas, fakerOptions, allRefs) : { kind: "none" });
1009
+ const preferTable = JSON.stringify(Object.fromEntries(responses.map((r) => [r.key, r.namedExamples.map(([name]) => name)])));
1010
+ const preferBranches = responses.flatMap((response) => {
1011
+ const isLiteral = /^\d{3}$/u.test(response.key);
1012
+ const key = JSON.stringify(response.key);
1013
+ const render = (example) => {
1014
+ const payload = responsePayload(response, example, schemas, fakerOptions, allRefs);
1015
+ return isLiteral ? makeHandlerBody(Number(response.key), response, payload) : makeRawHandlerBody(`Number(prefer.code ?? ${statusCodeToNumber(response.key)})`, response, payload);
1016
+ };
1017
+ const named = response.namedExamples.filter(([, value]) => value !== response.example).map(([name, value]) => `if(prefer.key===${key}&&prefer.example===${JSON.stringify(name)}){${render(value)}}`);
1018
+ return isLiteral && response.key === successKey ? named : [...named, `if(prefer.key===${key}){${render(response.example)}}`];
1019
+ }).join("");
1020
+ const preferCall = `resolvePrefer(c.req,${preferTable},${JSON.stringify(successKey)})`;
797
1021
  const authCheck = makeAuthCheck(security, operation.responses?.[String(401)] !== void 0);
798
1022
  const pathParams = (operation.parameters ?? []).flatMap((rawParam) => {
799
1023
  const resolved = rawParam.$ref ? openapi.components?.parameters?.[rawParam.$ref.replace("#/components/parameters/", "")] ?? rawParam : rawParam;
@@ -803,22 +1027,12 @@ function makeMock(openapi, basePath, options = {}) {
803
1027
  schema: resolved.schema ?? { type: "string" }
804
1028
  }];
805
1029
  });
806
- const notFoundResponse = operation.responses?.[String(404)] !== void 0 ? resolveResponse(operation.responses[String(404)], componentResponses) : void 0;
1030
+ const notFoundResponse = responses.find((r) => r.key === "404");
807
1031
  const notFoundCheck = notFoundResponse !== void 0 && pathParams.length > 0 ? (() => {
808
- const condition = pathParams.map((p) => `c.req.param('${p.name}') === '${getNonExistentValue(p.schema, schemas)}'`).join(" || ");
809
- const notFoundJsonMedia = notFoundResponse.content?.["application/json"];
810
- return `if(${condition}){${makeHandlerBody({
811
- statusCode: 404,
812
- jsonSchema: notFoundJsonMedia && isMediaWithSchema(notFoundJsonMedia) ? notFoundJsonMedia.schema : void 0,
813
- textSchema: void 0,
814
- schemas,
815
- fakerOptions,
816
- allRefs,
817
- exampleValue: void 0,
818
- exampleCast: void 0
819
- })}}`;
1032
+ return `if(prefer.key===undefined&&(${pathParams.map((p) => `c.req.param(${makeStringLiteral(p.name)}) === '${getNonExistentValue(p.schema, schemas)}'`).join(" || ")})){${makeHandlerBody(404, notFoundResponse, responsePayload(notFoundResponse, void 0, schemas, fakerOptions, allRefs))}}`;
820
1033
  })() : "";
821
- const handler = `const ${routeId}RouteHandler: RouteHandler<typeof ${routeId}Route> = async (${handlerBody.includes("c.") || authCheck !== "" || notFoundCheck !== "" ? "c" : "_c"}) => {${authCheck}${notFoundCheck}${handlerBody}}`;
1034
+ const usesFaker = /\bfaker\.|\bmock[A-Za-z0-9_$]*\(/u.test(`${preferBranches}${notFoundCheck}${handlerBody}`);
1035
+ const handler = `const ${routeId}RouteHandler: RouteHandler<typeof ${routeId}Route> = async (c) => {${seed !== void 0 && usesFaker ? `faker.seed(${JSON.stringify(seed)});faker.setDefaultRefDate('${SEED_REF_DATE}');` : ""}${authCheck}${preferBranches === "" && notFoundCheck === "" ? `${preferCall};` : `const prefer=${preferCall};${preferBranches}`}${notFoundCheck}${handlerBody}}`;
822
1036
  return [{
823
1037
  entry: {
824
1038
  routeId,
@@ -875,21 +1089,25 @@ function makeMock(openapi, basePath, options = {}) {
875
1089
  const mockFunctionsJoined = mockFunctions.join("\n\n");
876
1090
  const bigIntSerializer = `${mockFunctionsJoined}\n${handlersJoined}`.includes("faker.number.bigInt(") ? `if(!('toJSON'in BigInt.prototype)){Object.defineProperty(BigInt.prototype,'toJSON',{value(this:bigint){return this.toString()},writable:true,configurable:true})}` : "";
877
1091
  const needsCookieImport = handlersJoined.includes("getCookie(c,");
1092
+ const fakerImport = locale ? `import { faker } from '@faker-js/faker/locale/${locale}'` : `import { faker } from '@faker-js/faker'`;
1093
+ const usesPrefer = handlers.length > 0;
878
1094
  const imports = `import { OpenAPIHono, createRoute, z, type RouteHandler } from '@hono/zod-openapi'
879
- ${locale ? `import { faker } from '@faker-js/faker/locale/${locale}'` : `import { faker } from '@faker-js/faker'`}${needsCookieImport ? `\nimport { getCookie } from 'hono/cookie'` : ""}`;
1095
+ ${fakerImport}${needsCookieImport ? `\nimport { getCookie } from 'hono/cookie'` : ""}${usesPrefer ? `\nimport { HTTPException } from 'hono/http-exception'\nimport type { ContentfulStatusCode } from 'hono/utils/http-status'` : ""}`;
880
1096
  const delayMiddleware = delayMiddlewareCode(delay);
1097
+ const appCode = `const app = new OpenAPIHono()${basePath !== "/" ? `.basePath('${basePath}')` : ""}${delayMiddleware}
1098
+
1099
+ export const api = app${appSetup}
1100
+
1101
+ export default app`;
881
1102
  return [
882
1103
  imports,
883
1104
  bigIntSerializer,
884
1105
  components,
885
1106
  routes,
886
1107
  mockFunctionsJoined,
1108
+ usesPrefer ? PREFER_HELPERS : "",
887
1109
  handlersJoined,
888
- `const app = new OpenAPIHono()${basePath !== "/" ? `.basePath('${basePath}')` : ""}${delayMiddleware}
889
-
890
- export const api = app${appSetup}
891
-
892
- export default app`
1110
+ appCode
893
1111
  ].filter((s) => s.length > 0).join("\n\n");
894
1112
  }
895
1113
  //#endregion
@@ -1157,7 +1375,7 @@ function makeMockFunctions(spec, usedSchemaNames, circularSchemas) {
1157
1375
  const circular = circularSchemas ?? detectCircularSchemas(schemas);
1158
1376
  return topologicalOrder(usedSchemaNames, schemas).map((name) => {
1159
1377
  const returnType = circular.has(name) ? ": any" : "";
1160
- return `function mock${name.replaceAll(".", "")}()${returnType} {\n return ${schemaToFaker(schemas[name])}\n}`;
1378
+ return `function ${mockFunctionName(name)}()${returnType} {\n return ${schemaToFaker(schemas[name])}\n}`;
1161
1379
  }).join("\n\n");
1162
1380
  }
1163
1381
  function makeAuthHeader(sec) {
@@ -1,5 +1,5 @@
1
1
  import { n as mkdir, o as writeFile } from "./file-CwKqigE9.js";
2
- import { D as isOAuthFlowValue, H as isResponses, K as isSecurityArray, O as isOpenAPIPaths, R as isRecord, T as isMedia, U as isSchemaArray, V as isRequestBody, W as isSchemaObject, o as escapeHtml, q as isSecurityScheme, z as isRefObject } from "./utils-BDa05U34.js";
2
+ import { B as isRefObject, E as isMedia, G as isSchemaObject, H as isRequestBody, J as isSecurityScheme, O as isOAuthFlowValue, U as isResponses, W as isSchemaArray, k as isOpenAPIPaths, o as escapeHtml, q as isSecurityArray, z as isRecord } from "./utils-DEFpxBMu.js";
3
3
  import { Effect } from "effect";
4
4
  import path from "node:path";
5
5
  import { STATUS_CODES } from "node:http";
@@ -1,4 +1,4 @@
1
- import { t as OpenAPI } from "../../../index-B2QvGO4j.js";
1
+ import { t as OpenAPI } from "../../../index-Dw-w92xu.js";
2
2
  //#region src/generator/zod-openapi-hono/openapi/index.d.ts
3
3
  declare function zodOpenAPIHono(openapi: OpenAPI, options: {
4
4
  readonly readonly?: boolean;
@@ -1,2 +1,2 @@
1
- import { t as zodOpenAPIHono } from "../../../openapi-B2CqQVWF.js";
1
+ import { t as zodOpenAPIHono } from "../../../openapi-DhxrYmuQ.js";
2
2
  export { zodOpenAPIHono };
@@ -1,6 +1,6 @@
1
- import { A as isOperationLike, O as isOpenAPIPaths, R as isRecord, d as methodPath, g as toIdentifierPascalCase, n as capitalize } from "./utils-BDa05U34.js";
1
+ import { _ as toIdentifierPascalCase, f as methodPath, j as isOperationLike, k as isOpenAPIPaths, n as capitalize, z as isRecord } from "./utils-DEFpxBMu.js";
2
2
  import { t as emit } from "./emit-B_3fXoto.js";
3
- import { a as parsePathItem, i as operationHasArgs, n as hasNoContentResponse, o as resolveSplitOutDir, r as makeOperationDeps, s as GenerateError, t as formatPath } from "./rpc-B95CYct5.js";
3
+ import { a as parsePathItem, i as operationHasArgs, n as hasNoContentResponse, o as resolveSplitOutDir, r as makeOperationDeps, s as GenerateError, t as formatPath } from "./rpc-D_eeOVGa.js";
4
4
  import { Effect } from "effect";
5
5
  import path from "node:path";
6
6
  //#region src/helper/query.ts
@@ -268,7 +268,8 @@ type Schema$1 = {
268
268
  };
269
269
  readonly externalDocs?: ExternalDocs;
270
270
  readonly example?: unknown;
271
- readonly examples?: {
271
+ /** An array of values in OpenAPI 3.1 / JSON Schema 2020-12; the keyed map is the 3.0 shape. */
272
+ readonly examples?: readonly unknown[] | {
272
273
  readonly [k: string]: {
273
274
  readonly summary?: string;
274
275
  readonly description?: string;
package/dist/index.d.ts CHANGED
@@ -307,7 +307,8 @@ declare const ConfigSchema: Schema.Struct<{
307
307
  }>>;
308
308
  readonly mock: Schema.optionalKey<Schema.Struct<{
309
309
  readonly output: Schema.decodeTo<Schema.String, Schema.String, never, never>;
310
- readonly useExamples: Schema.optionalKey<Schema.Boolean>;
310
+ readonly useExamples: Schema.optionalKey<Schema.Union<readonly [Schema.Boolean, Schema.Literal<"all">]>>;
311
+ readonly seed: Schema.optionalKey<Schema.Union<readonly [Schema.Number, Schema.NonEmptyArray<Schema.Number>]>>;
311
312
  readonly locale: Schema.optionalKey<Schema.String>;
312
313
  readonly delay: Schema.optionalKey<Schema.Union<readonly [Schema.Number, Schema.Literal<false>, Schema.Struct<{
313
314
  readonly min: Schema.Number;
@@ -617,7 +618,8 @@ declare function parseConfig(config: unknown): Effect.Effect<{
617
618
  };
618
619
  readonly mock?: {
619
620
  readonly output: string;
620
- readonly useExamples?: boolean;
621
+ readonly useExamples?: "all" | boolean;
622
+ readonly seed?: number | readonly [number, ...number[]];
621
623
  readonly locale?: string;
622
624
  readonly delay?: number | false | {
623
625
  readonly min: number;
@@ -909,7 +911,8 @@ declare function readConfig(configPath?: string, reload?: boolean): Effect.Effec
909
911
  };
910
912
  readonly mock?: {
911
913
  readonly output: string;
912
- readonly useExamples?: boolean;
914
+ readonly useExamples?: "all" | boolean;
915
+ readonly seed?: number | readonly [number, ...number[]];
913
916
  readonly locale?: string;
914
917
  readonly delay?: number | false | {
915
918
  readonly min: number;
@@ -1194,7 +1197,8 @@ declare function defineConfig(config: typeof ConfigSchema.Encoded): {
1194
1197
  };
1195
1198
  readonly mock?: {
1196
1199
  readonly output: string;
1197
- readonly useExamples?: boolean;
1200
+ readonly useExamples?: "all" | boolean;
1201
+ readonly seed?: number | readonly [number, ...number[]];
1198
1202
  readonly locale?: string;
1199
1203
  readonly delay?: number | false | {
1200
1204
  readonly min: number;
package/dist/index.js CHANGED
@@ -163,6 +163,8 @@ const HOOK_KINDS = [
163
163
  ];
164
164
  /** Milliseconds, bounded so a mock cannot be configured to hang a request. */
165
165
  const DelayMsSchema = Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(6e4));
166
+ /** A faker seed: faker hashes it with Mersenne Twister, which takes a 32-bit unsigned integer. */
167
+ const SeedSchema = Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(4294967295));
166
168
  const ArrayLengthSchema = Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(1e3));
167
169
  const ConfigSchema = Schema.Struct({
168
170
  input: Schema.declare(Schema.is(Schema.TemplateLiteral([Schema.String, Schema.Literals([
@@ -419,7 +421,23 @@ const ConfigSchema = Schema.Struct({
419
421
  })),
420
422
  mock: Schema.optionalKey(Schema.Struct({
421
423
  output: FileOutputSchema,
422
- useExamples: Schema.optionalKey(Schema.Boolean.annotate({ description: "Prefer the `example` / `examples` declared in the document over faker-generated values." })),
424
+ useExamples: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Literal("all")]).annotate({
425
+ description: "Prefer the `example` / `examples` declared in the document over faker-generated values. `true` (default) uses a response's media-level example; `'all'` also uses the scalar example of every schema and property; `false` always generates.",
426
+ examples: [
427
+ true,
428
+ "all",
429
+ false
430
+ ]
431
+ })),
432
+ seed: Schema.optionalKey(Schema.Union([SeedSchema, Schema.NonEmptyArray(SeedSchema)]).annotate({
433
+ title: "Faker seed",
434
+ description: "Seeds faker at the start of every handler, so each route answers the same body on every request — stable enough for snapshot tests. Dates are generated relative to a fixed 2025-01-01T00:00:00Z, and the locale-specific faker instance is the one seeded.",
435
+ examples: [42, [
436
+ 1,
437
+ 2,
438
+ 3
439
+ ]]
440
+ })),
423
441
  locale: Schema.optionalKey(Schema.String.check(Schema.isPattern(/^[A-Za-z_]{1,40}$/u, { message: "Invalid faker locale. Use a code like 'ja', 'en', or 'zh_CN'." })).annotate({
424
442
  title: "Faker locale",
425
443
  description: "faker.js locale used for the generated values.",
@@ -463,6 +481,7 @@ const ConfigSchema = Schema.Struct({
463
481
  output: "./src/mock.ts",
464
482
  useExamples: true,
465
483
  locale: "ja",
484
+ seed: 42,
466
485
  delay: {
467
486
  min: 100,
468
487
  max: 800
@@ -1,4 +1,4 @@
1
- import { B as isRefOnly, C as isHeader, F as isPathItem, H as isResponses, I as isPathItemEntry, J as isSingleSchema, L as isPathItemRef, P as isParameterRef, R as isRecord, S as isDiscriminableBranch, T as isMedia, U as isSchemaArray, W as isSchemaObject, _ as uncapitalize, a as error, b as isCallbacks, d as methodPath, f as normalizeTypes, g as toIdentifierPascalCase, i as ensureSuffix, j as isParameter, k as isOperation, m as requestParamsArray, p as renderNamedImport, r as cyclicNodes, s as escapeRegexLiteral, t as baseError, u as makeSafeKey, y as zodToOpenAPISchema, z as isRefObject } from "./utils-BDa05U34.js";
1
+ import { A as isOperation, B as isRefObject, C as isDiscriminableBranch, E as isMedia, F as isParameterRef, G as isSchemaObject, I as isPathItem, L as isPathItemEntry, M as isParameter, R as isPathItemRef, U as isResponses, V as isRefOnly, W as isSchemaArray, Y as isSingleSchema, _ as toIdentifierPascalCase, a as error, b as zodToOpenAPISchema, f as methodPath, h as requestParamsArray, i as ensureSuffix, m as renderNamedImport, p as normalizeTypes, r as cyclicNodes, s as escapeRegexLiteral, t as baseError, u as makeSafeKey, v as uncapitalize, w as isHeader, x as isCallbacks, z as isRecord } from "./utils-DEFpxBMu.js";
2
2
  import path from "node:path";
3
3
  import { ts } from "ts-morph";
4
4
  //#region src/helper/code.ts
@@ -1248,7 +1248,7 @@ function makeFormatOptions(schema) {
1248
1248
  case "email": {
1249
1249
  const regex = schema["x-emailRegex"];
1250
1250
  const preset = schema["x-emailPattern"];
1251
- return [regex ? `pattern:/${escapeRegexLiteral(regex)}/` : preset && EMAIL_PATTERN_PRESET[preset] ? `pattern:z.regexes.${EMAIL_PATTERN_PRESET[preset]}` : void 0].filter((v) => v !== void 0);
1251
+ return [regex ? `pattern:/${escapeRegexLiteral(regex)}/` : preset && Object.hasOwn(EMAIL_PATTERN_PRESET, preset) ? `pattern:z.regexes.${EMAIL_PATTERN_PRESET[preset]}` : void 0].filter((v) => v !== void 0);
1252
1252
  }
1253
1253
  case "uuid": return schema["x-uuidVersion"] ? [`version:${JSON.stringify(schema["x-uuidVersion"])}`] : [];
1254
1254
  case "url":
@@ -1300,7 +1300,7 @@ function string(schema, options) {
1300
1300
  if (isJson) return `.transform((val,ctx)=>{try{const s=typeof atob==="function"?atob(val):Buffer.from(val,"base64").toString("utf8");return JSON.parse(s)}catch(e){ctx.addIssue(${errorMessage ? `{code:"custom",message:${JSON.stringify(errorMessage)},params:{cause:e instanceof Error?e.message:String(e)}}` : "{code:\"custom\",params:{cause:e instanceof Error?e.message:String(e)}}"});return z.NEVER}})`;
1301
1301
  return ".transform((val)=>typeof atob===\"function\"?atob(val):Buffer.from(val,\"base64\").toString(\"utf8\"))";
1302
1302
  })()}${contentSchema ? `.pipe(${zodToOpenAPI(contentSchema, void 0, options)})` : ""}`;
1303
- const format = schema.format && FORMAT_STRING[schema.format];
1303
+ const format = schema.format && Object.hasOwn(FORMAT_STRING, schema.format) ? FORMAT_STRING[schema.format] : void 0;
1304
1304
  const isTransformFormat = !!(schema.format && TRANSFORM_FORMATS.has(schema.format));
1305
1305
  const isValidationFormat = !!(format && !isTransformFormat);
1306
1306
  const trimX = schema["x-trim"] === true;
@@ -1,4 +1,4 @@
1
- import { A as isOperationLike, G as isSchemaProperty, N as isParameterObject, R as isRecord, X as isValidIdent, z as isRefObject } from "./utils-BDa05U34.js";
1
+ import { B as isRefObject, K as isSchemaProperty, P as isParameterObject, Z as isValidIdent, j as isOperationLike, z as isRecord } from "./utils-DEFpxBMu.js";
2
2
  import { Data } from "effect";
3
3
  import path from "node:path";
4
4
  //#region src/error/index.ts
@@ -1,9 +1,9 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
2
2
  import { a as unlink, i as readdir } from "./file-CwKqigE9.js";
3
- import { s as GenerateError } from "./rpc-B95CYct5.js";
4
- import { _ as links, a as defineTemplate, b as callbacks, c as mock, d as responses, f as requestBodies, g as mediaTypes, h as components, i as template, l as securitySchemes, m as parameters, n as webhooks, o as takibi, p as pathItems, r as test, s as route, u as schemas, v as headers, y as examples } from "./core-BdG_5KX8.js";
5
- import { t as hooks } from "./hooks-iffNFEYy.js";
6
- import { t as docs } from "./docs-MzhmjfNS.js";
3
+ import { s as GenerateError } from "./rpc-D_eeOVGa.js";
4
+ import { _ as links, a as defineTemplate, b as callbacks, c as mock, d as responses, f as requestBodies, g as mediaTypes, h as components, i as template, l as securitySchemes, m as parameters, n as webhooks, o as takibi, p as pathItems, r as test, s as route, u as schemas, v as headers, y as examples } from "./core-CpzC5kSm.js";
5
+ import { t as hooks } from "./hooks-6j2Z-MPl.js";
6
+ import { t as docs } from "./docs-C1_fNNJ-.js";
7
7
  import { rpc } from "./core/rpc/index.js";
8
8
  import { type } from "./core/type/index.js";
9
9
  import { Effect, Schema } from "effect";
@@ -178,9 +178,33 @@ function requestParamsArray(parameters) {
178
178
  */
179
179
  function makeSafeKey(key) {
180
180
  if (/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(key)) return key;
181
- return `'${key.replaceAll("\\", "\\\\").replaceAll("'", "\\'").replaceAll("\n", "\\n").replaceAll("\r", "\\r").replaceAll(" ", "\\t")}'`;
181
+ return makeStringLiteral(key);
182
182
  }
183
183
  /**
184
+ * Converts a string to a single-quoted TypeScript string literal.
185
+ *
186
+ * Use it for every document-supplied value spliced into generated code as a
187
+ * string (header, query, cookie and path parameter names, …): a raw `'` or
188
+ * line break would otherwise end the literal and let the rest run as code.
189
+ *
190
+ *
191
+ * @example
192
+ * ```ts
193
+ * makeStringLiteral('X-API-Key') // → "'X-API-Key'"
194
+ * makeStringLiteral("it's") // → "'it\\'s'"
195
+ * makeStringLiteral('a\nb') // → "'a\\nb'"
196
+ * ```
197
+ */
198
+ function makeStringLiteral(value) {
199
+ return `'${value.replaceAll("\\", "\\\\").replaceAll("'", "\\'").replaceAll("\n", "\\n").replaceAll("\r", "\\r").replaceAll(" ", "\\t")}'`;
200
+ }
201
+ const REGEX_LINE_TERMINATOR_ESCAPES = {
202
+ "\n": "\\n",
203
+ "\r": "\\r",
204
+ "\u2028": "\\u2028",
205
+ "\u2029": "\\u2029"
206
+ };
207
+ /**
184
208
  * Escapes unescaped forward slashes in a string that will be embedded inside a
185
209
  * regular-expression literal (`/.../`).
186
210
  *
@@ -189,16 +213,27 @@ function makeSafeKey(key) {
189
213
  * generated literal — an unescaped `/` would close it and let arbitrary code
190
214
  * follow. Slashes already escaped (`\/`) are left untouched.
191
215
  *
216
+ * The source is scanned as escape pairs, so a slash after an escaped backslash
217
+ * (`\\/`) is still recognised as unescaped. Line terminators, which a regex
218
+ * literal cannot contain, become their escape sequences (same meaning), and a
219
+ * trailing lone backslash — which would escape the closing `/` — is doubled.
220
+ *
192
221
  *
193
222
  * @example
194
223
  * ```ts
195
224
  * escapeRegexLiteral('^https?$') // → '^https?$'
196
225
  * escapeRegexLiteral('a/b') // → 'a\\/b'
197
226
  * escapeRegexLiteral('a\\/b') // → 'a\\/b'
227
+ * escapeRegexLiteral('a\\\\/b') // → 'a\\\\\\/b'
228
+ * escapeRegexLiteral('a\nb') // → 'a\\nb'
198
229
  * ```
199
230
  */
200
231
  function escapeRegexLiteral(source) {
201
- return source.replaceAll(/(?<!\\)\//gu, "\\/");
232
+ return source.replaceAll(/\\([\s\S]?)|[/\n\r\u2028\u2029]/gu, (match, escaped) => {
233
+ if (escaped === void 0) return match === "/" ? "\\/" : REGEX_LINE_TERMINATOR_ESCAPES[match] ?? match;
234
+ if (escaped === "") return "\\\\";
235
+ return REGEX_LINE_TERMINATOR_ESCAPES[escaped] ?? match;
236
+ });
202
237
  }
203
238
  /**
204
239
  * Escapes the HTML special characters in a string that will be embedded as
@@ -433,4 +468,4 @@ function cyclicNodes(deps) {
433
468
  return result;
434
469
  }
435
470
  //#endregion
436
- export { isOperationLike as A, isRefOnly as B, isHeader as C, isOAuthFlowValue as D, isMediaWithSchema as E, isPathItem as F, isSchemaProperty as G, isResponses as H, isPathItemEntry as I, isSingleSchema as J, isSecurityArray as K, isPathItemRef as L, isParameterArray as M, isParameterObject as N, isOpenAPIPaths as O, isParameterRef as P, isRecord as R, isDiscriminableBranch as S, isMedia as T, isSchemaArray as U, isRequestBody as V, isSchemaObject as W, isValidIdent as X, isStringRef as Y, uncapitalize as _, error as a, isCallbacks as b, makeBarrel as c, methodPath as d, normalizeTypes as f, toIdentifierPascalCase as g, statusCodeToNumber as h, ensureSuffix as i, isParameter as j, isOperation as k, makeInferRequestType as l, requestParamsArray as m, capitalize as n, escapeHtml as o, renderNamedImport as p, isSecurityScheme as q, cyclicNodes as r, escapeRegexLiteral as s, baseError as t, makeSafeKey as u, uncapitalizeWord as v, isHttpMethod as w, isContentBody as x, zodToOpenAPISchema as y, isRefObject as z };
471
+ export { isOperation as A, isRefObject as B, isDiscriminableBranch as C, isMediaWithSchema as D, isMedia as E, isParameterRef as F, isSchemaObject as G, isRequestBody as H, isPathItem as I, isSecurityScheme as J, isSchemaProperty as K, isPathItemEntry as L, isParameter as M, isParameterArray as N, isOAuthFlowValue as O, isParameterObject as P, isPathItemRef as R, isContentBody as S, isHttpMethod as T, isResponses as U, isRefOnly as V, isSchemaArray as W, isStringRef as X, isSingleSchema as Y, isValidIdent as Z, toIdentifierPascalCase as _, error as a, zodToOpenAPISchema as b, makeBarrel as c, makeStringLiteral as d, methodPath as f, statusCodeToNumber as g, requestParamsArray as h, ensureSuffix as i, isOperationLike as j, isOpenAPIPaths as k, makeInferRequestType as l, renderNamedImport as m, capitalize as n, escapeHtml as o, normalizeTypes as p, isSecurityArray as q, cyclicNodes as r, escapeRegexLiteral as s, baseError as t, makeSafeKey as u, uncapitalize as v, isHeader as w, isCallbacks as x, uncapitalizeWord as y, isRecord as z };
@@ -1,9 +1,9 @@
1
1
  import { parseConfig } from "../index.js";
2
2
  import { t as fileSystemLayer } from "../file-CwKqigE9.js";
3
3
  import { t as FormatOptions } from "../format-Bm9LZ_ki.js";
4
- import { R as isRecord } from "../utils-BDa05U34.js";
4
+ import { z as isRecord } from "../utils-DEFpxBMu.js";
5
5
  import { n as parseOpenAPI } from "../openapi-CzAVsFDt.js";
6
- import { n as cleanSplitOutputs, r as makeJob, t as appEntryOutput } from "../shared-Ck7P2pO5.js";
6
+ import { n as cleanSplitOutputs, r as makeJob, t as appEntryOutput } from "../shared-BJ4A07Yx.js";
7
7
  import { Effect, FileSystem, Option, Result } from "effect";
8
8
  import path from "node:path";
9
9
  import crypto from "node:crypto";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hono-takibi",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "description": "Hono Takibi is a code generator from OpenAPI to @hono/zod-openapi",
5
5
  "keywords": [
6
6
  "hono",