@kubb/plugin-msw 5.0.0-beta.3 → 5.0.0-beta.30
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 +26 -5
- package/dist/{components-vO0FIb2i.js → components--7xwlHZU.js} +52 -59
- package/dist/components--7xwlHZU.js.map +1 -0
- package/dist/{components-CLQ77DVn.cjs → components-CHyTtokd.cjs} +55 -68
- package/dist/components-CHyTtokd.cjs.map +1 -0
- package/dist/components.cjs +1 -1
- package/dist/components.d.ts +5 -5
- package/dist/components.js +1 -1
- package/dist/{generators-BPJCs1x1.js → generators-BcGCyGBt.js} +61 -32
- package/dist/generators-BcGCyGBt.js.map +1 -0
- package/dist/{generators-CrmMwWE4.cjs → generators-DzDKzDFe.cjs} +60 -31
- package/dist/generators-DzDKzDFe.cjs.map +1 -0
- package/dist/generators.cjs +1 -1
- package/dist/generators.d.ts +13 -1
- package/dist/generators.js +1 -1
- package/dist/index.cjs +54 -9
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +31 -1
- package/dist/index.js +54 -9
- package/dist/index.js.map +1 -1
- package/dist/types-CLAiv8qc.d.ts +103 -0
- package/extension.yaml +680 -0
- package/package.json +11 -14
- package/src/components/Handlers.tsx +1 -1
- package/src/components/Mock.tsx +5 -4
- package/src/components/MockWithFaker.tsx +5 -4
- package/src/components/Response.tsx +1 -1
- package/src/generators/handlersGenerator.tsx +18 -12
- package/src/generators/mswGenerator.tsx +27 -17
- package/src/plugin.ts +32 -4
- package/src/resolvers/resolverMsw.ts +19 -3
- package/src/types.ts +35 -21
- package/src/utils.ts +16 -60
- package/dist/components-CLQ77DVn.cjs.map +0 -1
- package/dist/components-vO0FIb2i.js.map +0 -1
- package/dist/generators-BPJCs1x1.js.map +0 -1
- package/dist/generators-CrmMwWE4.cjs.map +0 -1
- package/dist/types-Dxu0KMQ4.d.ts +0 -89
package/README.md
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
<div align="center">
|
|
2
|
-
<h1
|
|
2
|
+
<h1>@kubb/plugin-msw</h1>
|
|
3
3
|
<a href="https://kubb.dev" target="_blank" rel="noopener noreferrer">
|
|
4
4
|
<img width="180" src="https://raw.githubusercontent.com/kubb-labs/kubb/main/assets/logo.png" alt="Kubb logo">
|
|
5
5
|
</a>
|
|
@@ -11,9 +11,9 @@
|
|
|
11
11
|
[![Sponsors][sponsors-src]][sponsors-href]
|
|
12
12
|
|
|
13
13
|
<h4>
|
|
14
|
-
<a href="https://codesandbox.io/s/github/kubb-labs/
|
|
14
|
+
<a href="https://codesandbox.io/s/github/kubb-labs/plugins/tree/main/examples/msw" target="_blank">View Demo</a>
|
|
15
15
|
<span> · </span>
|
|
16
|
-
<a href="https://kubb.dev/" target="_blank">Documentation</a>
|
|
16
|
+
<a href="https://kubb.dev/plugins/msw" target="_blank">Documentation</a>
|
|
17
17
|
<span> · </span>
|
|
18
18
|
<a href="https://github.com/kubb-labs/kubb/issues/" target="_blank">Report Bug</a>
|
|
19
19
|
<span> · </span>
|
|
@@ -21,11 +21,32 @@
|
|
|
21
21
|
</h4>
|
|
22
22
|
</div>
|
|
23
23
|
|
|
24
|
-
|
|
24
|
+
`@kubb/plugin-msw` generates Mock Service Worker (MSW) request handlers from your OpenAPI specification. The handlers work in both browser and Node.js environments via MSW v2.
|
|
25
|
+
|
|
26
|
+
## Features
|
|
27
|
+
|
|
28
|
+
- Generates one handler per OpenAPI operation
|
|
29
|
+
- Infers request and response types from the spec
|
|
30
|
+
- Works in both browser (via service worker) and Node.js test environments
|
|
31
|
+
- Works with `@kubb/plugin-faker` to serve realistic response data
|
|
32
|
+
|
|
33
|
+
## Installation
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
bun add @kubb/plugin-msw
|
|
37
|
+
# or
|
|
38
|
+
pnpm add @kubb/plugin-msw
|
|
39
|
+
# or
|
|
40
|
+
npm install @kubb/plugin-msw
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## Documentation
|
|
44
|
+
|
|
45
|
+
See the [full documentation](https://kubb.dev/plugins/msw) for configuration options and examples.
|
|
25
46
|
|
|
26
47
|
## Supporting Kubb
|
|
27
48
|
|
|
28
|
-
Kubb
|
|
49
|
+
Kubb is an MIT-licensed open source project with its ongoing development made possible entirely by the support of Sponsors. If you would like to become a sponsor, please consider:
|
|
29
50
|
|
|
30
51
|
- [Become a Sponsor on GitHub](https://github.com/sponsors/stijnvanhulle)
|
|
31
52
|
|
|
@@ -214,16 +214,16 @@ var URLPath = class {
|
|
|
214
214
|
get object() {
|
|
215
215
|
return this.toObject();
|
|
216
216
|
}
|
|
217
|
-
/** Returns a map of path parameter names, or `
|
|
217
|
+
/** Returns a map of path parameter names, or `null` when the path has no parameters.
|
|
218
218
|
*
|
|
219
219
|
* @example
|
|
220
220
|
* ```ts
|
|
221
221
|
* new URLPath('/pet/{petId}').params // { petId: 'petId' }
|
|
222
|
-
* new URLPath('/pet').params //
|
|
222
|
+
* new URLPath('/pet').params // null
|
|
223
223
|
* ```
|
|
224
224
|
*/
|
|
225
225
|
get params() {
|
|
226
|
-
return this.
|
|
226
|
+
return this.toParamsObject();
|
|
227
227
|
}
|
|
228
228
|
#transformParam(raw) {
|
|
229
229
|
const param = isValidVarName(raw) ? raw : camelCase(raw);
|
|
@@ -241,7 +241,7 @@ var URLPath = class {
|
|
|
241
241
|
toObject({ type = "path", replacer, stringify } = {}) {
|
|
242
242
|
const object = {
|
|
243
243
|
url: type === "path" ? this.toURLPath() : this.toTemplateString({ replacer }),
|
|
244
|
-
params: this.
|
|
244
|
+
params: this.toParamsObject()
|
|
245
245
|
};
|
|
246
246
|
if (stringify) {
|
|
247
247
|
if (type === "template") return JSON.stringify(object).replaceAll("'", "").replaceAll(`"`, "");
|
|
@@ -257,12 +257,13 @@ var URLPath = class {
|
|
|
257
257
|
* @example
|
|
258
258
|
* new URLPath('/pet/{petId}').toTemplateString() // '`/pet/${petId}`'
|
|
259
259
|
*/
|
|
260
|
-
toTemplateString({ prefix
|
|
261
|
-
|
|
260
|
+
toTemplateString({ prefix, replacer } = {}) {
|
|
261
|
+
const result = this.path.split(/\{([^}]+)\}/).map((part, i) => {
|
|
262
262
|
if (i % 2 === 0) return part;
|
|
263
263
|
const param = this.#transformParam(part);
|
|
264
264
|
return `\${${replacer ? replacer(param) : param}}`;
|
|
265
|
-
}).join("")
|
|
265
|
+
}).join("");
|
|
266
|
+
return `\`${prefix ?? ""}${result}\``;
|
|
266
267
|
}
|
|
267
268
|
/**
|
|
268
269
|
* Extracts all `{param}` segments from the path and returns them as a key-value map.
|
|
@@ -271,17 +272,17 @@ var URLPath = class {
|
|
|
271
272
|
*
|
|
272
273
|
* @example
|
|
273
274
|
* ```ts
|
|
274
|
-
* new URLPath('/pet/{petId}/tag/{tagId}').
|
|
275
|
+
* new URLPath('/pet/{petId}/tag/{tagId}').toParamsObject()
|
|
275
276
|
* // { petId: 'petId', tagId: 'tagId' }
|
|
276
277
|
* ```
|
|
277
278
|
*/
|
|
278
|
-
|
|
279
|
+
toParamsObject(replacer) {
|
|
279
280
|
const params = {};
|
|
280
281
|
this.#eachParam((_raw, param) => {
|
|
281
282
|
const key = replacer ? replacer(param) : param;
|
|
282
283
|
params[key] = key;
|
|
283
284
|
});
|
|
284
|
-
return Object.keys(params).length > 0 ? params :
|
|
285
|
+
return Object.keys(params).length > 0 ? params : null;
|
|
285
286
|
}
|
|
286
287
|
/** Converts the OpenAPI path to Express-style colon syntax.
|
|
287
288
|
*
|
|
@@ -305,64 +306,56 @@ function Handlers({ name, handlers }) {
|
|
|
305
306
|
});
|
|
306
307
|
}
|
|
307
308
|
//#endregion
|
|
308
|
-
//#region src/
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
function transformName(name, type, transformers) {
|
|
313
|
-
return transformers?.name?.(name, type) || name;
|
|
309
|
+
//#region ../../internals/shared/src/operation.ts
|
|
310
|
+
function getStatusCodeNumber(statusCode) {
|
|
311
|
+
const code = Number(statusCode);
|
|
312
|
+
return Number.isNaN(code) ? null : code;
|
|
314
313
|
}
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
314
|
+
function isSuccessStatusCode(statusCode) {
|
|
315
|
+
const code = getStatusCodeNumber(statusCode);
|
|
316
|
+
return code !== null && code >= 200 && code < 300;
|
|
317
|
+
}
|
|
318
|
+
function getSuccessResponses(responses) {
|
|
319
|
+
return responses.filter((response) => isSuccessStatusCode(response.statusCode));
|
|
320
|
+
}
|
|
321
|
+
function getOperationSuccessResponses(node) {
|
|
322
|
+
return getSuccessResponses(node.responses);
|
|
323
323
|
}
|
|
324
|
-
/**
|
|
325
|
-
* Returns the first 2xx response for an operation, if any.
|
|
326
|
-
*/
|
|
327
324
|
function getPrimarySuccessResponse(node) {
|
|
328
|
-
return
|
|
325
|
+
return getOperationSuccessResponses(node)[0] ?? null;
|
|
326
|
+
}
|
|
327
|
+
function resolveResponseTypes(node, resolver) {
|
|
328
|
+
const types = [];
|
|
329
|
+
for (const response of node.responses) {
|
|
330
|
+
if (response.statusCode === "default") {
|
|
331
|
+
types.push(["default", resolver.resolveResponseName(node)]);
|
|
332
|
+
continue;
|
|
333
|
+
}
|
|
334
|
+
const code = getStatusCodeNumber(response.statusCode);
|
|
335
|
+
if (code === null) continue;
|
|
336
|
+
types.push([code, isSuccessStatusCode(code) ? resolver.resolveResponseName(node) : resolver.resolveResponseStatusName(node, response.statusCode)]);
|
|
337
|
+
}
|
|
338
|
+
return types;
|
|
329
339
|
}
|
|
340
|
+
//#endregion
|
|
341
|
+
//#region src/utils.ts
|
|
330
342
|
/**
|
|
331
343
|
* Gets the content type from a response, defaulting to 'application/json' if a schema exists.
|
|
332
344
|
*/
|
|
333
345
|
function getContentType(response) {
|
|
334
|
-
|
|
346
|
+
if (!hasResponseSchema(response)) return null;
|
|
347
|
+
return getResponseContentType(response) ?? "application/json";
|
|
335
348
|
}
|
|
336
349
|
/**
|
|
337
350
|
* Determines if a response has a schema that is not void or any.
|
|
338
351
|
*/
|
|
339
352
|
function hasResponseSchema(response) {
|
|
340
|
-
|
|
353
|
+
const schema = response?.content?.[0]?.schema;
|
|
354
|
+
return !!schema && schema.type !== "void" && schema.type !== "any";
|
|
341
355
|
}
|
|
342
356
|
function getResponseContentType(response) {
|
|
343
|
-
const
|
|
344
|
-
|
|
345
|
-
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
346
|
-
}
|
|
347
|
-
/**
|
|
348
|
-
* Maps all operation responses to their type names, including status code or 'default' for default responses.
|
|
349
|
-
*/
|
|
350
|
-
function getResponseTypes(node, tsResolver) {
|
|
351
|
-
const types = [];
|
|
352
|
-
for (const response of node.responses) {
|
|
353
|
-
if (response.statusCode === "default") {
|
|
354
|
-
types.push(["default", tsResolver.resolveResponseName(node)]);
|
|
355
|
-
continue;
|
|
356
|
-
}
|
|
357
|
-
const code = Number.parseInt(response.statusCode, 10);
|
|
358
|
-
if (Number.isNaN(code)) continue;
|
|
359
|
-
if (code >= 200 && code < 300) {
|
|
360
|
-
types.push([code, tsResolver.resolveResponseName(node)]);
|
|
361
|
-
continue;
|
|
362
|
-
}
|
|
363
|
-
types.push([code, tsResolver.resolveResponseStatusName(node, response.statusCode)]);
|
|
364
|
-
}
|
|
365
|
-
return types;
|
|
357
|
+
const value = response?.content?.[0]?.contentType;
|
|
358
|
+
return typeof value === "string" && value.length > 0 ? value : null;
|
|
366
359
|
}
|
|
367
360
|
/**
|
|
368
361
|
* Converts an HTTP method to its lowercase MSW equivalent (e.g., 'POST' → 'post').
|
|
@@ -392,7 +385,7 @@ function resolveFakerMeta(node, options) {
|
|
|
392
385
|
}, {
|
|
393
386
|
root,
|
|
394
387
|
output: fakerOutput,
|
|
395
|
-
group: fakerGroup
|
|
388
|
+
group: fakerGroup ?? void 0
|
|
396
389
|
})
|
|
397
390
|
};
|
|
398
391
|
}
|
|
@@ -405,7 +398,7 @@ function Mock({ baseURL = "", name, typeName, requestTypeName, node }) {
|
|
|
405
398
|
const statusCode = successResponse ? Number(successResponse.statusCode) : 200;
|
|
406
399
|
const contentType = getContentType(successResponse);
|
|
407
400
|
const url = new URLPath(getMswUrl(node)).toURLPath();
|
|
408
|
-
const headers = [contentType ? `'Content-Type': '${contentType}'` :
|
|
401
|
+
const headers = [contentType ? `'Content-Type': '${contentType}'` : null].filter(Boolean);
|
|
409
402
|
const dataType = hasResponseSchema(successResponse) ? typeName : "string | number | boolean | null | object";
|
|
410
403
|
const callbackType = requestTypeName ? `HttpResponseResolver<Record<string, string>, ${requestTypeName}, any>` : `((info: Parameters<Parameters<typeof http.${method}>[1]>[0]) => Response | Promise<Response>)`;
|
|
411
404
|
const params = declarationPrinter$2.print(ast.createFunctionParameters({ params: [ast.createFunctionParameter({
|
|
@@ -447,7 +440,7 @@ function MockWithFaker({ baseURL = "", name, fakerName, typeName, requestTypeNam
|
|
|
447
440
|
const statusCode = successResponse ? Number(successResponse.statusCode) : 200;
|
|
448
441
|
const contentType = getContentType(successResponse);
|
|
449
442
|
const url = new URLPath(getMswUrl(node)).toURLPath();
|
|
450
|
-
const headers = [contentType ? `'Content-Type': '${contentType}'` :
|
|
443
|
+
const headers = [contentType ? `'Content-Type': '${contentType}'` : null].filter(Boolean);
|
|
451
444
|
const callbackType = requestTypeName ? `HttpResponseResolver<Record<string, string>, ${requestTypeName}, any>` : `((info: Parameters<Parameters<typeof http.${method}>[1]>[0]) => Response | Promise<Response>)`;
|
|
452
445
|
const params = declarationPrinter$1.print(ast.createFunctionParameters({ params: [ast.createFunctionParameter({
|
|
453
446
|
name: "data",
|
|
@@ -485,7 +478,7 @@ const declarationPrinter = functionPrinter({ mode: "declaration" });
|
|
|
485
478
|
function Response({ name, typeName, response }) {
|
|
486
479
|
const statusCode = Number(response.statusCode);
|
|
487
480
|
const contentType = getContentType(response);
|
|
488
|
-
const headers = [contentType ? `'Content-Type': '${contentType}'` :
|
|
481
|
+
const headers = [contentType ? `'Content-Type': '${contentType}'` : null].filter(Boolean);
|
|
489
482
|
const params = declarationPrinter.print(ast.createFunctionParameters({ params: [ast.createFunctionParameter({
|
|
490
483
|
name: "data",
|
|
491
484
|
type: ast.createParamsType({
|
|
@@ -514,6 +507,6 @@ function Response({ name, typeName, response }) {
|
|
|
514
507
|
});
|
|
515
508
|
}
|
|
516
509
|
//#endregion
|
|
517
|
-
export {
|
|
510
|
+
export { getOperationSuccessResponses as a, camelCase as c, resolveFakerMeta as i, MockWithFaker as n, resolveResponseTypes as o, Mock as r, Handlers as s, Response as t };
|
|
518
511
|
|
|
519
|
-
//# sourceMappingURL=components
|
|
512
|
+
//# sourceMappingURL=components--7xwlHZU.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"components--7xwlHZU.js","names":["#options","#transformParam","#eachParam","declarationPrinter","declarationPrinter"],"sources":["../../../internals/utils/src/casing.ts","../../../internals/utils/src/reserved.ts","../../../internals/utils/src/urlPath.ts","../src/components/Handlers.tsx","../../../internals/shared/src/operation.ts","../src/utils.ts","../src/components/Mock.tsx","../src/components/MockWithFaker.tsx","../src/components/Response.tsx"],"sourcesContent":["type Options = {\n /**\n * When `true`, dot-separated segments are split on `.` and joined with `/` after casing.\n */\n isFile?: boolean\n /**\n * Text prepended before casing is applied.\n */\n prefix?: string\n /**\n * Text appended before casing is applied.\n */\n suffix?: string\n}\n\n/**\n * Shared implementation for camelCase and PascalCase conversion.\n * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)\n * and capitalizes each word according to `pascal`.\n *\n * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.\n */\nfunction toCamelOrPascal(text: string, pascal: boolean): string {\n const normalized = text\n .trim()\n .replace(/([a-z\\d])([A-Z])/g, '$1 $2')\n .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')\n .replace(/(\\d)([a-z])/g, '$1 $2')\n\n const words = normalized.split(/[\\s\\-_./\\\\:]+/).filter(Boolean)\n\n return words\n .map((word, i) => {\n const allUpper = word.length > 1 && word === word.toUpperCase()\n if (allUpper) return word\n if (i === 0 && !pascal) return word.charAt(0).toLowerCase() + word.slice(1)\n return word.charAt(0).toUpperCase() + word.slice(1)\n })\n .join('')\n .replace(/[^a-zA-Z0-9]/g, '')\n}\n\n/**\n * Splits `text` on `.` and applies `transformPart` to each segment.\n * The last segment receives `isLast = true`, all earlier segments receive `false`.\n * Segments are joined with `/` to form a file path.\n *\n * Only splits on dots followed by a letter so that version numbers\n * embedded in operationIds (e.g. `v2025.0`) are kept intact.\n */\nfunction applyToFileParts(text: string, transformPart: (part: string, isLast: boolean) => string): string {\n const parts = text.split(/\\.(?=[a-zA-Z])/)\n return parts.map((part, i) => transformPart(part, i === parts.length - 1)).join('/')\n}\n\n/**\n * Converts `text` to camelCase.\n * When `isFile` is `true`, dot-separated segments are each cased independently and joined with `/`.\n *\n * @example\n * camelCase('hello-world') // 'helloWorld'\n * camelCase('pet.petId', { isFile: true }) // 'pet/petId'\n */\nexport function camelCase(text: string, { isFile, prefix = '', suffix = '' }: Options = {}): string {\n if (isFile) {\n return applyToFileParts(text, (part, isLast) => camelCase(part, isLast ? { prefix, suffix } : {}))\n }\n\n return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false)\n}\n\n/**\n * Converts `text` to PascalCase.\n * When `isFile` is `true`, the last dot-separated segment is PascalCased and earlier segments are camelCased.\n *\n * @example\n * pascalCase('hello-world') // 'HelloWorld'\n * pascalCase('pet.petId', { isFile: true }) // 'pet/PetId'\n */\nexport function pascalCase(text: string, { isFile, prefix = '', suffix = '' }: Options = {}): string {\n if (isFile) {\n return applyToFileParts(text, (part, isLast) => (isLast ? pascalCase(part, { prefix, suffix }) : camelCase(part)))\n }\n\n return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true)\n}\n\n/**\n * Converts `text` to snake_case.\n *\n * @example\n * snakeCase('helloWorld') // 'hello_world'\n * snakeCase('Hello-World') // 'hello_world'\n */\nexport function snakeCase(text: string, { prefix = '', suffix = '' }: Omit<Options, 'isFile'> = {}): string {\n const processed = `${prefix} ${text} ${suffix}`.trim()\n return processed\n .replace(/([a-z])([A-Z])/g, '$1_$2')\n .replace(/[\\s\\-.]+/g, '_')\n .replace(/[^a-zA-Z0-9_]/g, '')\n .toLowerCase()\n .split('_')\n .filter(Boolean)\n .join('_')\n}\n\n/**\n * Converts `text` to SCREAMING_SNAKE_CASE.\n *\n * @example\n * screamingSnakeCase('helloWorld') // 'HELLO_WORLD'\n */\nexport function screamingSnakeCase(text: string, { prefix = '', suffix = '' }: Omit<Options, 'isFile'> = {}): string {\n return snakeCase(text, { prefix, suffix }).toUpperCase()\n}\n","/**\n * JavaScript and Java reserved words.\n * @link https://github.com/jonschlinkert/reserved/blob/master/index.js\n */\nconst reservedWords = new Set([\n 'abstract',\n 'arguments',\n 'boolean',\n 'break',\n 'byte',\n 'case',\n 'catch',\n 'char',\n 'class',\n 'const',\n 'continue',\n 'debugger',\n 'default',\n 'delete',\n 'do',\n 'double',\n 'else',\n 'enum',\n 'eval',\n 'export',\n 'extends',\n 'false',\n 'final',\n 'finally',\n 'float',\n 'for',\n 'function',\n 'goto',\n 'if',\n 'implements',\n 'import',\n 'in',\n 'instanceof',\n 'int',\n 'interface',\n 'let',\n 'long',\n 'native',\n 'new',\n 'null',\n 'package',\n 'private',\n 'protected',\n 'public',\n 'return',\n 'short',\n 'static',\n 'super',\n 'switch',\n 'synchronized',\n 'this',\n 'throw',\n 'throws',\n 'transient',\n 'true',\n 'try',\n 'typeof',\n 'var',\n 'void',\n 'volatile',\n 'while',\n 'with',\n 'yield',\n 'Array',\n 'Date',\n 'hasOwnProperty',\n 'Infinity',\n 'isFinite',\n 'isNaN',\n 'isPrototypeOf',\n 'length',\n 'Math',\n 'name',\n 'NaN',\n 'Number',\n 'Object',\n 'prototype',\n 'String',\n 'toString',\n 'undefined',\n 'valueOf',\n] as const)\n\n/**\n * Returns `true` when `name` is a syntactically valid JavaScript variable name.\n *\n * @example\n * ```ts\n * isValidVarName('status') // true\n * isValidVarName('class') // false (reserved word)\n * isValidVarName('42foo') // false (starts with digit)\n * ```\n */\nexport function isValidVarName(name: string): boolean {\n if (!name || reservedWords.has(name as 'valueOf')) {\n return false\n }\n return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name)\n}\n\n/**\n * Returns `name` when it's a syntactically valid JavaScript variable name,\n * otherwise prefixes it with `_` so the result is a valid identifier.\n *\n * Useful for sanitizing OpenAPI schema names or operation IDs that start with\n * a digit (e.g. `409`, `504AccountCancel`) before using them as exported\n * variable, type, or function names.\n *\n * @example\n * ```ts\n * ensureValidVarName('409') // '_409'\n * ensureValidVarName('504AccountCancel') // '_504AccountCancel'\n * ensureValidVarName('Pet') // 'Pet'\n * ensureValidVarName('class') // '_class'\n * ```\n */\nexport function ensureValidVarName(name: string): string {\n if (!name || isValidVarName(name)) {\n return name\n }\n return `_${name}`\n}\n","import { camelCase } from './casing.ts'\nimport { isValidVarName } from './reserved.ts'\n\nexport type URLObject = {\n /**\n * The resolved URL string (Express-style or template literal, depending on context).\n */\n url: string\n /**\n * Extracted path parameters as a key-value map, or `null` when the path has none.\n */\n params: Record<string, string> | null\n}\n\ntype ObjectOptions = {\n /**\n * Controls whether the `url` is rendered as an Express path or a template literal.\n * @default 'path'\n */\n type?: 'path' | 'template'\n /**\n * Optional transform applied to each extracted parameter name.\n */\n replacer?: (pathParam: string) => string\n /**\n * When `true`, the result is serialized to a string expression instead of a plain object.\n */\n stringify?: boolean\n}\n\n/**\n * Supported identifier casing strategies for path parameters.\n */\ntype PathCasing = 'camelcase'\n\ntype Options = {\n /**\n * Casing strategy applied to path parameter names.\n * @default undefined (original identifier preserved)\n */\n casing?: PathCasing\n}\n\n/**\n * Parses and transforms an OpenAPI/Swagger path string into various URL formats.\n *\n * @example\n * const p = new URLPath('/pet/{petId}')\n * p.URL // '/pet/:petId'\n * p.template // '`/pet/${petId}`'\n */\nexport class URLPath {\n /**\n * The raw OpenAPI/Swagger path string, e.g. `/pet/{petId}`.\n */\n path: string\n\n #options: Options\n\n constructor(path: string, options: Options = {}) {\n this.path = path\n this.#options = options\n }\n\n /** Converts the OpenAPI path to Express-style colon syntax, e.g. `/pet/{petId}` → `/pet/:petId`.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}').URL // '/pet/:petId'\n * ```\n */\n get URL(): string {\n return this.toURLPath()\n }\n\n /** Returns `true` when `path` is a fully-qualified URL (e.g. starts with `https://`).\n *\n * @example\n * ```ts\n * new URLPath('https://petstore.swagger.io/v2/pet').isURL // true\n * new URLPath('/pet/{petId}').isURL // false\n * ```\n */\n get isURL(): boolean {\n try {\n return !!new URL(this.path).href\n } catch {\n return false\n }\n }\n\n /**\n * Converts the OpenAPI path to a TypeScript template literal string.\n *\n * @example\n * new URLPath('/pet/{petId}').template // '`/pet/${petId}`'\n * new URLPath('/account/monetary-accountID').template // '`/account/${monetaryAccountId}`'\n */\n get template(): string {\n return this.toTemplateString()\n }\n\n /** Returns the path and its extracted params as a structured `URLObject`, or as a stringified expression when `stringify` is set.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}').object\n * // { url: '/pet/:petId', params: { petId: 'petId' } }\n * ```\n */\n get object(): URLObject | string {\n return this.toObject()\n }\n\n /** Returns a map of path parameter names, or `null` when the path has no parameters.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}').params // { petId: 'petId' }\n * new URLPath('/pet').params // null\n * ```\n */\n get params(): Record<string, string> | null {\n return this.toParamsObject()\n }\n\n #transformParam(raw: string): string {\n const param = isValidVarName(raw) ? raw : camelCase(raw)\n return this.#options.casing === 'camelcase' ? camelCase(param) : param\n }\n\n /**\n * Iterates over every `{param}` token in `path`, calling `fn` with the raw token and transformed name.\n */\n #eachParam(fn: (raw: string, param: string) => undefined): undefined {\n for (const match of this.path.matchAll(/\\{([^}]+)\\}/g)) {\n const raw = match[1]!\n fn(raw, this.#transformParam(raw))\n }\n }\n\n toObject({ type = 'path', replacer, stringify }: ObjectOptions = {}): URLObject | string {\n const object = {\n url: type === 'path' ? this.toURLPath() : this.toTemplateString({ replacer }),\n params: this.toParamsObject(),\n }\n\n if (stringify) {\n if (type === 'template') {\n return JSON.stringify(object).replaceAll(\"'\", '').replaceAll(`\"`, '')\n }\n\n if (object.params) {\n return `{ url: '${object.url}', params: ${JSON.stringify(object.params).replaceAll(\"'\", '').replaceAll(`\"`, '')} }`\n }\n\n return `{ url: '${object.url}' }`\n }\n\n return object\n }\n\n /**\n * Converts the OpenAPI path to a TypeScript template literal string.\n * An optional `replacer` can transform each extracted parameter name before interpolation.\n *\n * @example\n * new URLPath('/pet/{petId}').toTemplateString() // '`/pet/${petId}`'\n */\n toTemplateString({ prefix, replacer }: { prefix?: string | null; replacer?: (pathParam: string) => string } = {}): string {\n const parts = this.path.split(/\\{([^}]+)\\}/)\n const result = parts\n .map((part, i) => {\n if (i % 2 === 0) return part\n const param = this.#transformParam(part)\n return `\\${${replacer ? replacer(param) : param}}`\n })\n .join('')\n\n return `\\`${prefix ?? ''}${result}\\``\n }\n\n /**\n * Extracts all `{param}` segments from the path and returns them as a key-value map.\n * An optional `replacer` transforms each parameter name in both key and value positions.\n * Returns `undefined` when no path parameters are found.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}/tag/{tagId}').toParamsObject()\n * // { petId: 'petId', tagId: 'tagId' }\n * ```\n */\n toParamsObject(replacer?: (pathParam: string) => string): Record<string, string> | null {\n const params: Record<string, string> = {}\n\n this.#eachParam((_raw, param) => {\n const key = replacer ? replacer(param) : param\n params[key] = key\n })\n\n return Object.keys(params).length > 0 ? params : null\n }\n\n /** Converts the OpenAPI path to Express-style colon syntax.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}').toURLPath() // '/pet/:petId'\n * ```\n */\n toURLPath(): string {\n return this.path.replace(/\\{([^}]+)\\}/g, ':$1')\n }\n}\n","import { File } from '@kubb/renderer-jsx'\nimport type { KubbReactNode } from '@kubb/renderer-jsx/types'\n\ntype HandlersProps = {\n /**\n * Name of the function\n */\n name: string\n // custom\n handlers: Array<string>\n}\n\nexport function Handlers({ name, handlers }: HandlersProps): KubbReactNode {\n return (\n <File.Source name={name} isIndexable isExportable>\n {`export const ${name} = ${JSON.stringify(handlers).replaceAll(`\"`, '')} as const`}\n </File.Source>\n )\n}\n","import { URLPath } from '@internals/utils'\nimport { ast } from '@kubb/core'\n\nexport type ContentTypeInfo = {\n contentTypes: string[]\n isMultipleContentTypes: boolean\n contentTypeUnion: string\n defaultContentType: string\n hasFormData: boolean\n}\n\nexport type RequestConfigResolver = {\n resolveDataName(node: ast.OperationNode): string\n}\n\nexport type ResponseStatusNameResolver = {\n resolveResponseStatusName(node: ast.OperationNode, statusCode: ast.StatusCode): string\n}\n\nexport type ResponseNameResolver = ResponseStatusNameResolver & {\n resolveResponseName(node: ast.OperationNode): string\n}\n\nexport type OperationTypeNameResolver = RequestConfigResolver &\n ResponseNameResolver & {\n resolvePathParamsName(node: ast.OperationNode, param: ast.ParameterNode): string\n resolveQueryParamsName(node: ast.OperationNode, param: ast.ParameterNode): string\n resolveHeaderParamsName(node: ast.OperationNode, param: ast.ParameterNode): string\n }\n\nexport type OperationCommentLink = 'pathTemplate' | 'urlPath' | false | ((node: ast.OperationNode) => string | undefined)\n\nexport type BuildOperationCommentsOptions = {\n link?: OperationCommentLink\n linkPosition?: 'beforeDeprecated' | 'afterDeprecated'\n splitLines?: boolean\n}\n\ntype ResponseLike = {\n statusCode: ast.StatusCode | number | string\n}\n\nexport type OperationParameterGroups = Record<ast.ParameterNode['in'], Array<ast.ParameterNode>>\n\nexport type ResolveOperationTypeNameOptions = {\n paramsCasing?: 'camelcase'\n responseStatusNames?: boolean | 'error'\n exclude?: ReadonlyArray<string | undefined>\n order?: 'params-first' | 'body-response-first'\n}\n\nfunction getOperationLink(node: ast.OperationNode, link: OperationCommentLink): string | null {\n if (!link) {\n return null\n }\n\n if (typeof link === 'function') {\n return link(node) ?? null\n }\n\n if (link === 'urlPath') {\n return node.path ? `{@link ${new URLPath(node.path).URL}}` : null\n }\n\n return `{@link ${node.path.replaceAll('{', ':').replaceAll('}', '')}}`\n}\n\nexport function getContentTypeInfo(node: ast.OperationNode): ContentTypeInfo {\n const contentTypes = node.requestBody?.content?.map((e) => e.contentType) ?? []\n const isMultipleContentTypes = contentTypes.length > 1\n\n return {\n contentTypes,\n isMultipleContentTypes,\n contentTypeUnion: isMultipleContentTypes ? contentTypes.map((ct) => JSON.stringify(ct)).join(' | ') : '',\n defaultContentType: contentTypes[0] ?? 'application/json',\n hasFormData: contentTypes.some((ct) => ct === 'multipart/form-data'),\n }\n}\n\nexport function buildRequestConfigType(node: ast.OperationNode, resolver: RequestConfigResolver): string {\n const requestName = node.requestBody?.content?.[0]?.schema ? resolver.resolveDataName(node) : null\n const { isMultipleContentTypes, contentTypeUnion } = getContentTypeInfo(node)\n const configType = requestName ? `Partial<RequestConfig<${requestName}>>` : 'Partial<RequestConfig>'\n const configProps = ['client?: Client', isMultipleContentTypes ? `contentType?: ${contentTypeUnion}` : null].filter(Boolean).join('; ')\n\n return `${configType} & { ${configProps} }`\n}\n\nexport function buildOperationComments(node: ast.OperationNode, options: BuildOperationCommentsOptions = {}): Array<string> {\n const { link = 'pathTemplate', linkPosition = 'afterDeprecated', splitLines = false } = options\n const linkComment = getOperationLink(node, link)\n const comments =\n linkPosition === 'beforeDeprecated'\n ? [node.description && `@description ${node.description}`, node.summary && `@summary ${node.summary}`, linkComment, node.deprecated && '@deprecated']\n : [node.description && `@description ${node.description}`, node.summary && `@summary ${node.summary}`, node.deprecated && '@deprecated', linkComment]\n\n const filteredComments = comments.filter((comment): comment is string => Boolean(comment))\n\n if (!splitLines) {\n return filteredComments\n }\n\n return filteredComments.flatMap((text) => text.split(/\\r?\\n/).map((line) => line.trim())).filter((comment): comment is string => Boolean(comment))\n}\n\nexport function getOperationParameters(node: ast.OperationNode, options: { paramsCasing?: 'camelcase' } = {}): OperationParameterGroups {\n const params = ast.caseParams(node.parameters, options.paramsCasing)\n\n return {\n path: params.filter((param) => param.in === 'path'),\n query: params.filter((param) => param.in === 'query'),\n header: params.filter((param) => param.in === 'header'),\n cookie: params.filter((param) => param.in === 'cookie'),\n }\n}\n\nexport function getStatusCodeNumber(statusCode: ast.StatusCode | number | string): number | null {\n const code = Number(statusCode)\n\n return Number.isNaN(code) ? null : code\n}\n\nexport function isSuccessStatusCode(statusCode: ast.StatusCode | number | string): boolean {\n const code = getStatusCodeNumber(statusCode)\n\n return code !== null && code >= 200 && code < 300\n}\n\nexport function isErrorStatusCode(statusCode: ast.StatusCode | number | string): boolean {\n const code = getStatusCodeNumber(statusCode)\n\n return code !== null && code >= 400\n}\n\nexport function getSuccessResponses<TResponse extends ResponseLike>(responses: ReadonlyArray<TResponse>): Array<TResponse> {\n return responses.filter((response) => isSuccessStatusCode(response.statusCode))\n}\n\nexport function getOperationSuccessResponses(node: ast.OperationNode): Array<ast.ResponseNode> {\n return getSuccessResponses(node.responses)\n}\n\nexport function getPrimarySuccessResponse(node: ast.OperationNode): ast.ResponseNode | null {\n return getOperationSuccessResponses(node)[0] ?? null\n}\n\nexport function resolveErrorNames(node: ast.OperationNode, resolver: ResponseStatusNameResolver): string[] {\n return node.responses\n .filter((response) => isErrorStatusCode(response.statusCode))\n .map((response) => resolver.resolveResponseStatusName(node, response.statusCode))\n}\n\nexport function resolveSuccessNames(node: ast.OperationNode, resolver: ResponseStatusNameResolver): string[] {\n return node.responses\n .filter((response) => isSuccessStatusCode(response.statusCode))\n .map((response) => resolver.resolveResponseStatusName(node, response.statusCode))\n}\n\nexport function resolveStatusCodeNames(node: ast.OperationNode, resolver: ResponseStatusNameResolver): string[] {\n return node.responses.map((response) => resolver.resolveResponseStatusName(node, response.statusCode))\n}\n\nconst typeNamesByResolver = new WeakMap<OperationTypeNameResolver, Map<string, string[]>>()\n\nexport function resolveOperationTypeNames(\n node: ast.OperationNode,\n resolver: OperationTypeNameResolver,\n options: ResolveOperationTypeNameOptions = {},\n): string[] {\n const cacheKey = `${node.operationId}\\0${options.paramsCasing ?? ''}\\0${options.order ?? ''}\\0${options.responseStatusNames ?? ''}\\0${(options.exclude ?? []).join(',')}`\n let byResolver = typeNamesByResolver.get(resolver)\n if (byResolver) {\n const cached = byResolver.get(cacheKey)\n if (cached) return cached\n } else {\n byResolver = new Map()\n typeNamesByResolver.set(resolver, byResolver)\n }\n\n const { path, query, header } = getOperationParameters(node, { paramsCasing: options.paramsCasing })\n const responseStatusNames =\n options.responseStatusNames === 'error'\n ? resolveErrorNames(node, resolver)\n : options.responseStatusNames === false\n ? []\n : resolveStatusCodeNames(node, resolver)\n const exclude = new Set(options.exclude ?? [])\n const paramNames = [\n ...path.map((param) => resolver.resolvePathParamsName(node, param)),\n ...query.map((param) => resolver.resolveQueryParamsName(node, param)),\n ...header.map((param) => resolver.resolveHeaderParamsName(node, param)),\n ]\n const bodyAndResponseNames = [node.requestBody?.content?.[0]?.schema ? resolver.resolveDataName(node) : null, resolver.resolveResponseName(node)]\n const names =\n options.order === 'body-response-first'\n ? [...bodyAndResponseNames, ...paramNames, ...responseStatusNames]\n : [...paramNames, ...bodyAndResponseNames, ...responseStatusNames]\n\n const result = names.filter((name): name is string => Boolean(name) && !exclude.has(name as string))\n byResolver.set(cacheKey, result)\n return result\n}\n\nexport function resolveResponseTypes(node: ast.OperationNode, resolver: ResponseNameResolver): Array<[statusCode: number | 'default', typeName: string]> {\n const types: Array<[number | 'default', string]> = []\n\n for (const response of node.responses) {\n if (response.statusCode === 'default') {\n types.push(['default', resolver.resolveResponseName(node)])\n continue\n }\n\n const code = getStatusCodeNumber(response.statusCode)\n if (code === null) {\n continue\n }\n\n types.push([code, isSuccessStatusCode(code) ? resolver.resolveResponseName(node) : resolver.resolveResponseStatusName(node, response.statusCode)])\n }\n\n return types\n}\n\nexport function findSuccessStatusCode(responses: Array<{ statusCode: ast.StatusCode | number | string }>): ast.StatusCode | null {\n for (const response of responses) {\n if (isSuccessStatusCode(response.statusCode)) {\n return response.statusCode as ast.StatusCode\n }\n }\n\n return null\n}\n","import type { ast } from '@kubb/core'\nimport type { ResolverFaker } from '@kubb/plugin-faker'\nimport type { PluginMsw } from './types.ts'\n\n/**\n * Gets the content type from a response, defaulting to 'application/json' if a schema exists.\n */\nexport function getContentType(response: ast.ResponseNode | null | undefined): string | null {\n if (!hasResponseSchema(response)) {\n return null\n }\n\n return getResponseContentType(response) ?? 'application/json'\n}\n\n/**\n * Determines if a response has a schema that is not void or any.\n */\nexport function hasResponseSchema(response: ast.ResponseNode | null | undefined): boolean {\n const schema = response?.content?.[0]?.schema\n return !!schema && schema.type !== 'void' && schema.type !== 'any'\n}\n\nfunction getResponseContentType(response: ast.ResponseNode | null | undefined): string | null {\n const value = response?.content?.[0]?.contentType\n return typeof value === 'string' && value.length > 0 ? value : null\n}\n\n/**\n * Converts an HTTP method to its lowercase MSW equivalent (e.g., 'POST' → 'post').\n */\nexport function getMswMethod(node: ast.OperationNode): string {\n return node.method.toLowerCase()\n}\n\n/**\n * Converts an OpenAPI-style path to an Express/MSW-style path by replacing `{param}` with `:param`.\n */\nexport function getMswUrl(node: ast.OperationNode): string {\n return node.path.replaceAll('{', ':').replaceAll('}', '')\n}\n\n/**\n * Resolves faker metadata for an MSW operation, including response name and file path.\n */\nexport function resolveFakerMeta(\n node: ast.OperationNode,\n options: {\n root: string\n fakerResolver: ResolverFaker\n fakerOutput: PluginMsw['resolvedOptions']['output']\n fakerGroup: PluginMsw['resolvedOptions']['group']\n },\n): { name: string; file: { path: string } } {\n const { root, fakerResolver, fakerOutput, fakerGroup } = options\n const tag = node.tags[0] ?? 'default'\n\n return {\n name: fakerResolver.resolveResponseName(node),\n file: fakerResolver.resolveFile(\n { name: node.operationId, extname: '.ts', tag, path: node.path },\n { root, output: fakerOutput, group: fakerGroup ?? undefined },\n ),\n }\n}\n","import { getPrimarySuccessResponse } from '@internals/shared'\nimport { URLPath } from '@internals/utils'\nimport { ast } from '@kubb/core'\nimport { functionPrinter } from '@kubb/plugin-ts'\nimport { File, Function } from '@kubb/renderer-jsx'\nimport type { KubbReactNode } from '@kubb/renderer-jsx/types'\nimport { getContentType, getMswMethod, getMswUrl, hasResponseSchema } from '../utils.ts'\n\ntype Props = {\n name: string\n typeName: string\n requestTypeName?: string | null\n baseURL: string | null | undefined\n node: ast.OperationNode\n}\n\nconst declarationPrinter = functionPrinter({ mode: 'declaration' })\n\nexport function Mock({ baseURL = '', name, typeName, requestTypeName, node }: Props): KubbReactNode {\n const method = getMswMethod(node)\n const successResponse = getPrimarySuccessResponse(node)\n const statusCode = successResponse ? Number(successResponse.statusCode) : 200\n const contentType = getContentType(successResponse)\n const url = new URLPath(getMswUrl(node)).toURLPath()\n\n const headers = [contentType ? `'Content-Type': '${contentType}'` : null].filter(Boolean)\n const responseHasSchema = hasResponseSchema(successResponse)\n const dataType = responseHasSchema ? typeName : 'string | number | boolean | null | object'\n\n const callbackType = requestTypeName\n ? `HttpResponseResolver<Record<string, string>, ${requestTypeName}, any>`\n : `((info: Parameters<Parameters<typeof http.${method}>[1]>[0]) => Response | Promise<Response>)`\n\n const params = declarationPrinter.print(\n ast.createFunctionParameters({\n params: [\n ast.createFunctionParameter({\n name: 'data',\n type: ast.createParamsType({\n variant: 'reference',\n name: `${dataType} | ${callbackType}`,\n }),\n optional: true,\n }),\n ],\n }),\n )\n\n const httpCall = requestTypeName ? `http.${method}<Record<string, string>, ${requestTypeName}, any>` : `http.${method}`\n\n return (\n <File.Source name={name} isIndexable isExportable>\n <Function name={name} export params={params ?? ''}>\n {`return ${httpCall}(\\`${baseURL}${url.replace(/([^/]):/g, '$1\\\\\\\\:')}\\`, function handler(info) {\n if(typeof data === 'function') return data(info)\n\n return new Response(JSON.stringify(data), {\n status: ${statusCode},\n ${\n headers.length\n ? ` headers: {\n ${headers.join(', \\n')}\n },`\n : ''\n }\n })\n })`}\n </Function>\n </File.Source>\n )\n}\n","import { getPrimarySuccessResponse } from '@internals/shared'\nimport { URLPath } from '@internals/utils'\nimport { ast } from '@kubb/core'\nimport { functionPrinter } from '@kubb/plugin-ts'\nimport { File, Function } from '@kubb/renderer-jsx'\nimport type { KubbReactNode } from '@kubb/renderer-jsx/types'\nimport { getContentType, getMswMethod, getMswUrl } from '../utils.ts'\n\ntype Props = {\n name: string\n typeName: string\n requestTypeName?: string | null\n fakerName: string\n baseURL: string | null | undefined\n node: ast.OperationNode\n}\n\nconst declarationPrinter = functionPrinter({ mode: 'declaration' })\n\nexport function MockWithFaker({ baseURL = '', name, fakerName, typeName, requestTypeName, node }: Props): KubbReactNode {\n const method = getMswMethod(node)\n const successResponse = getPrimarySuccessResponse(node)\n const statusCode = successResponse ? Number(successResponse.statusCode) : 200\n const contentType = getContentType(successResponse)\n const url = new URLPath(getMswUrl(node)).toURLPath()\n\n const headers = [contentType ? `'Content-Type': '${contentType}'` : null].filter(Boolean)\n\n const callbackType = requestTypeName\n ? `HttpResponseResolver<Record<string, string>, ${requestTypeName}, any>`\n : `((info: Parameters<Parameters<typeof http.${method}>[1]>[0]) => Response | Promise<Response>)`\n\n const params = declarationPrinter.print(\n ast.createFunctionParameters({\n params: [\n ast.createFunctionParameter({\n name: 'data',\n type: ast.createParamsType({\n variant: 'reference',\n name: `${typeName} | ${callbackType}`,\n }),\n optional: true,\n }),\n ],\n }),\n )\n\n const httpCall = requestTypeName ? `http.${method}<Record<string, string>, ${requestTypeName}, any>` : `http.${method}`\n\n return (\n <File.Source name={name} isIndexable isExportable>\n <Function name={name} export params={params ?? ''}>\n {`return ${httpCall}('${baseURL}${url.replace(/([^/]):/g, '$1\\\\\\\\:')}', function handler(info) {\n if(typeof data === 'function') return data(info)\n\n return new Response(JSON.stringify(data || ${fakerName}(data)), {\n status: ${statusCode},\n ${\n headers.length\n ? ` headers: {\n ${headers.join(', \\n')}\n },`\n : ''\n }\n })\n })`}\n </Function>\n </File.Source>\n )\n}\n","import { ast } from '@kubb/core'\nimport { functionPrinter } from '@kubb/plugin-ts'\nimport { File, Function } from '@kubb/renderer-jsx'\nimport type { KubbReactNode } from '@kubb/renderer-jsx/types'\nimport { getContentType, hasResponseSchema } from '../utils.ts'\n\ntype Props = {\n typeName: string\n name: string\n response: ast.ResponseNode\n key?: string | number | null\n}\n\nconst declarationPrinter = functionPrinter({ mode: 'declaration' })\n\nexport function Response({ name, typeName, response }: Props): KubbReactNode {\n const statusCode = Number(response.statusCode)\n const contentType = getContentType(response)\n const headers = [contentType ? `'Content-Type': '${contentType}'` : null].filter(Boolean)\n\n const params = declarationPrinter.print(\n ast.createFunctionParameters({\n params: [\n ast.createFunctionParameter({\n name: 'data',\n type: ast.createParamsType({ variant: 'reference', name: typeName }),\n optional: !hasResponseSchema(response),\n }),\n ],\n }),\n )\n\n const responseName = `${name}Response${statusCode}`\n\n return (\n <File.Source name={responseName} isIndexable isExportable>\n <Function name={responseName} export params={params ?? ''}>\n {`\n return new Response(JSON.stringify(data), {\n status: ${statusCode},\n ${\n headers.length\n ? ` headers: {\n ${headers.join(', \\n')}\n },`\n : ''\n }\n })`}\n </Function>\n </File.Source>\n )\n}\n"],"mappings":";;;;;;;;;;;;;AAsBA,SAAS,gBAAgB,MAAc,QAAyB;CAS9D,OARmB,KAChB,MAAM,CACN,QAAQ,qBAAqB,QAAQ,CACrC,QAAQ,yBAAyB,QAAQ,CACzC,QAAQ,gBAAgB,QAEH,CAAC,MAAM,gBAAgB,CAAC,OAAO,QAE3C,CACT,KAAK,MAAM,MAAM;EAEhB,IADiB,KAAK,SAAS,KAAK,SAAS,KAAK,aAAa,EACjD,OAAO;EACrB,IAAI,MAAM,KAAK,CAAC,QAAQ,OAAO,KAAK,OAAO,EAAE,CAAC,aAAa,GAAG,KAAK,MAAM,EAAE;EAC3E,OAAO,KAAK,OAAO,EAAE,CAAC,aAAa,GAAG,KAAK,MAAM,EAAE;GACnD,CACD,KAAK,GAAG,CACR,QAAQ,iBAAiB,GAAG;;;;;;;;;;AAWjC,SAAS,iBAAiB,MAAc,eAAkE;CACxG,MAAM,QAAQ,KAAK,MAAM,iBAAiB;CAC1C,OAAO,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MAAM;GAAc,QAAA;GAAO,QAAQ,UAAU;aACpD;;gBAEO,WAAW;QAEnB,QAAQ,SACJ;UACF,QAAQ,KAAK,OAAO,CAAC;YAEnB,GACL;;GAEU,CAAA;EACC,CAAA"}
|
|
@@ -220,16 +220,16 @@ var URLPath = class {
|
|
|
220
220
|
get object() {
|
|
221
221
|
return this.toObject();
|
|
222
222
|
}
|
|
223
|
-
/** Returns a map of path parameter names, or `
|
|
223
|
+
/** Returns a map of path parameter names, or `null` when the path has no parameters.
|
|
224
224
|
*
|
|
225
225
|
* @example
|
|
226
226
|
* ```ts
|
|
227
227
|
* new URLPath('/pet/{petId}').params // { petId: 'petId' }
|
|
228
|
-
* new URLPath('/pet').params //
|
|
228
|
+
* new URLPath('/pet').params // null
|
|
229
229
|
* ```
|
|
230
230
|
*/
|
|
231
231
|
get params() {
|
|
232
|
-
return this.
|
|
232
|
+
return this.toParamsObject();
|
|
233
233
|
}
|
|
234
234
|
#transformParam(raw) {
|
|
235
235
|
const param = isValidVarName(raw) ? raw : camelCase(raw);
|
|
@@ -247,7 +247,7 @@ var URLPath = class {
|
|
|
247
247
|
toObject({ type = "path", replacer, stringify } = {}) {
|
|
248
248
|
const object = {
|
|
249
249
|
url: type === "path" ? this.toURLPath() : this.toTemplateString({ replacer }),
|
|
250
|
-
params: this.
|
|
250
|
+
params: this.toParamsObject()
|
|
251
251
|
};
|
|
252
252
|
if (stringify) {
|
|
253
253
|
if (type === "template") return JSON.stringify(object).replaceAll("'", "").replaceAll(`"`, "");
|
|
@@ -263,12 +263,13 @@ var URLPath = class {
|
|
|
263
263
|
* @example
|
|
264
264
|
* new URLPath('/pet/{petId}').toTemplateString() // '`/pet/${petId}`'
|
|
265
265
|
*/
|
|
266
|
-
toTemplateString({ prefix
|
|
267
|
-
|
|
266
|
+
toTemplateString({ prefix, replacer } = {}) {
|
|
267
|
+
const result = this.path.split(/\{([^}]+)\}/).map((part, i) => {
|
|
268
268
|
if (i % 2 === 0) return part;
|
|
269
269
|
const param = this.#transformParam(part);
|
|
270
270
|
return `\${${replacer ? replacer(param) : param}}`;
|
|
271
|
-
}).join("")
|
|
271
|
+
}).join("");
|
|
272
|
+
return `\`${prefix ?? ""}${result}\``;
|
|
272
273
|
}
|
|
273
274
|
/**
|
|
274
275
|
* Extracts all `{param}` segments from the path and returns them as a key-value map.
|
|
@@ -277,17 +278,17 @@ var URLPath = class {
|
|
|
277
278
|
*
|
|
278
279
|
* @example
|
|
279
280
|
* ```ts
|
|
280
|
-
* new URLPath('/pet/{petId}/tag/{tagId}').
|
|
281
|
+
* new URLPath('/pet/{petId}/tag/{tagId}').toParamsObject()
|
|
281
282
|
* // { petId: 'petId', tagId: 'tagId' }
|
|
282
283
|
* ```
|
|
283
284
|
*/
|
|
284
|
-
|
|
285
|
+
toParamsObject(replacer) {
|
|
285
286
|
const params = {};
|
|
286
287
|
this.#eachParam((_raw, param) => {
|
|
287
288
|
const key = replacer ? replacer(param) : param;
|
|
288
289
|
params[key] = key;
|
|
289
290
|
});
|
|
290
|
-
return Object.keys(params).length > 0 ? params :
|
|
291
|
+
return Object.keys(params).length > 0 ? params : null;
|
|
291
292
|
}
|
|
292
293
|
/** Converts the OpenAPI path to Express-style colon syntax.
|
|
293
294
|
*
|
|
@@ -311,64 +312,56 @@ function Handlers({ name, handlers }) {
|
|
|
311
312
|
});
|
|
312
313
|
}
|
|
313
314
|
//#endregion
|
|
314
|
-
//#region src/
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
function transformName(name, type, transformers) {
|
|
319
|
-
return transformers?.name?.(name, type) || name;
|
|
315
|
+
//#region ../../internals/shared/src/operation.ts
|
|
316
|
+
function getStatusCodeNumber(statusCode) {
|
|
317
|
+
const code = Number(statusCode);
|
|
318
|
+
return Number.isNaN(code) ? null : code;
|
|
320
319
|
}
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
320
|
+
function isSuccessStatusCode(statusCode) {
|
|
321
|
+
const code = getStatusCodeNumber(statusCode);
|
|
322
|
+
return code !== null && code >= 200 && code < 300;
|
|
323
|
+
}
|
|
324
|
+
function getSuccessResponses(responses) {
|
|
325
|
+
return responses.filter((response) => isSuccessStatusCode(response.statusCode));
|
|
326
|
+
}
|
|
327
|
+
function getOperationSuccessResponses(node) {
|
|
328
|
+
return getSuccessResponses(node.responses);
|
|
329
329
|
}
|
|
330
|
-
/**
|
|
331
|
-
* Returns the first 2xx response for an operation, if any.
|
|
332
|
-
*/
|
|
333
330
|
function getPrimarySuccessResponse(node) {
|
|
334
|
-
return
|
|
331
|
+
return getOperationSuccessResponses(node)[0] ?? null;
|
|
332
|
+
}
|
|
333
|
+
function resolveResponseTypes(node, resolver) {
|
|
334
|
+
const types = [];
|
|
335
|
+
for (const response of node.responses) {
|
|
336
|
+
if (response.statusCode === "default") {
|
|
337
|
+
types.push(["default", resolver.resolveResponseName(node)]);
|
|
338
|
+
continue;
|
|
339
|
+
}
|
|
340
|
+
const code = getStatusCodeNumber(response.statusCode);
|
|
341
|
+
if (code === null) continue;
|
|
342
|
+
types.push([code, isSuccessStatusCode(code) ? resolver.resolveResponseName(node) : resolver.resolveResponseStatusName(node, response.statusCode)]);
|
|
343
|
+
}
|
|
344
|
+
return types;
|
|
335
345
|
}
|
|
346
|
+
//#endregion
|
|
347
|
+
//#region src/utils.ts
|
|
336
348
|
/**
|
|
337
349
|
* Gets the content type from a response, defaulting to 'application/json' if a schema exists.
|
|
338
350
|
*/
|
|
339
351
|
function getContentType(response) {
|
|
340
|
-
|
|
352
|
+
if (!hasResponseSchema(response)) return null;
|
|
353
|
+
return getResponseContentType(response) ?? "application/json";
|
|
341
354
|
}
|
|
342
355
|
/**
|
|
343
356
|
* Determines if a response has a schema that is not void or any.
|
|
344
357
|
*/
|
|
345
358
|
function hasResponseSchema(response) {
|
|
346
|
-
|
|
359
|
+
const schema = response?.content?.[0]?.schema;
|
|
360
|
+
return !!schema && schema.type !== "void" && schema.type !== "any";
|
|
347
361
|
}
|
|
348
362
|
function getResponseContentType(response) {
|
|
349
|
-
const
|
|
350
|
-
|
|
351
|
-
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
352
|
-
}
|
|
353
|
-
/**
|
|
354
|
-
* Maps all operation responses to their type names, including status code or 'default' for default responses.
|
|
355
|
-
*/
|
|
356
|
-
function getResponseTypes(node, tsResolver) {
|
|
357
|
-
const types = [];
|
|
358
|
-
for (const response of node.responses) {
|
|
359
|
-
if (response.statusCode === "default") {
|
|
360
|
-
types.push(["default", tsResolver.resolveResponseName(node)]);
|
|
361
|
-
continue;
|
|
362
|
-
}
|
|
363
|
-
const code = Number.parseInt(response.statusCode, 10);
|
|
364
|
-
if (Number.isNaN(code)) continue;
|
|
365
|
-
if (code >= 200 && code < 300) {
|
|
366
|
-
types.push([code, tsResolver.resolveResponseName(node)]);
|
|
367
|
-
continue;
|
|
368
|
-
}
|
|
369
|
-
types.push([code, tsResolver.resolveResponseStatusName(node, response.statusCode)]);
|
|
370
|
-
}
|
|
371
|
-
return types;
|
|
363
|
+
const value = response?.content?.[0]?.contentType;
|
|
364
|
+
return typeof value === "string" && value.length > 0 ? value : null;
|
|
372
365
|
}
|
|
373
366
|
/**
|
|
374
367
|
* Converts an HTTP method to its lowercase MSW equivalent (e.g., 'POST' → 'post').
|
|
@@ -398,7 +391,7 @@ function resolveFakerMeta(node, options) {
|
|
|
398
391
|
}, {
|
|
399
392
|
root,
|
|
400
393
|
output: fakerOutput,
|
|
401
|
-
group: fakerGroup
|
|
394
|
+
group: fakerGroup ?? void 0
|
|
402
395
|
})
|
|
403
396
|
};
|
|
404
397
|
}
|
|
@@ -411,7 +404,7 @@ function Mock({ baseURL = "", name, typeName, requestTypeName, node }) {
|
|
|
411
404
|
const statusCode = successResponse ? Number(successResponse.statusCode) : 200;
|
|
412
405
|
const contentType = getContentType(successResponse);
|
|
413
406
|
const url = new URLPath(getMswUrl(node)).toURLPath();
|
|
414
|
-
const headers = [contentType ? `'Content-Type': '${contentType}'` :
|
|
407
|
+
const headers = [contentType ? `'Content-Type': '${contentType}'` : null].filter(Boolean);
|
|
415
408
|
const dataType = hasResponseSchema(successResponse) ? typeName : "string | number | boolean | null | object";
|
|
416
409
|
const callbackType = requestTypeName ? `HttpResponseResolver<Record<string, string>, ${requestTypeName}, any>` : `((info: Parameters<Parameters<typeof http.${method}>[1]>[0]) => Response | Promise<Response>)`;
|
|
417
410
|
const params = declarationPrinter$2.print(_kubb_core.ast.createFunctionParameters({ params: [_kubb_core.ast.createFunctionParameter({
|
|
@@ -453,7 +446,7 @@ function MockWithFaker({ baseURL = "", name, fakerName, typeName, requestTypeNam
|
|
|
453
446
|
const statusCode = successResponse ? Number(successResponse.statusCode) : 200;
|
|
454
447
|
const contentType = getContentType(successResponse);
|
|
455
448
|
const url = new URLPath(getMswUrl(node)).toURLPath();
|
|
456
|
-
const headers = [contentType ? `'Content-Type': '${contentType}'` :
|
|
449
|
+
const headers = [contentType ? `'Content-Type': '${contentType}'` : null].filter(Boolean);
|
|
457
450
|
const callbackType = requestTypeName ? `HttpResponseResolver<Record<string, string>, ${requestTypeName}, any>` : `((info: Parameters<Parameters<typeof http.${method}>[1]>[0]) => Response | Promise<Response>)`;
|
|
458
451
|
const params = declarationPrinter$1.print(_kubb_core.ast.createFunctionParameters({ params: [_kubb_core.ast.createFunctionParameter({
|
|
459
452
|
name: "data",
|
|
@@ -491,7 +484,7 @@ const declarationPrinter = (0, _kubb_plugin_ts.functionPrinter)({ mode: "declara
|
|
|
491
484
|
function Response({ name, typeName, response }) {
|
|
492
485
|
const statusCode = Number(response.statusCode);
|
|
493
486
|
const contentType = getContentType(response);
|
|
494
|
-
const headers = [contentType ? `'Content-Type': '${contentType}'` :
|
|
487
|
+
const headers = [contentType ? `'Content-Type': '${contentType}'` : null].filter(Boolean);
|
|
495
488
|
const params = declarationPrinter.print(_kubb_core.ast.createFunctionParameters({ params: [_kubb_core.ast.createFunctionParameter({
|
|
496
489
|
name: "data",
|
|
497
490
|
type: _kubb_core.ast.createParamsType({
|
|
@@ -556,16 +549,10 @@ Object.defineProperty(exports, "camelCase", {
|
|
|
556
549
|
return camelCase;
|
|
557
550
|
}
|
|
558
551
|
});
|
|
559
|
-
Object.defineProperty(exports, "
|
|
560
|
-
enumerable: true,
|
|
561
|
-
get: function() {
|
|
562
|
-
return getResponseTypes;
|
|
563
|
-
}
|
|
564
|
-
});
|
|
565
|
-
Object.defineProperty(exports, "getSuccessResponses", {
|
|
552
|
+
Object.defineProperty(exports, "getOperationSuccessResponses", {
|
|
566
553
|
enumerable: true,
|
|
567
554
|
get: function() {
|
|
568
|
-
return
|
|
555
|
+
return getOperationSuccessResponses;
|
|
569
556
|
}
|
|
570
557
|
});
|
|
571
558
|
Object.defineProperty(exports, "resolveFakerMeta", {
|
|
@@ -574,11 +561,11 @@ Object.defineProperty(exports, "resolveFakerMeta", {
|
|
|
574
561
|
return resolveFakerMeta;
|
|
575
562
|
}
|
|
576
563
|
});
|
|
577
|
-
Object.defineProperty(exports, "
|
|
564
|
+
Object.defineProperty(exports, "resolveResponseTypes", {
|
|
578
565
|
enumerable: true,
|
|
579
566
|
get: function() {
|
|
580
|
-
return
|
|
567
|
+
return resolveResponseTypes;
|
|
581
568
|
}
|
|
582
569
|
});
|
|
583
570
|
|
|
584
|
-
//# sourceMappingURL=components-
|
|
571
|
+
//# sourceMappingURL=components-CHyTtokd.cjs.map
|