@kubb/plugin-swr 5.0.0-alpha.34 → 5.0.0-alpha.35

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.
Files changed (41) hide show
  1. package/dist/components-BJSzUg7M.cjs +955 -0
  2. package/dist/components-BJSzUg7M.cjs.map +1 -0
  3. package/dist/components-JQ2KRFCa.js +877 -0
  4. package/dist/components-JQ2KRFCa.js.map +1 -0
  5. package/dist/components.cjs +1 -1
  6. package/dist/components.d.ts +77 -37
  7. package/dist/components.js +1 -1
  8. package/dist/generators-17ulS9mu.cjs +537 -0
  9. package/dist/generators-17ulS9mu.cjs.map +1 -0
  10. package/dist/generators-Cl7nr-FB.js +526 -0
  11. package/dist/generators-Cl7nr-FB.js.map +1 -0
  12. package/dist/generators.cjs +1 -1
  13. package/dist/generators.d.ts +4 -4
  14. package/dist/generators.js +1 -1
  15. package/dist/index.cjs +132 -110
  16. package/dist/index.cjs.map +1 -1
  17. package/dist/index.d.ts +22 -2
  18. package/dist/index.js +132 -110
  19. package/dist/index.js.map +1 -1
  20. package/dist/{types-BVDtH9S7.d.ts → types-FA5mH9Ch.d.ts} +46 -90
  21. package/package.json +7 -11
  22. package/src/components/Mutation.tsx +165 -170
  23. package/src/components/MutationKey.tsx +50 -1
  24. package/src/components/Query.tsx +122 -126
  25. package/src/components/QueryKey.tsx +65 -1
  26. package/src/components/QueryOptions.tsx +38 -93
  27. package/src/generators/mutationGenerator.tsx +194 -117
  28. package/src/generators/queryGenerator.tsx +205 -139
  29. package/src/plugin.ts +117 -152
  30. package/src/resolvers/resolverSwr.ts +26 -0
  31. package/src/resolvers/resolverSwrLegacy.ts +17 -0
  32. package/src/types.ts +55 -18
  33. package/src/utils.ts +209 -0
  34. package/dist/components-DaCTPplv.js +0 -756
  35. package/dist/components-DaCTPplv.js.map +0 -1
  36. package/dist/components-Qs8_faOt.cjs +0 -834
  37. package/dist/components-Qs8_faOt.cjs.map +0 -1
  38. package/dist/generators-0YayIrse.js +0 -400
  39. package/dist/generators-0YayIrse.js.map +0 -1
  40. package/dist/generators-Bd4rCa3l.cjs +0 -411
  41. package/dist/generators-Bd4rCa3l.cjs.map +0 -1
@@ -1,25 +1,27 @@
1
- import type { Params } from '@kubb/core'
2
- import { FunctionParams } from '@kubb/core'
3
- import { isOptional, type Operation } from '@kubb/oas'
4
- import { ClientLegacy as Client } from '@kubb/plugin-client'
5
- import type { OperationSchemas } from '@kubb/plugin-oas'
6
- import { getComments, getPathParams } from '@kubb/plugin-oas/utils'
1
+ import { ast } from '@kubb/core'
2
+ import type { PluginTs } from '@kubb/plugin-ts'
3
+ import { functionPrinter } from '@kubb/plugin-ts'
7
4
  import { File, Function, Type } from '@kubb/renderer-jsx'
8
5
  import type { KubbReactNode } from '@kubb/renderer-jsx/types'
9
6
  import type { PluginSwr } from '../types.ts'
10
- import { MutationKey } from './MutationKey.tsx'
7
+ import {
8
+ buildGroupParam,
9
+ buildMutationArgParams,
10
+ getComments,
11
+ resolveErrorNames,
12
+ resolveHeaderGroupType,
13
+ resolvePathParamType,
14
+ resolveQueryGroupType,
15
+ } from '../utils.ts'
11
16
 
