@kubb/plugin-msw 5.0.0-alpha.9 → 5.0.0-beta.100

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/plugin.ts"],"sourcesContent":["import path from 'node:path'\nimport { camelCase } from '@internals/utils'\nimport { createPlugin, type Group, getBarrelFiles, getMode } from '@kubb/core'\nimport { pluginFakerName } from '@kubb/plugin-faker'\nimport { OperationGenerator, pluginOasName } from '@kubb/plugin-oas'\nimport { pluginTsName } from '@kubb/plugin-ts'\nimport { handlersGenerator, mswGenerator } from './generators'\nimport type { PluginMsw } from './types.ts'\n\nexport const pluginMswName = 'plugin-msw' satisfies PluginMsw['name']\n\nexport const pluginMsw = createPlugin<PluginMsw>((options) => {\n const {\n output = { path: 'handlers', barrelType: 'named' },\n group,\n exclude = [],\n include,\n override = [],\n transformers = {},\n handlers = false,\n parser = 'data',\n generators = [mswGenerator, handlers ? handlersGenerator : undefined].filter(Boolean),\n contentType,\n baseURL,\n } = options\n\n return {\n name: pluginMswName,\n options: {\n output,\n parser,\n group,\n baseURL,\n },\n pre: [pluginOasName, pluginTsName, parser === 'faker' ? pluginFakerName : undefined].filter(Boolean),\n resolvePath(baseName, pathMode, options) {\n const root = path.resolve(this.config.root, this.config.output.path)\n const mode = pathMode ?? getMode(path.resolve(root, output.path))\n\n if (mode === 'single') {\n /**\n * when output is a file then we will always append to the same file(output file), see fileManager.addOrAppend\n * Other plugins then need to call addOrAppend instead of just add from the fileManager class\n */\n return path.resolve(root, output.path)\n }\n\n if (group && (options?.group?.path || options?.group?.tag)) {\n const groupName: Group['name'] = group?.name\n ? group.name\n : (ctx) => {\n if (group?.type === 'path') {\n return `${ctx.group.split('/')[1]}`\n }\n return `${camelCase(ctx.group)}Controller`\n }\n\n return path.resolve(\n root,\n output.path,\n groupName({\n group: group.type === 'path' ? options.group.path! : options.group.tag!,\n }),\n baseName,\n )\n }\n\n return path.resolve(root, output.path, baseName)\n },\n resolveName(name, type) {\n const resolvedName = camelCase(name, {\n suffix: type ? 'handler' : undefined,\n isFile: type === 'file',\n })\n\n if (type) {\n return transformers?.name?.(resolvedName, type) || resolvedName\n }\n\n return resolvedName\n },\n async install() {\n const root = path.resolve(this.config.root, this.config.output.path)\n const mode = getMode(path.resolve(root, output.path))\n const oas = await this.getOas()\n\n const operationGenerator = new OperationGenerator(this.plugin.options, {\n fabric: this.fabric,\n oas,\n driver: this.driver,\n events: this.events,\n plugin: this.plugin,\n contentType,\n exclude,\n include,\n override,\n mode,\n })\n\n const files = await operationGenerator.build(...generators)\n await this.upsertFile(...files)\n\n const barrelFiles = await getBarrelFiles(this.fabric.files, {\n type: output.barrelType ?? 'named',\n root,\n output,\n meta: {\n pluginName: this.plugin.name,\n },\n })\n\n await this.upsertFile(...barrelFiles)\n },\n }\n})\n"],"mappings":";;;;;;;;;AASA,MAAa,gBAAgB;AAE7B,MAAa,YAAY,cAAyB,YAAY;CAC5D,MAAM,EACJ,SAAS;EAAE,MAAM;EAAY,YAAY;EAAS,EAClD,OACA,UAAU,EAAE,EACZ,SACA,WAAW,EAAE,EACb,eAAe,EAAE,EACjB,WAAW,OACX,SAAS,QACT,aAAa,CAAC,cAAc,WAAW,oBAAoB,KAAA,EAAU,CAAC,OAAO,QAAQ,EACrF,aACA,YACE;AAEJ,QAAO;EACL,MAAM;EACN,SAAS;GACP;GACA;GACA;GACA;GACD;EACD,KAAK;GAAC;GAAe;GAAc,WAAW,UAAU,kBAAkB,KAAA;GAAU,CAAC,OAAO,QAAQ;EACpG,YAAY,UAAU,UAAU,SAAS;GACvC,MAAM,OAAO,KAAK,QAAQ,KAAK,OAAO,MAAM,KAAK,OAAO,OAAO,KAAK;AAGpE,QAFa,YAAY,QAAQ,KAAK,QAAQ,MAAM,OAAO,KAAK,CAAC,MAEpD;;;;;AAKX,UAAO,KAAK,QAAQ,MAAM,OAAO,KAAK;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inter"],"sources":["../../../internals/shared/src/operation.ts","../../../internals/utils/src/casing.ts","../../../internals/shared/src/group.ts","../src/generators/handlersGenerator.ts","../src/utils.ts","../src/components/Mock.tsx","../src/components/Response.tsx","../src/generators/mswGenerator.tsx","../src/resolvers/resolverMsw.ts","../src/plugin.ts"],"sourcesContent":["import { type ast, type ResolverFileParams, Url } from 'kubb/kit'\nimport { dedupeParams } from './params.ts'\n\n/**\n * Builds the `ResolverFileParams` every operation generator passes to\n * `resolver.file`: a file named `name`, tagged by the operation's first\n * tag (or `'default'`), at the operation's path. Centralizes the entry object\n * that was repeated at dozens of call sites across the client and query plugins.\n *\n * @example\n * ```ts\n * resolver.file(operationFileEntry(node, node.operationId), { root, output, group })\n * ```\n */\nexport function operationFileEntry(node: ast.OperationNode, name: string, extname: ResolverFileParams['extname'] = '.ts'): ResolverFileParams {\n return {\n name,\n extname,\n tag: node.tags[0] ?? 'default',\n path: node.path,\n }\n}\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 response: {\n body(node: ast.OperationNode): string\n }\n}\n\nexport type ResponseStatusNameResolver = {\n response: {\n status(node: ast.OperationNode, statusCode: ast.StatusCode): string\n }\n}\n\nexport type ResponseNameResolver = ResponseStatusNameResolver & {\n response: {\n response(node: ast.OperationNode): string\n }\n}\n\nexport type OperationTypeNameResolver = RequestConfigResolver &\n ResponseNameResolver & {\n param: {\n path(node: ast.OperationNode, param: ast.ParameterNode): string\n query(node: ast.OperationNode, param: ast.ParameterNode): string\n headers(node: ast.OperationNode, param: ast.ParameterNode): string\n }\n }\n\n/**\n * Resolver interface for building operation parameters.\n *\n * `ResolverTs` from `@kubb/plugin-ts` satisfies this interface and can be passed directly.\n */\nexport type OperationParamsResolver = {\n /**\n * Naming for an operation's parameters, grouped by location.\n */\n param: {\n /**\n * Resolves the type name for an individual parameter.\n *\n * @example Individual path parameter name\n * `resolver.param.name(node, param) // → 'DeletePetPathPetId'`\n */\n name(node: ast.OperationNode, param: ast.ParameterNode): string\n /**\n * Resolves the grouped path parameters type name.\n * When the return value equals `resolver.param.name`, no indexed access is emitted.\n *\n * @example Grouped path params type name\n * `resolver.param.path(node, param) // → 'DeletePetPath'`\n */\n path(node: ast.OperationNode, param: ast.ParameterNode): string\n /**\n * Resolves the grouped query parameters type name.\n * When the return value equals `resolver.param.name`, an inline struct type is emitted instead.\n *\n * @example Grouped query params type name\n * `resolver.param.query(node, param) // → 'FindPetsByStatusQuery'`\n */\n query(node: ast.OperationNode, param: ast.ParameterNode): string\n /**\n * Resolves the grouped header parameters type name.\n * When the return value equals `resolver.param.name`, an inline struct type is emitted instead.\n *\n * @example Grouped header params type name\n * `resolver.param.headers(node, param) // → 'DeletePetHeaders'`\n */\n headers(node: ast.OperationNode, param: ast.ParameterNode): string\n }\n /**\n * Naming for an operation's request and response types.\n */\n response: {\n /**\n * Resolves the request body type name.\n *\n * @example Request body type name\n * `resolver.response.body(node) // → 'CreatePetBody'`\n */\n body(node: ast.OperationNode): string\n }\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 responseStatusNames?: boolean | 'error'\n exclude?: ReadonlyArray<string | undefined>\n order?: 'params-first' | 'body-response-first'\n /**\n * Include the individual `Path`/`Query`/`Headers` group type names. Set to `false` for clients\n * that reference the grouped `Options` type instead of the per-group types.\n */\n includeParams?: boolean\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 return node.path ? `{@link ${Url.toPath(node.path)}}` : null\n}\n\n/**\n * Derives the shared `ContentTypeInfo` shape from a list of content types, tracking whether several\n * are present and the union, default, and form-data flags the client uses to pick one.\n */\nfunction buildContentTypeInfo(contentTypes: string[]): ContentTypeInfo {\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 getContentTypeInfo(node: ast.OperationNode): ContentTypeInfo {\n return buildContentTypeInfo(node.requestBody?.content?.map((e) => e.contentType) ?? [])\n}\n\n/**\n * The request-body counterpart for the primary success response: the content types it documents and\n * whether several are present, so the client can let a caller pick which one to accept.\n */\nexport function getResponseContentTypeInfo(node: ast.OperationNode): ContentTypeInfo {\n return buildContentTypeInfo(getPrimarySuccessResponse(node)?.content?.map((e) => e.contentType) ?? [])\n}\n\nexport type ResponseType = 'arraybuffer' | 'blob' | 'document' | 'json' | 'text' | 'stream'\n\n/**\n * Reads the single base content type of an operation's primary success response, lowercased and\n * stripped of any `; charset=...` suffix. Returns `undefined` when the response declares zero or\n * more than one content type, since neither case has a single type to act on.\n */\nfunction getPrimarySuccessContentType(node: ast.OperationNode): string | undefined {\n const contentTypes = getPrimarySuccessResponse(node)?.content?.map((entry) => entry.contentType) ?? []\n if (contentTypes.length !== 1) return undefined\n return contentTypes[0]!.split(';')[0]!.trim().toLowerCase()\n}\n\n/**\n * Whether an operation streams its primary success response as Server-Sent Events\n * (`text/event-stream`). The client generator uses this to return a typed event stream instead of a\n * one-shot `RequestResult`.\n */\nexport function isEventStream(node: ast.OperationNode): boolean {\n return getPrimarySuccessContentType(node) === 'text/event-stream'\n}\n\n/**\n * Derives the default `responseType` for an operation from its primary success response.\n *\n * Returns a value only when that response declares a single non-JSON content type. `text/event-stream`\n * and other binary types (`application/octet-stream`, `application/pdf`, `image/*`, `audio/*`,\n * `video/*`) map to a stream or `'blob'`, and other `text/*` maps to `'text'`. Otherwise `undefined`,\n * leaving the runtime client's `Content-Type` auto-detection in charge.\n */\nexport function getResponseType(node: ast.OperationNode): ResponseType | undefined {\n const baseType = getPrimarySuccessContentType(node)\n if (!baseType) return undefined\n\n if (baseType === 'application/json' || baseType.endsWith('+json') || baseType === 'text/json') return undefined\n if (baseType === 'text/event-stream') return 'stream'\n if (baseType.startsWith('text/')) return 'text'\n if (baseType === 'application/octet-stream' || baseType === 'application/pdf' || /^(image|audio|video)\\//.test(baseType)) return 'blob'\n return undefined\n}\n\n/**\n * Maps a content type to the PascalCase suffix used to name per-content-type variants\n * (e.g. `application/json` → `Json`, `application/xml` → `Xml`, `multipart/form-data` → `FormData`).\n */\nfunction getContentTypeSuffix(contentType: string): string {\n const baseType = contentType.split(';')[0]!.trim()\n if (baseType === 'application/json') return 'Json'\n if (baseType === 'multipart/form-data') return 'FormData'\n if (baseType === 'application/x-www-form-urlencoded') return 'FormUrlEncoded'\n const subtype = baseType.split('/').pop() ?? baseType\n const parts = subtype.split(/[^a-zA-Z0-9]+/).filter(Boolean)\n if (parts.length === 0) return 'Unknown'\n return parts.map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join('')\n}\n\n/**\n * Appends a content-type suffix to a base name, keeping a trailing `Data` segment last\n * (e.g. `AddPetData` + `Json` → `AddPetJsonData`, `AddPetStatus200` + `Xml` → `AddPetStatus200Xml`).\n */\nexport function getPerContentTypeName(baseName: string, suffix: string): string {\n if (baseName.endsWith('Data')) {\n return suffix.endsWith('Data') ? baseName.slice(0, -4) + suffix : `${baseName.slice(0, -4)}${suffix}Data`\n }\n return baseName + suffix\n}\n\nexport type ContentVariantInput = { contentType: string; schema?: ast.SchemaNode | null; keysToOmit?: Array<string> | null }\nexport type ContentVariant = { name: string; suffix: string; schema: ast.SchemaNode; keysToOmit?: Array<string> | null; contentType: string }\n\n/**\n * Resolves per-content-type variant names for a set of content entries, deduplicating suffix\n * collisions with a numeric counter. Entries without a schema are skipped. The returned `suffix` is\n * the final (possibly counter-augmented) value, so callers can derive parallel names in another\n * namespace (e.g. plugin-faker deriving the matching plugin-ts type name).\n */\nexport function resolveContentTypeVariants(entries: Array<ContentVariantInput>, baseName: string): Array<ContentVariant> {\n const usedNames = new Set<string>()\n return entries\n .filter((entry) => entry.schema)\n .map((entry) => {\n const baseSuffix = getContentTypeSuffix(entry.contentType)\n let suffix = baseSuffix\n let name = getPerContentTypeName(baseName, suffix)\n let counter = 2\n while (usedNames.has(name)) {\n suffix = `${baseSuffix}${counter++}`\n name = getPerContentTypeName(baseName, suffix)\n }\n usedNames.add(name)\n return { name, suffix, schema: entry.schema!, keysToOmit: entry.keysToOmit, contentType: entry.contentType }\n })\n}\n\nexport function buildRequestConfigType(node: ast.OperationNode): string {\n const request = getContentTypeInfo(node)\n const response = getResponseContentTypeInfo(node)\n // The request groups come from the grouped params, so `config` drops the data-shape keys to stay\n // assignable to `Options`, which omits them from `RequestConfig`.\n const configType = `Partial<Omit<RequestConfig, 'path' | 'query' | 'body' | 'headers' | 'url'>>`\n\n // Only the ambiguous side is offered: a single-type side has nothing to pick, so it stays baked in\n // the generated call.\n const members = [\n request.isMultipleContentTypes ? `request?: ${request.contentTypeUnion}` : null,\n response.isMultipleContentTypes ? `response?: ${response.contentTypeUnion}` : null,\n ].filter(Boolean)\n\n return members.length ? `${configType} & { contentType?: { ${members.join('; ')} } }` : configType\n}\n\n/**\n * Builds the `client?:` option type shared by the generated query hooks (`useQuery`,\n * `useInfiniteQuery`, `useSWR`, ...). Unlike {@link buildRequestConfigType}, it never adds a\n * `contentType?:` member: query hooks wrap GET operations, which carry no request body to select a\n * content type for.\n */\nexport function buildClientOptionType(): string {\n return `Partial<Omit<RequestConfig, 'path' | 'query' | 'body' | 'headers' | 'url'>>`\n}\n\nexport type RequestGroups = {\n path: boolean\n query: boolean\n body: boolean\n headers: boolean\n}\n\n/**\n * Which of the grouped request options an operation carries.\n */\nexport function getRequestGroups(node: ast.OperationNode): RequestGroups {\n const { path, query, header } = getOperationParameters(node)\n return {\n path: path.length > 0,\n query: query.length > 0,\n body: Boolean(node.requestBody?.content?.[0]?.schema),\n headers: header.length > 0,\n }\n}\n\nexport type RequestGroupOptionality = {\n groups: RequestGroups\n hasRequiredPath: boolean\n hasRequiredQuery: boolean\n hasRequiredHeader: boolean\n /**\n * Whether the grouped request parameter can default to `{}`. True only when no group carries a\n * required member, so every member is safe to omit.\n */\n isOptional: boolean\n}\n\n/**\n * Resolves which grouped request options an operation carries together with whether each group\n * holds a required member. The grouped parameter stays optional only when nothing inside it is\n * required, matching the generated `RequestConfig` type.\n */\nexport function getRequestGroupOptionality(node: ast.OperationNode): RequestGroupOptionality {\n const groups = getRequestGroups(node)\n const { path, query, header } = getOperationParameters(node)\n const hasRequiredPath = path.some((param) => param.required)\n const hasRequiredQuery = query.some((param) => param.required)\n const hasRequiredHeader = header.some((param) => param.required)\n\n return {\n groups,\n hasRequiredPath,\n hasRequiredQuery,\n hasRequiredHeader,\n isOptional: !hasRequiredPath && !hasRequiredQuery && !hasRequiredHeader && !groups.body,\n }\n}\n\nexport type RequestOptionsNameResolver = RequestConfigResolver & {\n response: {\n options(node: ast.OperationNode): string\n }\n}\n\n/**\n * Builds the grouped `{ path, query, body, headers }` parameter for a generated client\n * function, typed from the operation's `Options` (minus `url`). Only the groups the\n * operation actually has are destructured. The trailing `config` parameter carries the\n * runtime `RequestConfig` overrides plus `client`.\n */\nexport function buildRequestParamsSignature(\n node: ast.OperationNode,\n resolver: RequestOptionsNameResolver,\n options: { isConfigurable?: boolean } = {},\n): { signature: string; groups: RequestGroups } {\n const { isConfigurable = true } = options\n const { groups, isOptional } = getRequestGroupOptionality(node)\n\n const names = (['path', 'query', 'body', 'headers'] as const).filter((key) => groups[key])\n\n const firstParam = names.length > 0 ? `{ ${names.join(', ')} }: ${resolver.response.options(node)}${isOptional ? ' = {}' : ''}` : null\n const configParam = isConfigurable ? `config: ${buildRequestConfigType(node)} = {}` : null\n\n return {\n signature: [firstParam, configParam].filter(Boolean).join(', '),\n groups,\n }\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): OperationParameterGroups {\n return {\n path: dedupeParams(node.parameters.filter((param) => param.in === 'path')),\n query: dedupeParams(node.parameters.filter((param) => param.in === 'query')),\n header: dedupeParams(node.parameters.filter((param) => param.in === 'header')),\n cookie: dedupeParams(node.parameters.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.filter((response) => isErrorStatusCode(response.statusCode)).map((response) => resolver.response.status(node, response.statusCode))\n}\n\nexport function resolveSuccessNames(node: ast.OperationNode, resolver: ResponseStatusNameResolver): string[] {\n return node.responses.filter((response) => isSuccessStatusCode(response.statusCode)).map((response) => resolver.response.status(node, response.statusCode))\n}\n\nexport function resolveStatusCodeNames(node: ast.OperationNode, resolver: ResponseStatusNameResolver): string[] {\n return node.responses.map((response) => resolver.response.status(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.order ?? ''}\\0${options.responseStatusNames ?? ''}\\0${options.includeParams === false ? 'noparams' : ''}\\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)\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 options.includeParams === false\n ? []\n : [\n ...path.map((param) => resolver.param.path(node, param)),\n ...query.map((param) => resolver.param.query(node, param)),\n ...header.map((param) => resolver.param.headers(node, param)),\n ]\n const bodyAndResponseNames = [node.requestBody?.content?.[0]?.schema ? resolver.response.body(node) : null, resolver.response.response(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.response.response(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.response.response(node) : resolver.response.status(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","type Options = {\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 return 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 .split(/[\\s\\-_./\\\\:]+/)\n .filter(Boolean)\n .map((word, i) => {\n if (word.length > 1 && word === word.toUpperCase()) return word\n const head = i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()\n return head + word.slice(1)\n })\n .join('')\n .replace(/[^a-zA-Z0-9]/g, '')\n}\n\n/**\n * Converts `text` to camelCase.\n *\n * @example Word boundaries\n * `camelCase('hello-world') // 'helloWorld'`\n *\n * @example With a prefix\n * `camelCase('tag', { prefix: 'create' }) // 'createTag'`\n */\nexport function camelCase(text: string, { prefix = '', suffix = '' }: Options = {}): string {\n return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false)\n}\n\n/**\n * Converts `text` to PascalCase.\n *\n * @example Word boundaries\n * `pascalCase('hello-world') // 'HelloWorld'`\n *\n * @example With a suffix\n * `pascalCase('tag', { suffix: 'schema' }) // 'TagSchema'`\n */\nexport function pascalCase(text: string, { prefix = '', suffix = '' }: Options = {}): string {\n return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true)\n}\n\n/**\n * Uppercases only the first character of `text`, leaving the rest untouched.\n * Unlike {@link pascalCase} it never re-splits word boundaries or strips characters.\n *\n * @example\n * `capitalize('getPetById') // 'GetPetById'`\n */\nexport function capitalize(text: string): string {\n return `${text.charAt(0).toUpperCase()}${text.slice(1)}`\n}\n\n/**\n * Converts `text` to snake_case.\n *\n * @example From camelCase\n * `snakeCase('helloWorld') // 'hello_world'`\n *\n * @example From mixed separators\n * `snakeCase('Hello-World') // 'hello_world'`\n */\nexport function snakeCase(text: string, { prefix = '', suffix = '' }: Options = {}): 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 From camelCase\n * `screamingSnakeCase('helloWorld') // 'HELLO_WORLD'`\n */\nexport function screamingSnakeCase(text: string, { prefix = '', suffix = '' }: Options = {}): string {\n return snakeCase(text, { prefix, suffix }).toUpperCase()\n}\n","import { camelCase } from '@internals/utils'\nimport type { Group } from 'kubb/kit'\n\n/**\n * Builds the `group` config a Kubb plugin passes to `ctx.setOptions`, applying the\n * shared default naming so every plugin groups output consistently:\n *\n * - `path` groups use the second path segment (`/pet/findByStatus` → `pet`).\n * - other groups use the camelCased group (`pet store` → `petStore`).\n *\n * A user-provided `group.name` always wins over the default namer, so callers stay in\n * control of their output folders. Returns `null` when grouping is disabled, matching the\n * per-plugin convention.\n *\n * @param group - The user-supplied group option, or `undefined` to disable grouping.\n *\n * @example\n * ```ts\n * createGroupConfig(group) // shared across every plugin\n * ```\n */\nexport function createGroupConfig(group: Group | undefined): Group | null {\n if (!group) {\n return null\n }\n\n const defaultName = (ctx: { group: string }): string => {\n if (group.type === 'path') {\n return `${ctx.group.split('/')[1]}`\n }\n\n return camelCase(ctx.group)\n }\n\n return {\n ...group,\n name: group.name ? group.name : defaultName,\n } satisfies Group\n}\n","import { ast, defineGenerator } from 'kubb/kit'\nimport type { PluginMsw } from '../types'\n\n/**\n * Aggregate generator enabled by `pluginMsw({ handlers: true })`. Emits a\n * `handlers.ts` file that re-exports every generated handler in operation\n * order, ready to spread into `setupServer(...handlers)` or\n * `setupWorker(...handlers)`.\n */\nexport const handlersGenerator = defineGenerator<PluginMsw>({\n name: 'plugin-msw',\n operations(nodes, ctx) {\n const { resolver, config, root } = ctx\n const { output, group } = ctx.options\n\n const handlersName = resolver.handler.listName()\n const file = resolver.file({ name: handlersName, extname: '.ts', root, output, group: group ?? undefined })\n\n const imports = nodes.map((node) => {\n const operationName = resolver.handler.name(node)\n const operationFile = resolver.file({\n name: resolver.name(node.operationId),\n extname: '.ts',\n tag: node.tags[0] ?? 'default',\n path: node.path,\n root,\n output,\n group: group ?? undefined,\n })\n return ast.factory.createImport({ name: [operationName], root: file.path, path: operationFile.path })\n })\n\n const handlers = nodes.map((node) => `${resolver.handler.name(node)}()`)\n\n return [\n ast.factory.createFile({\n baseName: file.baseName,\n path: file.path,\n meta: file.meta,\n banner: resolver.default.banner(ctx.meta, { output, config, file: { path: file.path, baseName: file.baseName } }),\n footer: resolver.default.footer(ctx.meta, { output, config, file: { path: file.path, baseName: file.baseName } }),\n imports,\n sources: [\n ast.factory.createSource({\n name: handlersName,\n isIndexable: true,\n isExportable: true,\n nodes: [ast.factory.createText(`export const ${handlersName} = ${JSON.stringify(handlers).replaceAll('\"', '')} as const`)],\n }),\n ],\n }),\n ]\n },\n})\n","import { ast } from 'kubb/kit'\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?.find((entry) => entry.schema)?.schema\n return !!schema && schema.type !== 'void' && schema.type !== 'any'\n}\n\n/**\n * Picks the content type used for the mocked response header. When a response declares multiple\n * content types, JSON is preferred (the faker mock body is JSON), otherwise the first declared type.\n */\nfunction getResponseContentType(response: ast.ResponseNode | null | undefined): string | null {\n const contents = response?.content ?? []\n const jsonEntry = contents.find((entry) => {\n const baseType = entry.contentType?.split(';')[0]?.trim().toLowerCase()\n return baseType === 'application/json' || baseType?.endsWith('+json')\n })\n const value = (jsonEntry ?? contents[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 ast.isHttpOperationNode(node) ? node.method.toLowerCase() : ''\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.response.response(node),\n file: fakerResolver.file({ name: node.operationId, extname: '.ts', tag, path: node.path, root, output: fakerOutput, group: fakerGroup ?? undefined }),\n }\n}\n","import { getPrimarySuccessResponse } from '@internals/shared'\nimport { ast, Url } from 'kubb/kit'\nimport { createFunctionParameter, createFunctionParameters, functionPrinter } from '@kubb/plugin-ts'\nimport { File, Function } from 'kubb/jsx'\nimport type { KubbReactNode } from 'kubb/jsx'\nimport { getContentType, getMswMethod, hasResponseSchema } 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 Mock({ 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 = ast.isHttpOperationNode(node) ? Url.toPath(node.path) : ''\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 const paramType = fakerName ? typeName : dataType\n\n const callbackType = requestTypeName\n ? `HttpResponseResolver<Record<string, string>, ${requestTypeName}>`\n : `((info: Parameters<Parameters<typeof http.${method}>[1]>[0]) => Response | Promise<Response>)`\n\n const params = declarationPrinter.print(\n createFunctionParameters({\n params: [\n createFunctionParameter({\n name: 'data',\n type: `${paramType} | ${callbackType}`,\n optional: true,\n }),\n ],\n }),\n )\n\n const httpCall = requestTypeName ? `http.${method}<Record<string, string>, ${requestTypeName}>` : `http.${method}`\n\n const requestUrl = `${baseURL}${url.replace(/([^/]):/g, '$1\\\\\\\\:')}`\n const urlLiteral = fakerName ? `'${requestUrl}'` : `\\`${requestUrl}\\``\n const responseBody = fakerName ? `JSON.stringify(data || ${fakerName}(data))` : 'JSON.stringify(data)'\n\n return (\n <File.Source name={name} isIndexable isExportable>\n <Function name={name} export params={params ?? ''}>\n {`return ${httpCall}(${urlLiteral}, function handler(info) {\n if(typeof data === 'function') return data(info)\n\n return new Response(${responseBody}, {\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 type { ast } from 'kubb/kit'\nimport { createFunctionParameter, createFunctionParameters, functionPrinter } from '@kubb/plugin-ts'\nimport { File, Function } from 'kubb/jsx'\nimport type { KubbReactNode } from 'kubb/jsx'\nimport { getContentType, hasResponseSchema } from '../utils.ts'\n\ntype Props = {\n typeName: string\n name: string\n response: ast.ResponseNode\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 createFunctionParameters({\n params: [\n createFunctionParameter({\n name: 'data',\n type: 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","import { getOperationSuccessResponses, resolveResponseTypes } from '@internals/shared'\nimport { ast, defineGenerator } from 'kubb/kit'\nimport { pluginFakerName } from '@kubb/plugin-faker'\nimport { pluginTsName } from '@kubb/plugin-ts'\nimport { File, jsxRenderer } from 'kubb/jsx'\nimport { Mock, Response } from '../components'\nimport type { PluginMsw } from '../types'\nimport { resolveFakerMeta } from '../utils.ts'\n\n/**\n * Built-in operation generator for `@kubb/plugin-msw`. Emits one MSW handler\n * per OpenAPI operation. With `parser: 'faker'` the handler returns a value\n * from `@kubb/plugin-faker`; with `parser: 'data'` it returns a typed empty\n * payload for tests to fill in.\n */\nexport const mswGenerator = defineGenerator<PluginMsw>({\n name: 'msw',\n renderer: jsxRenderer,\n operation(node, ctx) {\n if (!ast.isHttpOperationNode(node)) return null\n const { driver, resolver, config, root } = ctx\n const { output, parser, baseURL, group } = ctx.options\n\n const fileName = resolver.name(node.operationId)\n const mock = {\n name: resolver.handler.name(node),\n file: resolver.file({ name: fileName, extname: '.ts', tag: node.tags[0] ?? 'default', path: node.path, root, output, group: group ?? undefined }),\n }\n\n const fakerPlugin = parser === 'faker' ? driver.getPlugin(pluginFakerName) : null\n const faker =\n parser === 'faker' && fakerPlugin\n ? resolveFakerMeta(node, {\n root,\n fakerResolver: driver.getResolver(pluginFakerName),\n fakerOutput: fakerPlugin.options?.output ?? output,\n fakerGroup: fakerPlugin.options?.group ?? null,\n })\n : null\n\n const pluginTs = driver.getPlugin(pluginTsName)\n if (!pluginTs) return null\n const tsResolver = driver.getResolver(pluginTsName)\n\n const type = {\n file: tsResolver.file({\n name: node.operationId,\n extname: '.ts',\n tag: node.tags[0] ?? 'default',\n path: node.path,\n root,\n output: pluginTs.options?.output ?? output,\n group: pluginTs.options?.group ?? undefined,\n }),\n responseName: tsResolver.response.response(node),\n }\n\n const types = resolveResponseTypes(node, tsResolver)\n const successResponses = getOperationSuccessResponses(node)\n const hasSuccessSchema = successResponses.some((response) => !!response.content?.[0]?.schema)\n\n const requestName = node.requestBody?.content?.[0]?.schema ? tsResolver.response.body(node) : null\n\n return (\n <File\n baseName={mock.file.baseName}\n path={mock.file.path}\n meta={mock.file.meta}\n banner={resolver.default.banner(ctx.meta, { output, config, file: { path: mock.file.path, baseName: mock.file.baseName } })}\n footer={resolver.default.footer(ctx.meta, { output, config, file: { path: mock.file.path, baseName: mock.file.baseName } })}\n >\n <File.Import name={['http']} path=\"msw\" />\n <File.Import name={['HttpResponseResolver']} isTypeOnly path=\"msw\" />\n <File.Import\n name={Array.from(new Set([type.responseName, ...types.map((t) => t[1]), ...(requestName ? [requestName] : [])]))}\n path={type.file.path}\n root={mock.file.path}\n isTypeOnly\n />\n {parser === 'faker' && faker && <File.Import name={[faker.name]} root={mock.file.path} path={faker.file.path} />}\n\n {types\n .filter(([code]) => code !== 'default')\n .map(([code, typeName]) => {\n const response = node.responses.find((item) => item.statusCode === String(code))\n if (!response) return null\n return <Response key={typeName} typeName={typeName} response={response} name={mock.name} />\n })}\n\n {parser === 'faker' && faker && hasSuccessSchema ? (\n <Mock name={mock.name} typeName={type.responseName} requestTypeName={requestName} fakerName={faker.name} node={node} baseURL={baseURL} />\n ) : (\n <Mock name={mock.name} typeName={type.responseName} requestTypeName={requestName} node={node} baseURL={baseURL} />\n )}\n </File>\n )\n },\n})\n","import { camelCase } from '@internals/utils'\nimport { createResolver } from 'kubb/kit'\nimport type { PluginMsw } from '../types.ts'\n\n/**\n * Default resolver used by `@kubb/plugin-msw`. Decides the names and file\n * paths for every generated MSW handler. Function names get a `Handler`\n * suffix; the aggregate export is always `handlers`.\n *\n * The top-level `name` applies the `handler` suffix, and `file` falls back to the built-in\n * `toFilePath` casing. Operation-specific naming is grouped under the `handler` namespace.\n *\n * @example Resolve a handler name\n * ```ts\n * import { resolverMsw } from '@kubb/plugin-msw'\n *\n * resolverMsw.name('addPet') // 'addPetHandler'\n * ```\n */\nexport const resolverMsw = createResolver<PluginMsw>({\n pluginName: 'plugin-msw',\n name(name) {\n return camelCase(name, { suffix: 'handler' })\n },\n handler: {\n name(node) {\n return this.name(node.operationId)\n },\n listName() {\n return 'handlers'\n },\n },\n})\n","import { createGroupConfig } from '@internals/shared'\nimport { definePlugin, Resolver } from 'kubb/kit'\nimport { pluginFakerName } from '@kubb/plugin-faker'\nimport { pluginTsName } from '@kubb/plugin-ts'\nimport { handlersGenerator, mswGenerator } from './generators'\nimport { resolverMsw } from './resolvers/resolverMsw.ts'\nimport type { PluginMsw, ResolverMsw } from './types.ts'\n\n/**\n * Canonical plugin name for `@kubb/plugin-msw`. Used for driver lookups and\n * cross-plugin dependency references.\n */\nexport const pluginMswName = 'plugin-msw' satisfies PluginMsw['name']\n\n/**\n * Generates MSW request handlers from an OpenAPI spec. Drop them into your\n * test setup or service worker to mock the API end-to-end. Request path,\n * method, status, and response body all stay in sync with the spec. Combine\n * with `@kubb/plugin-faker` (via `parser: 'faker'`) to seed handlers with\n * realistic data.\n *\n * @example\n * ```ts\n * import { defineConfig } from 'kubb/config'\n * import { pluginTs } from '@kubb/plugin-ts'\n * import { pluginMsw } from '@kubb/plugin-msw'\n *\n * export default defineConfig({\n * input: './petStore.yaml',\n * output: { path: './src/gen' },\n * plugins: [\n * pluginTs(),\n * pluginMsw({\n * output: { path: './handlers' },\n * handlers: true,\n * }),\n * ],\n * })\n * ```\n */\nexport const pluginMsw = definePlugin<PluginMsw>((options) => {\n const {\n output = { path: 'handlers', barrel: { type: 'named' } },\n group,\n exclude = [],\n include,\n override = [],\n handlers = false,\n parser = 'data',\n baseURL,\n resolver: userResolver,\n macros: userMacros,\n } = options\n\n const groupConfig = createGroupConfig(group)\n\n return {\n name: pluginMswName,\n options,\n dependencies: [pluginTsName, parser === 'faker' ? pluginFakerName : null].filter((dependency): dependency is string => Boolean(dependency)),\n hooks: {\n 'kubb:plugin:setup'(ctx) {\n const resolver = userResolver ? Resolver.merge<ResolverMsw>(resolverMsw, userResolver) : resolverMsw\n\n ctx.setOptions({\n output,\n parser,\n baseURL,\n group: groupConfig,\n exclude,\n include,\n override,\n handlers,\n resolver,\n })\n ctx.setResolver(resolver)\n if (userMacros?.length) {\n ctx.setMacros(userMacros)\n }\n\n ctx.addGenerator(mswGenerator)\n if (handlers) {\n ctx.addGenerator(handlersGenerator)\n }\n },\n },\n }\n})\n\nexport default pluginMsw\n"],"mappings":";;;;;;;AA0ZA,SAAgB,oBAAoB,YAA6D;CAC/F,MAAM,OAAO,OAAO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/plugin-msw",
3
- "version": "5.0.0-alpha.9",
4
- "description": "Mock Service Worker (MSW) handlers generator plugin for Kubb, creating API mocks from OpenAPI specifications for frontend development and testing.",
3
+ "version": "5.0.0-beta.100",
4
+ "description": "Generate Mock Service Worker (MSW) request handlers with Kubb. Intercept HTTP requests in the browser or Node.js for frontend development and testing.",
5
5
  "keywords": [
6
- "msw",
7
- "mock-service-worker",
8
6
  "api-mocking",
7
+ "code-generation",
8
+ "codegen",
9
+ "kubb",
10
+ "meta-framework",
11
+ "mock-service-worker",
9
12
  "mocking",
10
13
  "mocks",
11
- "testing",
12
- "development",
13
- "interceptor",
14
- "typescript",
15
- "openapi",
16
- "swagger",
17
- "oas",
18
- "code-generator",
19
- "codegen",
20
- "plugins",
21
- "kubb"
14
+ "msw",
15
+ "service-worker",
16
+ "typescript"
22
17
  ],
18
+ "license": "MIT",
19
+ "author": "stijnvanhulle",
23
20
  "repository": {
24
21
  "type": "git",
25
- "url": "git+https://github.com/kubb-labs/kubb.git",
22
+ "url": "git+https://github.com/kubb-labs/plugins.git",
26
23
  "directory": "packages/plugin-msw"
27
24
  },
28
- "license": "MIT",
29
- "author": "stijnvanhulle",
30
- "sideEffects": false,
25
+ "files": [
26
+ "dist",
27
+ "!/**/**.test.**",
28
+ "!/**/__tests__/**",
29
+ "!/**/__snapshots__/**"
30
+ ],
31
31
  "type": "module",
32
- "exports": {
33
- ".": {
34
- "import": "./dist/index.js",
35
- "require": "./dist/index.cjs"
36
- },
37
- "./components": {
38
- "import": "./dist/components.js",
39
- "require": "./dist/components.cjs"
40
- },
41
- "./generators": {
42
- "import": "./dist/generators.js",
43
- "require": "./dist/generators.cjs"
44
- },
45
- "./package.json": "./package.json"
46
- },
32
+ "sideEffects": false,
33
+ "main": "./dist/index.cjs",
34
+ "module": "./dist/index.js",
47
35
  "types": "./dist/index.d.ts",
48
36
  "typesVersions": {
49
37
  "*": {
@@ -61,47 +49,37 @@
61
49
  ]
62
50
  }
63
51
  },
64
- "files": [
65
- "src",
66
- "dist",
67
- "!/**/**.test.**",
68
- "!/**/__tests__/**",
69
- "!/**/__snapshots__/**"
70
- ],
71
- "size-limit": [
72
- {
73
- "path": "./dist/*.js",
74
- "limit": "510 KiB",
75
- "gzip": true
76
- }
77
- ],
52
+ "exports": {
53
+ ".": {
54
+ "import": "./dist/index.js",
55
+ "require": "./dist/index.cjs"
56
+ },
57
+ "./package.json": "./package.json"
58
+ },
59
+ "publishConfig": {
60
+ "access": "public",
61
+ "registry": "https://registry.npmjs.org/"
62
+ },
78
63
  "dependencies": {
79
- "@kubb/react-fabric": "0.14.0",
80
- "@kubb/core": "5.0.0-alpha.9",
81
- "@kubb/oas": "5.0.0-alpha.9",
82
- "@kubb/plugin-oas": "5.0.0-alpha.9",
83
- "@kubb/plugin-faker": "5.0.0-alpha.9",
84
- "@kubb/plugin-ts": "5.0.0-alpha.9"
64
+ "@kubb/plugin-faker": "5.0.0-beta.99",
65
+ "@kubb/plugin-ts": "5.0.0-beta.99"
85
66
  },
86
67
  "devDependencies": {
68
+ "kubb": "5.0.0-beta.98",
69
+ "@internals/shared": "0.0.0",
87
70
  "@internals/utils": "0.0.0"
88
71
  },
72
+ "peerDependencies": {
73
+ "kubb": "5.0.0-beta.98"
74
+ },
89
75
  "engines": {
90
76
  "node": ">=22"
91
77
  },
92
- "publishConfig": {
93
- "access": "public",
94
- "registry": "https://registry.npmjs.org/"
95
- },
96
- "main": "./dist/index.cjs",
97
- "module": "./dist/index.js",
98
78
  "scripts": {
99
- "build": "tsdown && size-limit",
100
- "clean": "npx rimraf ./dist",
101
- "lint": "bun biome lint .",
102
- "lint:fix": "bun biome lint --fix --unsafe .",
103
- "release": "pnpm publish --no-git-check",
104
- "release:canary": "bash ../../.github/canary.sh && node ../../scripts/build.js canary && pnpm publish --no-git-check",
79
+ "build": "tsdown",
80
+ "clean": "node -e \"require('node:fs').rmSync('./dist', {recursive:true,force:true})\"",
81
+ "lint": "oxlint .",
82
+ "lint:fix": "oxlint --fix .",
105
83
  "start": "tsdown --watch",
106
84
  "test": "vitest --passWithNoTests",
107
85
  "typecheck": "tsc -p ./tsconfig.json --noEmit --emitDeclarationOnly false"
@@ -1,343 +0,0 @@
1
- //#region \0rolldown/runtime.js
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __name = (target, value) => __defProp(target, "name", {
5
- value,
6
- configurable: true
7
- });
8
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
9
- var __getOwnPropNames = Object.getOwnPropertyNames;
10
- var __getProtoOf = Object.getPrototypeOf;
11
- var __hasOwnProp = Object.prototype.hasOwnProperty;
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
14
- key = keys[i];
15
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
16
- get: ((k) => from[k]).bind(null, key),
17
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
18
- });
19
- }
20
- return to;
21
- };
22
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
23
- value: mod,
24
- enumerable: true
25
- }) : target, mod));
26
- //#endregion
27
- let _kubb_react_fabric = require("@kubb/react-fabric");
28
- let _kubb_react_fabric_jsx_runtime = require("@kubb/react-fabric/jsx-runtime");
29
- //#region ../../internals/utils/src/casing.ts
30
- /**
31
- * Shared implementation for camelCase and PascalCase conversion.
32
- * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
33
- * and capitalizes each word according to `pascal`.
34
- *
35
- * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
36
- */
37
- function toCamelOrPascal(text, pascal) {
38
- return text.trim().replace(/([a-z\d])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").replace(/(\d)([a-z])/g, "$1 $2").split(/[\s\-_./\\:]+/).filter(Boolean).map((word, i) => {
39
- if (word.length > 1 && word === word.toUpperCase()) return word;
40
- if (i === 0 && !pascal) return word.charAt(0).toLowerCase() + word.slice(1);
41
- return word.charAt(0).toUpperCase() + word.slice(1);
42
- }).join("").replace(/[^a-zA-Z0-9]/g, "");
43
- }
44
- /**
45
- * Splits `text` on `.` and applies `transformPart` to each segment.
46
- * The last segment receives `isLast = true`, all earlier segments receive `false`.
47
- * Segments are joined with `/` to form a file path.
48
- */
49
- function applyToFileParts(text, transformPart) {
50
- const parts = text.split(".");
51
- return parts.map((part, i) => transformPart(part, i === parts.length - 1)).join("/");
52
- }
53
- /**
54
- * Converts `text` to camelCase.
55
- * When `isFile` is `true`, dot-separated segments are each cased independently and joined with `/`.
56
- *
57
- * @example
58
- * camelCase('hello-world') // 'helloWorld'
59
- * camelCase('pet.petId', { isFile: true }) // 'pet/petId'
60
- */
61
- function camelCase(text, { isFile, prefix = "", suffix = "" } = {}) {
62
- if (isFile) return applyToFileParts(text, (part, isLast) => camelCase(part, isLast ? {
63
- prefix,
64
- suffix
65
- } : {}));
66
- return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false);
67
- }
68
- //#endregion
69
- //#region ../../internals/utils/src/reserved.ts
70
- /**
71
- * Returns `true` when `name` is a syntactically valid JavaScript variable name.
72
- */
73
- function isValidVarName(name) {
74
- try {
75
- new Function(`var ${name}`);
76
- } catch {
77
- return false;
78
- }
79
- return true;
80
- }
81
- //#endregion
82
- //#region ../../internals/utils/src/urlPath.ts
83
- /**
84
- * Parses and transforms an OpenAPI/Swagger path string into various URL formats.
85
- *
86
- * @example
87
- * const p = new URLPath('/pet/{petId}')
88
- * p.URL // '/pet/:petId'
89
- * p.template // '`/pet/${petId}`'
90
- */
91
- var URLPath = class {
92
- /** The raw OpenAPI/Swagger path string, e.g. `/pet/{petId}`. */
93
- path;
94
- #options;
95
- constructor(path, options = {}) {
96
- this.path = path;
97
- this.#options = options;
98
- }
99
- /** Converts the OpenAPI path to Express-style colon syntax, e.g. `/pet/{petId}` → `/pet/:petId`. */
100
- get URL() {
101
- return this.toURLPath();
102
- }
103
- /** Returns `true` when `path` is a fully-qualified URL (e.g. starts with `https://`). */
104
- get isURL() {
105
- try {
106
- return !!new URL(this.path).href;
107
- } catch {
108
- return false;
109
- }
110
- }
111
- /**
112
- * Converts the OpenAPI path to a TypeScript template literal string.
113
- *
114
- * @example
115
- * new URLPath('/pet/{petId}').template // '`/pet/${petId}`'
116
- * new URLPath('/account/monetary-accountID').template // '`/account/${monetaryAccountId}`'
117
- */
118
- get template() {
119
- return this.toTemplateString();
120
- }
121
- /** Returns the path and its extracted params as a structured `URLObject`, or as a stringified expression when `stringify` is set. */
122
- get object() {
123
- return this.toObject();
124
- }
125
- /** Returns a map of path parameter names, or `undefined` when the path has no parameters. */
126
- get params() {
127
- return this.getParams();
128
- }
129
- #transformParam(raw) {
130
- const param = isValidVarName(raw) ? raw : camelCase(raw);
131
- return this.#options.casing === "camelcase" ? camelCase(param) : param;
132
- }
133
- /** Iterates over every `{param}` token in `path`, calling `fn` with the raw token and transformed name. */
134
- #eachParam(fn) {
135
- for (const match of this.path.matchAll(/\{([^}]+)\}/g)) {
136
- const raw = match[1];
137
- fn(raw, this.#transformParam(raw));
138
- }
139
- }
140
- toObject({ type = "path", replacer, stringify } = {}) {
141
- const object = {
142
- url: type === "path" ? this.toURLPath() : this.toTemplateString({ replacer }),
143
- params: this.getParams()
144
- };
145
- if (stringify) {
146
- if (type === "template") return JSON.stringify(object).replaceAll("'", "").replaceAll(`"`, "");
147
- if (object.params) return `{ url: '${object.url}', params: ${JSON.stringify(object.params).replaceAll("'", "").replaceAll(`"`, "")} }`;
148
- return `{ url: '${object.url}' }`;
149
- }
150
- return object;
151
- }
152
- /**
153
- * Converts the OpenAPI path to a TypeScript template literal string.
154
- * An optional `replacer` can transform each extracted parameter name before interpolation.
155
- *
156
- * @example
157
- * new URLPath('/pet/{petId}').toTemplateString() // '`/pet/${petId}`'
158
- */
159
- toTemplateString({ prefix = "", replacer } = {}) {
160
- return `\`${prefix}${this.path.split(/\{([^}]+)\}/).map((part, i) => {
161
- if (i % 2 === 0) return part;
162
- const param = this.#transformParam(part);
163
- return `\${${replacer ? replacer(param) : param}}`;
164
- }).join("")}\``;
165
- }
166
- /**
167
- * Extracts all `{param}` segments from the path and returns them as a key-value map.
168
- * An optional `replacer` transforms each parameter name in both key and value positions.
169
- * Returns `undefined` when no path parameters are found.
170
- */
171
- getParams(replacer) {
172
- const params = {};
173
- this.#eachParam((_raw, param) => {
174
- const key = replacer ? replacer(param) : param;
175
- params[key] = key;
176
- });
177
- return Object.keys(params).length > 0 ? params : void 0;
178
- }
179
- /** Converts the OpenAPI path to Express-style colon syntax, e.g. `/pet/{petId}` → `/pet/:petId`. */
180
- toURLPath() {
181
- return this.path.replace(/\{([^}]+)\}/g, ":$1");
182
- }
183
- };
184
- //#endregion
185
- //#region src/components/Handlers.tsx
186
- function Handlers({ name, handlers }) {
187
- return /* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsx)(_kubb_react_fabric.File.Source, {
188
- name,
189
- isIndexable: true,
190
- isExportable: true,
191
- children: `export const ${name} = ${JSON.stringify(handlers).replaceAll(`"`, "")} as const`
192
- });
193
- }
194
- //#endregion
195
- //#region src/components/Mock.tsx
196
- function Mock({ baseURL = "", name, typeName, operation }) {
197
- const method = operation.method;
198
- const successStatusCodes = operation.getResponseStatusCodes().filter((code) => code.startsWith("2"));
199
- const statusCode = successStatusCodes.length > 0 ? Number(successStatusCodes[0]) : 200;
200
- const responseObject = operation.getResponseByStatusCode(statusCode);
201
- const contentType = Object.keys(responseObject.content || {})?.[0];
202
- const url = new URLPath(operation.path).toURLPath().replace(/([^/]):/g, "$1\\\\:");
203
- const headers = [contentType ? `'Content-Type': '${contentType}'` : void 0].filter(Boolean);
204
- const dataType = contentType && responseObject?.content?.[contentType]?.schema !== void 0 ? typeName : "string | number | boolean | null | object";
205
- const params = _kubb_react_fabric.FunctionParams.factory({ data: {
206
- type: `${dataType} | ((
207
- info: Parameters<Parameters<typeof http.${method}>[1]>[0],
208
- ) => Response | Promise<Response>)`,
209
- optional: true
210
- } });
211
- return /* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsx)(_kubb_react_fabric.File.Source, {
212
- name,
213
- isIndexable: true,
214
- isExportable: true,
215
- children: /* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsx)(_kubb_react_fabric.Function, {
216
- name,
217
- export: true,
218
- params: params.toConstructor(),
219
- children: `return http.${method}(\`${baseURL}${url.replace(/([^/]):/g, "$1\\\\:")}\`, function handler(info) {
220
- if(typeof data === 'function') return data(info)
221
-
222
- return new Response(JSON.stringify(data), {
223
- status: ${statusCode},
224
- ${headers.length ? ` headers: {
225
- ${headers.join(", \n")}
226
- },` : ""}
227
- })
228
- })`
229
- })
230
- });
231
- }
232
- //#endregion
233
- //#region src/components/MockWithFaker.tsx
234
- function MockWithFaker({ baseURL = "", name, fakerName, typeName, operation }) {
235
- const method = operation.method;
236
- const successStatusCodes = operation.getResponseStatusCodes().filter((code) => code.startsWith("2"));
237
- const statusCode = successStatusCodes.length > 0 ? Number(successStatusCodes[0]) : 200;
238
- const responseObject = operation.getResponseByStatusCode(statusCode);
239
- const contentType = Object.keys(responseObject.content || {})?.[0];
240
- const url = new URLPath(operation.path).toURLPath().replace(/([^/]):/g, "$1\\\\:");
241
- const headers = [contentType ? `'Content-Type': '${contentType}'` : void 0].filter(Boolean);
242
- const params = _kubb_react_fabric.FunctionParams.factory({ data: {
243
- type: `${typeName} | ((
244
- info: Parameters<Parameters<typeof http.${method}>[1]>[0],
245
- ) => Response | Promise<Response>)`,
246
- optional: true
247
- } });
248
- return /* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsx)(_kubb_react_fabric.File.Source, {
249
- name,
250
- isIndexable: true,
251
- isExportable: true,
252
- children: /* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsx)(_kubb_react_fabric.Function, {
253
- name,
254
- export: true,
255
- params: params.toConstructor(),
256
- children: `return http.${method}('${baseURL}${url.replace(/([^/]):/g, "$1\\\\:")}', function handler(info) {
257
- if(typeof data === 'function') return data(info)
258
-
259
- return new Response(JSON.stringify(data || ${fakerName}(data)), {
260
- status: ${statusCode},
261
- ${headers.length ? ` headers: {
262
- ${headers.join(", \n")}
263
- },` : ""}
264
- })
265
- })`
266
- })
267
- });
268
- }
269
- //#endregion
270
- //#region src/components/Response.tsx
271
- function Response({ name, typeName, operation, statusCode }) {
272
- const responseObject = operation.getResponseByStatusCode(statusCode);
273
- const contentType = Object.keys(responseObject.content || {})?.[0];
274
- const headers = [contentType ? `'Content-Type': '${contentType}'` : void 0].filter(Boolean);
275
- const hasResponseSchema = contentType && responseObject?.content?.[contentType]?.schema !== void 0;
276
- const params = _kubb_react_fabric.FunctionParams.factory({ data: {
277
- type: `${typeName}`,
278
- optional: !hasResponseSchema
279
- } });
280
- const responseName = `${name}Response${statusCode}`;
281
- return /* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsx)(_kubb_react_fabric.File.Source, {
282
- name: responseName,
283
- isIndexable: true,
284
- isExportable: true,
285
- children: /* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsx)(_kubb_react_fabric.Function, {
286
- name: responseName,
287
- export: true,
288
- params: params.toConstructor(),
289
- children: `
290
- return new Response(JSON.stringify(data), {
291
- status: ${statusCode},
292
- ${headers.length ? ` headers: {
293
- ${headers.join(", \n")}
294
- },` : ""}
295
- })`
296
- })
297
- });
298
- }
299
- //#endregion
300
- Object.defineProperty(exports, "Handlers", {
301
- enumerable: true,
302
- get: function() {
303
- return Handlers;
304
- }
305
- });
306
- Object.defineProperty(exports, "Mock", {
307
- enumerable: true,
308
- get: function() {
309
- return Mock;
310
- }
311
- });
312
- Object.defineProperty(exports, "MockWithFaker", {
313
- enumerable: true,
314
- get: function() {
315
- return MockWithFaker;
316
- }
317
- });
318
- Object.defineProperty(exports, "Response", {
319
- enumerable: true,
320
- get: function() {
321
- return Response;
322
- }
323
- });
324
- Object.defineProperty(exports, "__name", {
325
- enumerable: true,
326
- get: function() {
327
- return __name;
328
- }
329
- });
330
- Object.defineProperty(exports, "__toESM", {
331
- enumerable: true,
332
- get: function() {
333
- return __toESM;
334
- }
335
- });
336
- Object.defineProperty(exports, "camelCase", {
337
- enumerable: true,
338
- get: function() {
339
- return camelCase;
340
- }
341
- });
342
-
343
- //# sourceMappingURL=components-8XBwMbFa.cjs.map