12
17
  type Props = {
13
- /**
14
- * Name of the function
15
- */
16
18
  name: string
17
19
  typeName: string
18
20
  clientName: string
19
21
  mutationKeyName: string
20
22
  mutationKeyTypeName: string
21
- typeSchemas: OperationSchemas
22
- operation: Operation
23
+ node: ast.OperationNode
24
+ tsResolver: PluginTs['resolver']
23
25
  paramsCasing: PluginSwr['resolvedOptions']['paramsCasing']
24
26
  paramsType: PluginSwr['resolvedOptions']['paramsType']
25
27
  dataReturnType: PluginSwr['resolvedOptions']['client']['dataReturnType']
@@ -31,102 +33,118 @@ type Props = {
31
33
  paramsToTrigger?: boolean
32
34
  }
33
35
 
34
- type GetParamsProps = {
35
- paramsCasing: PluginSwr['resolvedOptions']['paramsCasing']
36
- pathParamsType: PluginSwr['resolvedOptions']['pathParamsType']
37
- dataReturnType: PluginSwr['resolvedOptions']['client']['dataReturnType']
38
- typeSchemas: OperationSchemas
39
- mutationKeyTypeName: string
40
- }
36
+ const declarationPrinter = functionPrinter({ mode: 'declaration' })
37
+ const callPrinter = functionPrinter({ mode: 'call' })
38
+ const keysPrinter = functionPrinter({ mode: 'keys' })
39
+
40
+ /**
41
+ * Default mutation hook params (paramsToTrigger=false):
42
+ * pathParams + queryParams + headers + options (NO data — it comes via useSWRMutation arg)
43
+ */
44
+ function getParams(
45
+ node: ast.OperationNode,
46
+ options: {
47
+ paramsCasing: PluginSwr['resolvedOptions']['paramsCasing']
48
+ pathParamsType: PluginSwr['resolvedOptions']['pathParamsType']
49
+ dataReturnType: PluginSwr['resolvedOptions']['client']['dataReturnType']
50
+ resolver: PluginTs['resolver']
51
+ mutationKeyTypeName: string
52
+ },
53
+ ): ast.FunctionParametersNode {
54
+ const { paramsCasing, pathParamsType, dataReturnType, resolver, mutationKeyTypeName } = options
55
+
56
+ const responseName = resolver.resolveResponseName(node)
57
+ const requestName = node.requestBody?.schema ? resolver.resolveDataName(node) : undefined
58
+ const errorNames = resolveErrorNames(node, resolver)
59
+
60
+ const TData = dataReturnType === 'data' ? responseName : `ResponseConfig<${responseName}>`
61
+ const TError = `ResponseErrorConfig<${errorNames.length > 0 ? errorNames.join(' | ') : 'Error'}>`
62
+ const TExtraArg = requestName || 'never'
63
+
64
+ const casedParams = ast.caseParams(node.parameters, paramsCasing)
65
+ const pathParams = casedParams.filter((p) => p.in === 'path')
66
+ const queryParams = casedParams.filter((p) => p.in === 'query')
67
+ const headerParams = casedParams.filter((p) => p.in === 'header')
68
+
69
+ const queryGroupType = resolveQueryGroupType(node, queryParams, resolver)
70
+ const headerGroupType = resolveHeaderGroupType(node, headerParams, resolver)
41
71
 
42
- // Original getParams - used when paramsToTrigger is false (default)
43
- function getParams({ pathParamsType, paramsCasing, dataReturnType, typeSchemas, mutationKeyTypeName }: GetParamsProps) {
44
- const TData = dataReturnType === 'data' ? typeSchemas.response.name : `ResponseConfig<${typeSchemas.response.name}>`
45
- const TError = `ResponseErrorConfig<${typeSchemas.errors?.map((item) => item.name).join(' | ') || 'Error'}>`
46
- const TExtraArg = typeSchemas.request?.name || 'never'
47
-
48
- return FunctionParams.factory({
49
- pathParams: {
50
- mode: pathParamsType === 'object' ? 'object' : 'inlineSpread',
51
- children: getPathParams(typeSchemas.pathParams, { typed: true, casing: paramsCasing }),
52
- },
53
- params: typeSchemas.queryParams?.name
54
- ? {
55
- type: typeSchemas.queryParams?.name,
56
- optional: isOptional(typeSchemas.queryParams?.schema),
57
- }
58
- : undefined,
59
- headers: typeSchemas.headerParams?.name
60
- ? {
61
- type: typeSchemas.headerParams?.name,
62
- optional: isOptional(typeSchemas.headerParams?.schema),
63
- }
64
- : undefined,
65
- options: {
66
- type: `
67
- {
72
+ const params: Array<ast.FunctionParameterNode | ast.ParameterGroupNode> = []
73
+
74
+ // Path params
75
+ if (pathParams.length) {
76
+ const pathChildren = pathParams.map((p) =>
77
+ ast.createFunctionParameter({ name: p.name, type: resolvePathParamType(node, p, resolver), optional: !p.required }),
78
+ )
79
+ params.push({
80
+ kind: 'ParameterGroup',
81
+ properties: pathChildren,
82
+ inline: pathParamsType === 'inline',
83
+ default: pathChildren.every((c) => c.optional) ? '{}' : undefined,
84
+ })
85
+ }
86
+
87
+ // Query params
88
+ params.push(...buildGroupParam('params', node, queryParams, queryGroupType, resolver))
89
+
90
+ // Header params
91
+ params.push(...buildGroupParam('headers', node, headerParams, headerGroupType, resolver))
92
+
93
+ // Options
94
+ params.push(
95
+ ast.createFunctionParameter({
96
+ name: 'options',
97
+ type: ast.createParamsType({
98
+ variant: 'reference',
99
+ name: `{
68
100
  mutation?: SWRMutationConfiguration<${TData}, ${TError}, ${mutationKeyTypeName} | null, ${TExtraArg}> & { throwOnError?: boolean },
69
- client?: ${typeSchemas.request?.name ? `Partial<RequestConfig<${typeSchemas.request?.name}>> & { client?: Client }` : 'Partial<RequestConfig> & { client?: Client }'},
101
+ client?: ${requestName ? `Partial<RequestConfig<${requestName}>> & { client?: Client }` : 'Partial<RequestConfig> & { client?: Client }'},
70
102
  shouldFetch?: boolean,
71
- }
72
- `,
103
+ }`,
104
+ }),
73
105
  default: '{}',
74
- },
75
- })
76
- }
106
+ }),
107
+ )
77
108
 
78
- type GetTriggerParamsProps = {
79
- dataReturnType: PluginSwr['resolvedOptions']['client']['dataReturnType']
80
- typeSchemas: OperationSchemas
81
- mutationKeyTypeName: string
82
- mutationArgTypeName: string
109
+ return ast.createFunctionParameters({ params })
83
110
  }
84
111
 
85
- // New getParams - used when paramsToTrigger is true
86
- function getTriggerParams({ dataReturnType, typeSchemas, mutationKeyTypeName, mutationArgTypeName }: GetTriggerParamsProps) {
87
- const TData = dataReturnType === 'data' ? typeSchemas.response.name : `ResponseConfig<${typeSchemas.response.name}>`
88
- const TError = `ResponseErrorConfig<${typeSchemas.errors?.map((item) => item.name).join(' | ') || 'Error'}>`
112
+ /**
113
+ * Trigger-mode params (paramsToTrigger=true): just `options`
114
+ */
115
+ function getTriggerParams(
116
+ node: ast.OperationNode,
117
+ options: {
118
+ dataReturnType: PluginSwr['resolvedOptions']['client']['dataReturnType']
119
+ resolver: PluginTs['resolver']
120
+ mutationKeyTypeName: string
121
+ mutationArgTypeName: string
122
+ },
123
+ ): ast.FunctionParametersNode {
124
+ const { dataReturnType, resolver, mutationKeyTypeName, mutationArgTypeName } = options
89
125
 
90
- return FunctionParams.factory({
91
- options: {
92
- type: `
93
- {
94
- mutation?: SWRMutationConfiguration<${TData}, ${TError}, ${mutationKeyTypeName} | null, ${mutationArgTypeName}> & { throwOnError?: boolean },
95
- client?: ${typeSchemas.request?.name ? `Partial<RequestConfig<${typeSchemas.request?.name}>> & { client?: Client }` : 'Partial<RequestConfig> & { client?: Client }'},
96
- shouldFetch?: boolean,
97
- }
98
- `,
99
- default: '{}',
100
- },
101
- })
102
- }
126
+ const responseName = resolver.resolveResponseName(node)
127
+ const requestName = node.requestBody?.schema ? resolver.resolveDataName(node) : undefined
128
+ const errorNames = resolveErrorNames(node, resolver)
103
129
 
104
- type GetMutationParamsProps = {
105
- paramsCasing: PluginSwr['resolvedOptions']['paramsCasing']
106
- typeSchemas: OperationSchemas
107
- }
130
+ const TData = dataReturnType === 'data' ? responseName : `ResponseConfig<${responseName}>`
131
+ const TError = `ResponseErrorConfig<${errorNames.length > 0 ? errorNames.join(' | ') : 'Error'}>`
108
132
 
109
- function getMutationParams({ paramsCasing, typeSchemas }: GetMutationParamsProps) {
110
- return FunctionParams.factory({
111
- ...getPathParams(typeSchemas.pathParams, { typed: true, casing: paramsCasing }),
112
- data: typeSchemas.request?.name
113
- ? {
114
- type: typeSchemas.request?.name,
115
- optional: isOptional(typeSchemas.request?.schema),
116
- }
117
- : undefined,
118
- params: typeSchemas.queryParams?.name
119
- ? {
120
- type: typeSchemas.queryParams?.name,
121
- optional: isOptional(typeSchemas.queryParams?.schema),
122
- }
123
- : undefined,
124
- headers: typeSchemas.headerParams?.name
125
- ? {
126
- type: typeSchemas.headerParams?.name,
127
- optional: isOptional(typeSchemas.headerParams?.schema),
128
- }
129
- : undefined,
133
+ return ast.createFunctionParameters({
134
+ params: [
135
+ ast.createFunctionParameter({
136
+ name: 'options',
137
+ type: ast.createParamsType({
138
+ variant: 'reference',
139
+ name: `{
140
+ mutation?: SWRMutationConfiguration<${TData}, ${TError}, ${mutationKeyTypeName} | null, ${mutationArgTypeName}> & { throwOnError?: boolean },
141
+ client?: ${requestName ? `Partial<RequestConfig<${requestName}>> & { client?: Client }` : 'Partial<RequestConfig> & { client?: Client }'},
142
+ shouldFetch?: boolean,
143
+ }`,
144
+ }),
145
+ default: '{}',
146
+ }),
147
+ ],
130
148
  })
131
149
  }
132
150
 
@@ -139,91 +157,78 @@ export function Mutation({
139
157
  paramsCasing,
140
158
  pathParamsType,
141
159
  dataReturnType,
142
- typeSchemas,
143
- operation,
160
+ node,
161
+ tsResolver,
144
162
  paramsToTrigger = false,
145
163
  }: Props): KubbReactNode {
146
- const TData = dataReturnType === 'data' ? typeSchemas.response.name : `ResponseConfig<${typeSchemas.response.name}>`
147
- const TError = `ResponseErrorConfig<${typeSchemas.errors?.map((item) => item.name).join(' | ') || 'Error'}>`
164
+ const responseName = tsResolver.resolveResponseName(node)
165
+ const requestName = node.requestBody?.schema ? tsResolver.resolveDataName(node) : undefined
166
+ const errorNames = resolveErrorNames(node, tsResolver)
148
167
 
149
- const mutationKeyParams = MutationKey.getParams({
150
- pathParamsType,
151
- typeSchemas,
152
- })
168
+ const TData = dataReturnType === 'data' ? responseName : `ResponseConfig<${responseName}>`
169
+ const TError = `ResponseErrorConfig<${errorNames.length > 0 ? errorNames.join(' | ') : 'Error'}>`
153
170
 
154
- const clientParams = Client.getParams({
155
- paramsCasing,
171
+ // Client call params (path + body + query + headers + config)
172
+ const clientCallParamsNode = ast.createOperationParams(node, {
156
173
  paramsType,
157
- typeSchemas,
158
- pathParamsType,
159
- isConfigurable: true,
174
+ pathParamsType: paramsType === 'object' ? 'object' : pathParamsType === 'object' ? 'object' : 'inline',
175
+ paramsCasing,
176
+ resolver: tsResolver,
177
+ extraParams: [
178
+ ast.createFunctionParameter({
179
+ name: 'config',
180
+ type: ast.createParamsType({
181
+ variant: 'reference',
182
+ name: requestName ? `Partial<RequestConfig<${requestName}>> & { client?: Client }` : 'Partial<RequestConfig> & { client?: Client }',
183
+ }),
184
+ default: '{}',
185
+ }),
186
+ ],
160
187
  })
188
+ const clientCallStr = callPrinter.print(clientCallParamsNode) ?? ''
161
189
 
162
- // Use the new trigger-based approach when paramsToTrigger is true
190
+ // paramsToTrigger mode
163
191
  if (paramsToTrigger) {
164
- // Build the mutation params type (for arg destructuring)
165
- const mutationParams = getMutationParams({
166
- paramsCasing,
167
- typeSchemas,
168
- })
169
-
170
- // Get the arg type name
171
192
  const mutationArgTypeName = `${mutationKeyTypeName.replace('MutationKey', '')}MutationArg`
172
193
 
173
- // Check if there are any mutation params (path, data, params, headers)
174
- const hasMutationParams = Object.keys(mutationParams.params).length > 0
175
-
176
- // Build the arg type for useSWRMutation
177
- const argParams = FunctionParams.factory({
178
- data: {
179
- mode: 'object',
180
- children: Object.entries(mutationParams.params).reduce((acc, [key, value]) => {
181
- if (value) {
182
- acc[key] = {
183
- ...value,
184
- type: undefined,
185
- }
186
- }
187
- return acc
188
- }, {} as Params),
189
- },
190
- })
194
+ const mutationArgParamsNode = buildMutationArgParams(node, { paramsCasing, resolver: tsResolver })
195
+ const hasMutationParams = mutationArgParamsNode.params.length > 0
191
196
 
192
- const params = getTriggerParams({
193
- dataReturnType,
194
- typeSchemas,
195
- mutationKeyTypeName,
196
- mutationArgTypeName,
197
- })
197
+ // Declaration for the type alias
198
+ const mutationArgDeclaration = hasMutationParams ? (declarationPrinter.print(mutationArgParamsNode) ?? '') : ''
198
199
 
199
- const generics = [TData, TError, `${mutationKeyTypeName} | null`, mutationArgTypeName].filter(Boolean)
200
+ // Destructured keys for the arg in the callback
201
+ const argKeysStr = hasMutationParams ? (keysPrinter.print(mutationArgParamsNode) ?? '') : ''
202
+
203
+ const paramsNode = getTriggerParams(node, { dataReturnType, resolver: tsResolver, mutationKeyTypeName, mutationArgTypeName })
204
+ const paramsSignature = declarationPrinter.print(paramsNode) ?? ''
200
205
 
201
- const mutationArg = mutationParams.toConstructor()
206
+ const generics = [TData, TError, `${mutationKeyTypeName} | null`, mutationArgTypeName].filter(Boolean)
202
207
 
203
208
  return (
204
209
  <>
205
210
  <File.Source name={mutationArgTypeName} isExportable isIndexable isTypeOnly>
206
211
  <Type name={mutationArgTypeName} export>
207
- {hasMutationParams ? `{${mutationArg}}` : 'never'}
212
+ {hasMutationParams ? `{${mutationArgDeclaration}}` : 'never'}
208
213
  </Type>
209
214
  </File.Source>
210
215
  <File.Source name={name} isExportable isIndexable>
211
216
  <Function
212
217
  name={name}
213
218
  export
214
- params={params.toConstructor()}
219
+ params={paramsSignature}
215
220
  JSDoc={{
216
- comments: getComments(operation),
221
+ comments: getComments(node),
217
222
  }}
218
223
  >
219
224
  {`
220
225
  const { mutation: mutationOptions, client: config = {}, shouldFetch = true } = options ?? {}
221
- const mutationKey = ${mutationKeyName}(${mutationKeyParams.toCall()})
226
+ const mutationKey = ${mutationKeyName}()
222
227
 
223
228
  return useSWRMutation<${generics.join(', ')}>(
224
229
  shouldFetch ? mutationKey : null,
225
- async (_url${hasMutationParams ? `, { arg: ${argParams.toCall()} }` : ''}) => {
226
- return ${clientName}(${clientParams.toCall()})
230
+ async (_url${hasMutationParams ? `, { arg: { ${argKeysStr} } }` : ''}) => {
231
+ return ${clientName}(${clientCallStr})
227
232
  },
228
233
  mutationOptions
229
234
  )
@@ -234,40 +239,30 @@ export function Mutation({
234
239
  )
235
240
  }
236
241
 
237
- // Original behavior (default)
238
- const generics = [
239
- TData,
240
- TError,
241
- `${mutationKeyTypeName} | null`,
242
- typeSchemas.request?.name, // TExtraArg - the arg type for useSWRMutation
243
- ].filter(Boolean)
242
+ // Default behavior (paramsToTrigger=false)
243
+ const generics = [TData, TError, `${mutationKeyTypeName} | null`, requestName].filter(Boolean)
244
244
 
245
- const params = getParams({
246
- paramsCasing,
247
- pathParamsType,
248
- dataReturnType,
249
- typeSchemas,
250
- mutationKeyTypeName,
251
- })
245
+ const paramsNode = getParams(node, { paramsCasing, pathParamsType, dataReturnType, resolver: tsResolver, mutationKeyTypeName })
246
+ const paramsSignature = declarationPrinter.print(paramsNode) ?? ''
252
247
 
253
248
  return (
254
249
  <File.Source name={name} isExportable isIndexable>
255
250
  <Function
256
251
  name={name}
257
252
  export
258
- params={params.toConstructor()}
253
+ params={paramsSignature}
259
254
  JSDoc={{
260
- comments: getComments(operation),
255
+ comments: getComments(node),
261
256
  }}
262
257
  >
263
258
  {`
264
259
  const { mutation: mutationOptions, client: config = {}, shouldFetch = true } = options ?? {}
265
- const mutationKey = ${mutationKeyName}(${mutationKeyParams.toCall()})
260
+ const mutationKey = ${mutationKeyName}()
266
261
 
267
262
  return useSWRMutation<${generics.join(', ')}>(
268
263
  shouldFetch ? mutationKey : null,
269
- async (_url${typeSchemas.request?.name ? ', { arg: data }' : ''}) => {
270
- return ${clientName}(${clientParams.toCall()})
264
+ async (_url${requestName ? ', { arg: data }' : ''}) => {
265
+ return ${clientName}(${clientCallStr})
271
266
  },
272
267
  mutationOptions
273
268
  )
@@ -1 +1,50 @@
1
- export { MutationKey } from '@internals/tanstack-query'
1
+ import { URLPath } from '@internals/utils'
2
+ import { ast } from '@kubb/core'
3
+ import { functionPrinter } from '@kubb/plugin-ts'
4
+ import { File, Function, Type } from '@kubb/renderer-jsx'
5
+ import type { KubbReactNode } from '@kubb/renderer-jsx/types'
6
+ import type { Transformer } from '../types.ts'
7
+
8
+ type Props = {
9
+ name: string
10
+ typeName: string
11
+ node: ast.OperationNode
12
+ paramsCasing: 'camelcase' | undefined
13
+ pathParamsType: 'object' | 'inline'
14
+ transformer: Transformer | undefined
15
+ }
16
+
17
+ const declarationPrinter = functionPrinter({ mode: 'declaration' })
18
+
19
+ function getParams(): ast.FunctionParametersNode {
20
+ return ast.createFunctionParameters({ params: [] })
21
+ }
22
+
23
+ const getTransformer: Transformer = ({ node, casing }) => {
24
+ const path = new URLPath(node.path, { casing })
25
+ return [`{ url: '${path.toURLPath()}' }`]
26
+ }
27
+
28
+ export function MutationKey({ name, paramsCasing, node, typeName, transformer = getTransformer }: Props): KubbReactNode {
29
+ const paramsNode = getParams()
30
+ const paramsSignature = declarationPrinter.print(paramsNode) ?? ''
31
+ const keys = transformer({ node, casing: paramsCasing })
32
+
33
+ return (
34
+ <>
35
+ <File.Source name={name} isExportable isIndexable>
36
+ <Function.Arrow name={name} export params={paramsSignature} singleLine>
37
+ {`[${keys.join(', ')}] as const`}
38
+ </Function.Arrow>
39
+ </File.Source>
40
+ <File.Source name={typeName} isExportable isIndexable isTypeOnly>
41
+ <Type name={typeName} export>
42
+ {`ReturnType<typeof ${name}>`}
43
+ </Type>
44
+ </File.Source>
45
+ </>
46
+ )
47
+ }
48
+
49
+ MutationKey.getParams = getParams
50
+ MutationKey.getTransformer = getTransformer