@azure-tools/typespec-go 0.16.0-dev.2 → 0.16.0-dev.20

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 (107) hide show
  1. package/README.md +1 -1
  2. package/dist/src/codegen/core/cloud-config.js +1 -0
  3. package/dist/src/codegen/core/cloud-config.js.map +1 -1
  4. package/dist/src/codegen/core/errors.d.ts +1 -1
  5. package/dist/src/codegen/core/errors.d.ts.map +1 -1
  6. package/dist/src/codegen/core/example.d.ts.map +1 -1
  7. package/dist/src/codegen/core/example.js +179 -19
  8. package/dist/src/codegen/core/example.js.map +1 -1
  9. package/dist/src/codegen/core/gomod.js +1 -0
  10. package/dist/src/codegen/core/gomod.js.map +1 -1
  11. package/dist/src/codegen/core/helpers.d.ts +15 -3
  12. package/dist/src/codegen/core/helpers.d.ts.map +1 -1
  13. package/dist/src/codegen/core/helpers.js +152 -22
  14. package/dist/src/codegen/core/helpers.js.map +1 -1
  15. package/dist/src/codegen/core/index.d.ts +17 -0
  16. package/dist/src/codegen/core/index.d.ts.map +1 -0
  17. package/dist/src/codegen/core/index.js +21 -0
  18. package/dist/src/codegen/core/index.js.map +1 -0
  19. package/dist/src/codegen/core/interfaces.js +1 -0
  20. package/dist/src/codegen/core/interfaces.js.map +1 -1
  21. package/dist/src/codegen/core/license.js +1 -0
  22. package/dist/src/codegen/core/license.js.map +1 -1
  23. package/dist/src/codegen/core/metadata.js +1 -0
  24. package/dist/src/codegen/core/metadata.js.map +1 -1
  25. package/dist/src/codegen/core/models.d.ts.map +1 -1
  26. package/dist/src/codegen/core/models.js +64 -16
  27. package/dist/src/codegen/core/models.js.map +1 -1
  28. package/dist/src/codegen/core/operations.d.ts +0 -1
  29. package/dist/src/codegen/core/operations.d.ts.map +1 -1
  30. package/dist/src/codegen/core/operations.js +60 -1086
  31. package/dist/src/codegen/core/operations.js.map +1 -1
  32. package/dist/src/codegen/core/request-handler.d.ts +14 -0
  33. package/dist/src/codegen/core/request-handler.d.ts.map +1 -0
  34. package/dist/src/codegen/core/request-handler.js +819 -0
  35. package/dist/src/codegen/core/request-handler.js.map +1 -0
  36. package/dist/src/codegen/core/response-handler.d.ts +12 -0
  37. package/dist/src/codegen/core/response-handler.d.ts.map +1 -0
  38. package/dist/src/codegen/core/response-handler.js +288 -0
  39. package/dist/src/codegen/core/response-handler.js.map +1 -0
  40. package/dist/src/codegen/core/version.js +1 -0
  41. package/dist/src/codegen/core/version.js.map +1 -1
  42. package/dist/src/codegen/core/xml-additional-props.js +1 -0
  43. package/dist/src/codegen/core/xml-additional-props.js.map +1 -1
  44. package/dist/src/codegen/emitter.d.ts.map +1 -1
  45. package/dist/src/codegen/emitter.js +21 -37
  46. package/dist/src/codegen/emitter.js.map +1 -1
  47. package/dist/src/codegen/fake/index.d.ts +3 -0
  48. package/dist/src/codegen/fake/index.d.ts.map +1 -0
  49. package/dist/src/codegen/fake/index.js +7 -0
  50. package/dist/src/codegen/fake/index.js.map +1 -0
  51. package/dist/src/codegen/fake/internal.js +1 -0
  52. package/dist/src/codegen/fake/internal.js.map +1 -1
  53. package/dist/src/codegen/fake/servers.d.ts.map +1 -1
  54. package/dist/src/codegen/fake/servers.js +17 -16
  55. package/dist/src/codegen/fake/servers.js.map +1 -1
  56. package/dist/src/codemodel/client.d.ts.map +1 -1
  57. package/dist/src/codemodel/client.js +6 -0
  58. package/dist/src/codemodel/client.js.map +1 -1
  59. package/dist/src/codemodel/code-model.js +2 -0
  60. package/dist/src/codemodel/code-model.js.map +1 -1
  61. package/dist/src/codemodel/docs.d.ts +9 -0
  62. package/dist/src/codemodel/docs.d.ts.map +1 -0
  63. package/dist/src/codemodel/docs.js +40 -0
  64. package/dist/src/codemodel/docs.js.map +1 -0
  65. package/dist/src/codemodel/examples.js +4 -0
  66. package/dist/src/codemodel/examples.js.map +1 -1
  67. package/dist/src/codemodel/index.d.ts +1 -0
  68. package/dist/src/codemodel/index.d.ts.map +1 -1
  69. package/dist/src/codemodel/index.js +1 -0
  70. package/dist/src/codemodel/index.js.map +1 -1
  71. package/dist/src/codemodel/method.js +2 -0
  72. package/dist/src/codemodel/method.js.map +1 -1
  73. package/dist/src/codemodel/module.js +3 -0
  74. package/dist/src/codemodel/module.js.map +1 -1
  75. package/dist/src/codemodel/param.d.ts.map +1 -1
  76. package/dist/src/codemodel/param.js +1 -0
  77. package/dist/src/codemodel/param.js.map +1 -1
  78. package/dist/src/codemodel/result.js +3 -0
  79. package/dist/src/codemodel/result.js.map +1 -1
  80. package/dist/src/codemodel/type.d.ts +7 -2
  81. package/dist/src/codemodel/type.d.ts.map +1 -1
  82. package/dist/src/codemodel/type.js +3 -0
  83. package/dist/src/codemodel/type.js.map +1 -1
  84. package/dist/src/emitter.d.ts +2 -2
  85. package/dist/src/emitter.d.ts.map +1 -1
  86. package/dist/src/emitter.js +110 -3
  87. package/dist/src/emitter.js.map +1 -1
  88. package/dist/src/lib.js.map +1 -1
  89. package/dist/src/tcgcadapter/adapter.d.ts +1 -1
  90. package/dist/src/tcgcadapter/adapter.d.ts.map +1 -1
  91. package/dist/src/tcgcadapter/adapter.js +6 -1
  92. package/dist/src/tcgcadapter/adapter.js.map +1 -1
  93. package/dist/src/tcgcadapter/clients.d.ts.map +1 -1
  94. package/dist/src/tcgcadapter/clients.js +9 -2
  95. package/dist/src/tcgcadapter/clients.js.map +1 -1
  96. package/dist/src/tcgcadapter/errors.d.ts +1 -1
  97. package/dist/src/tcgcadapter/errors.d.ts.map +1 -1
  98. package/dist/src/tcgcadapter/helpers.d.ts +5 -3
  99. package/dist/src/tcgcadapter/helpers.d.ts.map +1 -1
  100. package/dist/src/tcgcadapter/helpers.js +19 -4
  101. package/dist/src/tcgcadapter/helpers.js.map +1 -1
  102. package/dist/src/tcgcadapter/metadata.js +1 -0
  103. package/dist/src/tcgcadapter/metadata.js.map +1 -1
  104. package/dist/src/tcgcadapter/types.d.ts.map +1 -1
  105. package/dist/src/tcgcadapter/types.js +16 -8
  106. package/dist/src/tcgcadapter/types.js.map +1 -1
  107. package/package.json +35 -33
@@ -0,0 +1,819 @@
1
+ /*---------------------------------------------------------------------------------------------
2
+ * Copyright (c) Microsoft Corporation. All rights reserved.
3
+ * Licensed under the MIT License. See License.txt in the project root for license information.
4
+ *--------------------------------------------------------------------------------------------*/
5
+ import * as go from "../../codemodel/index.js";
6
+ import * as naming from "../../naming/naming.js";
7
+ import { CodegenError } from "./errors.js";
8
+ import * as helpers from "./helpers.js";
9
+ import { ImportManager } from "./imports.js";
10
+ /**
11
+ * emits the request handler for the specified method.
12
+ *
13
+ * @param azureARM indicates whether the request is for an Azure ARM service.
14
+ * @param method the method for which to create the request handler.
15
+ * @param imports the import manager to track required imports.
16
+ * @param indent the indentation helper for formatting the generated code.
17
+ * @returns the generated request handler code as a string.
18
+ */
19
+ export function createRequestHandler(azureARM, method, imports, indent) {
20
+ let name = method.name;
21
+ if (method.kind !== "nextPageMethod") {
22
+ name = method.naming.requestMethod;
23
+ }
24
+ for (const param of method.parameters) {
25
+ if (param.location !== "method" || !go.isRequiredParameter(param.style)) {
26
+ continue;
27
+ }
28
+ imports.addForType(param.type);
29
+ }
30
+ const returns = ["*policy.Request", "error"];
31
+ let text = `${helpers.comment(name, "// ")} creates the ${method.name} request.\n`;
32
+ text += `func ${helpers.getClientReceiverDefinition(method.receiver)} ${name}(${helpers.getCreateRequestParametersSig(method)}) (${returns.join(", ")}) {\n`;
33
+ // BEGIN create request
34
+ const hostParams = new Array();
35
+ for (const parameter of method.receiver.type.parameters) {
36
+ if (parameter.kind === "uriParam") {
37
+ hostParams.push(parameter);
38
+ }
39
+ }
40
+ let hostParam;
41
+ if (azureARM) {
42
+ hostParam = "client.internal.Endpoint()";
43
+ }
44
+ else if (method.receiver.type.instance?.kind === "templatedHost") {
45
+ imports.add("strings");
46
+ // we have a templated host
47
+ text += `${indent.get()}host := "${method.receiver.type.instance.path}"\n`;
48
+ // get all the host params on the client
49
+ for (const hostParam of hostParams) {
50
+ text += `${indent.get()}host = strings.ReplaceAll(host, "{${hostParam.uriPathSegment}}", ${helpers.formatValue(`client.${hostParam.name}`, hostParam.type, imports)})\n`;
51
+ }
52
+ // check for any method local host params
53
+ for (const param of method.parameters) {
54
+ if (param.location === "method" && param.kind === "uriParam") {
55
+ text += `${indent.get()}host = strings.ReplaceAll(host, "{${param.uriPathSegment}}", ${helpers.formatValue(helpers.getParamName(param), param.type, imports)})\n`;
56
+ }
57
+ }
58
+ hostParam = "host";
59
+ }
60
+ else if (hostParams.length === 1) {
61
+ // simple parameterized host case
62
+ hostParam = "client." + hostParams[0].name;
63
+ }
64
+ else {
65
+ throw new CodegenError("InternalError", `no host or endpoint defined for method ${method.receiver.type.name}.${method.name}`);
66
+ }
67
+ const methodParamGroups = helpers.getMethodParamGroups(method);
68
+ const hasPathParams = methodParamGroups.pathParams.length > 0;
69
+ // storage needs the client.u to be the source-of-truth for the full path.
70
+ // however, swagger requires that all operations specify a path, which is at odds with storage.
71
+ // to work around this, storage specifies x-ms-path paths with path params but doesn't
72
+ // actually reference the path params (i.e. no params with which to replace the tokens).
73
+ // so, if a path contains tokens but there are no path params, skip emitting the path.
74
+ const pathStr = method.httpPath;
75
+ const pathContainsParms = pathStr.includes("{");
76
+ if (hasPathParams || (!pathContainsParms && pathStr.length > 1)) {
77
+ // there are path params, or the path doesn't contain tokens and is not "/" so emit it
78
+ text += `${indent.get()}urlPath := "${method.httpPath}"\n`;
79
+ hostParam = `runtime.JoinPaths(${hostParam}, urlPath)`;
80
+ }
81
+ if (hasPathParams) {
82
+ // swagger defines path params, emit path and replace tokens
83
+ imports.add("strings");
84
+ // replace path parameters
85
+ for (const pp of methodParamGroups.pathParams) {
86
+ let paramValue;
87
+ let optionalPathSep = false;
88
+ if (pp.style === "literal") {
89
+ // literals are always scalar types and require no empty checks
90
+ paramValue = helpers.formatParamValue(pp, imports, indent);
91
+ }
92
+ else if (pp.style === "required" || pp.location === "client") {
93
+ // NOTE: we include client params here since they behave
94
+ // like required params (i.e. not grouped).
95
+ // emit check to ensure path param isn't an empty string
96
+ if (pp.kind === "pathScalarParam") {
97
+ // we only need to do this for params that have an underlying type of string
98
+ if ((pp.type.kind === "string" ||
99
+ (pp.type.kind === "constant" && pp.type.type === "string")) &&
100
+ !pp.omitEmptyStringCheck) {
101
+ const paramName = helpers.getParamName(pp);
102
+ imports.add("errors");
103
+ text += `${indent.get()}if ${paramName} == "" {\n`;
104
+ text += `${indent.push().get()}return nil, errors.New("parameter ${paramName} cannot be empty")\n`;
105
+ text += `${indent.pop().get()}}\n`;
106
+ }
107
+ }
108
+ paramValue = helpers.formatParamValue(pp, imports, indent);
109
+ // for collection-based path params, we emit the empty check
110
+ // after calling helpers.formatParamValue as that will have the
111
+ // var name that contains the slice.
112
+ if (pp.kind === "pathCollectionParam") {
113
+ const paramName = helpers.getParamName(pp);
114
+ const joinedParamName = `${paramName}Param`;
115
+ text += `${indent.get()}${joinedParamName} := ${paramValue}\n`;
116
+ imports.add("errors");
117
+ text += `${indent.get()}if len(${joinedParamName}) == 0 {\n`;
118
+ text += `${indent.push().get()}return nil, errors.New("parameter ${paramName} cannot be empty")\n`;
119
+ text += `${indent.pop().get()}}\n`;
120
+ paramValue = joinedParamName;
121
+ }
122
+ }
123
+ else if (go.isClientSideDefault(pp.style)) {
124
+ const defaultValue = naming.uncapitalize(pp.name) + "Default";
125
+ text += `${indent.get()}${defaultValue} := ${helpers.formatLiteralValue(pp.style.defaultValue, true)}\n`;
126
+ text += emitParamGroupCheck(pp, indent);
127
+ text += `${indent.push().get()}${defaultValue} = ${helpers.getParamName(pp)}\n`;
128
+ text += `${indent.pop().get()}}\n`;
129
+ paramValue = helpers.formatValue(defaultValue, pp.type, imports);
130
+ }
131
+ else {
132
+ // param isn't required, so emit a local var with
133
+ // the correct default value, then populate it with
134
+ // the optional value when set.
135
+ paramValue = `optional${naming.capitalize(pp.name)}`;
136
+ text += `${indent.get()}${paramValue} := ""\n`;
137
+ text += emitParamGroupCheck(pp, indent);
138
+ text += `${indent.push().get()}${paramValue} = ${helpers.formatParamValue(pp, imports, indent)}\n`;
139
+ text += `${indent.pop().get()}}\n`;
140
+ // there are two cases for optional path params.
141
+ // - /foo/bar/{optional}
142
+ // - /foo/bar{/optional}
143
+ // for the second case, we need to include a forward slash
144
+ if (method.httpPath[method.httpPath.indexOf(`{${pp.pathSegment}}`) - 1] !== "/") {
145
+ optionalPathSep = true;
146
+ }
147
+ }
148
+ if (optionalPathSep) {
149
+ text += `${indent.get()}if len(${paramValue}) > 0 {\n`;
150
+ text += `${indent.push().get()}${paramValue} = "/"+${emitPathEscape(pp, paramValue, imports)}\n`;
151
+ text += `${indent.pop().get()}}\n`;
152
+ }
153
+ else {
154
+ paramValue = emitPathEscape(pp, paramValue, imports);
155
+ }
156
+ text += `${indent.get()}urlPath = strings.ReplaceAll(urlPath, "{${pp.pathSegment}}", ${paramValue})\n`;
157
+ }
158
+ }
159
+ text += `${indent.get()}req, err := runtime.NewRequest(ctx, http.Method${naming.capitalize(method.httpMethod)}, ${hostParam})\n`;
160
+ text += `${indent.get()}if err != nil {\n`;
161
+ text += `${indent.push().get()}return nil, err\n`;
162
+ text += `${indent.pop().get()}}\n`;
163
+ // END create request
164
+ // BEGIN add query parameters
165
+ const encodedParams = methodParamGroups.encodedQueryParams;
166
+ const unencodedParams = methodParamGroups.unencodedQueryParams;
167
+ // emit encoded params first
168
+ if (encodedParams.length > 0) {
169
+ text += `${indent.get()}reqQP := req.Raw().URL.Query()\n`;
170
+ for (const qp of encodedParams.sort((a, b) => {
171
+ return helpers.sortAscending(a.queryParameter, b.queryParameter);
172
+ })) {
173
+ let setter;
174
+ if (qp.kind === "queryCollectionParam" && qp.collectionFormat === "multi") {
175
+ setter = `for _, qv := range ${helpers.getParamName(qp)} {\n`;
176
+ // emit a type conversion for the qv based on the array's element type
177
+ let queryVal;
178
+ const arrayQP = qp.type;
179
+ switch (arrayQP.elementType.kind) {
180
+ case "constant":
181
+ switch (arrayQP.elementType.type) {
182
+ case "string":
183
+ queryVal = "string(qv)";
184
+ break;
185
+ default:
186
+ imports.add("fmt");
187
+ queryVal = 'fmt.Sprintf("%d", qv)';
188
+ }
189
+ break;
190
+ case "string":
191
+ queryVal = "qv";
192
+ break;
193
+ default:
194
+ imports.add("fmt");
195
+ queryVal = 'fmt.Sprintf("%v", qv)';
196
+ }
197
+ setter += `${indent.push().get()}reqQP.Add("${qp.queryParameter}", ${queryVal})\n`;
198
+ setter += `${indent.pop().get()}}`;
199
+ }
200
+ else {
201
+ // cannot initialize setter to this value as helpers.formatParamValue() can change imports
202
+ setter = `reqQP.Set("${qp.queryParameter}", ${helpers.formatParamValue(qp, imports, indent)})`;
203
+ }
204
+ text += emitQueryParam(qp, imports, indent, setter);
205
+ }
206
+ // reqQP.Encode() encodes space chars as '+' which is application/x-www-form-urlencoded
207
+ // thus not applicable for URIs. the correct URI encoding for SP is %20. note that literal '+'
208
+ // characters are encoded by reqQP.Encode() as %2B so there's no risk of replacing them.
209
+ // see https://www.rfc-editor.org/rfc/rfc3986 sections 2.1, 2.2, and 3.4
210
+ imports.add("strings");
211
+ text += `${indent.get()}req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20")\n`;
212
+ }
213
+ // tack on any unencoded params to the end
214
+ if (unencodedParams.length > 0) {
215
+ if (encodedParams.length > 0) {
216
+ text += `${indent.get()}unencodedParams := []string{req.Raw().URL.RawQuery}\n`;
217
+ }
218
+ else {
219
+ text += `${indent.get()}unencodedParams := []string{}\n`;
220
+ }
221
+ for (const qp of unencodedParams.sort((a, b) => {
222
+ return helpers.sortAscending(a.queryParameter, b.queryParameter);
223
+ })) {
224
+ let setter;
225
+ if (qp.kind === "queryCollectionParam" && qp.collectionFormat === "multi") {
226
+ setter = `for _, qv := range ${helpers.getParamName(qp)} {\n`;
227
+ setter += `${indent.push().get()}unencodedParams = append(unencodedParams, "${qp.queryParameter}="+qv)\n`;
228
+ setter += `${indent.pop().get()}}`;
229
+ }
230
+ else {
231
+ setter = `unencodedParams = append(unencodedParams, "${qp.queryParameter}="+${helpers.formatParamValue(qp, imports, indent)})`;
232
+ }
233
+ text += emitQueryParam(qp, imports, indent, setter);
234
+ }
235
+ imports.add("strings");
236
+ text += `${indent.get()}req.Raw().URL.RawQuery = strings.Join(unencodedParams, "&")\n`;
237
+ }
238
+ // END add query parameters
239
+ if (method.kind !== "nextPageMethod" && method.returns.result?.kind === "binaryResult") {
240
+ // skip auto-body downloading for binary stream responses
241
+ text += `${indent.get()}runtime.SkipBodyDownload(req)\n`;
242
+ }
243
+ // BEGIN specific request headers
244
+ let contentType;
245
+ for (const param of methodParamGroups.headerParams.sort((a, b) => {
246
+ return helpers.sortAscending(a.headerName, b.headerName);
247
+ })) {
248
+ if (param.headerName.match(/^content-type$/i)) {
249
+ // canonicalize content-type as req.SetBody checks for it via its canonicalized name :(
250
+ param.headerName = "Content-Type";
251
+ // there's a corner case where we have a content-type param with no body
252
+ // param. for this case we still need to set the header inline.
253
+ const bodyParam = methodParamGroups.bodyParam;
254
+ if (bodyParam?.bodyFormat === "binary" || bodyParam?.bodyFormat === "Text") {
255
+ // if the content-type is from a param, then the param will be passed
256
+ // explicitly to runtime.SetBody() so don't emit code to set it inline.
257
+ // NOTE: only binary/text payloads call runtime.SetBody().
258
+ if (go.isClientSideDefault(param.style)) {
259
+ text += emitClientSideDefault(param, param.style, imports, indent, () => "");
260
+ continue;
261
+ }
262
+ else if (param.style === "required") {
263
+ continue;
264
+ }
265
+ }
266
+ }
267
+ if (param.headerName === "Content-Type" && param.style === "literal") {
268
+ // the content-type header will be set as part of emitSetBodyWithErrCheck
269
+ // to handle cases where the body param is optional. we don't want to set
270
+ // the content-type if the body is nil.
271
+ // we do it like this as tsp specifies content-type while swagger does not.
272
+ contentType = helpers.formatParamValue(param, imports, indent);
273
+ }
274
+ else if (go.isRequiredParameter(param.style) ||
275
+ go.isLiteralParameter(param.style) ||
276
+ go.isClientSideDefault(param.style)) {
277
+ text += emitHeaderSet(param, imports, indent);
278
+ }
279
+ else if (param.location === "client" && !param.group) {
280
+ // global optional param
281
+ text += `${indent.get()}if client.${param.name} != nil {\n`;
282
+ indent.push();
283
+ text += emitHeaderSet(param, imports, indent);
284
+ indent.pop();
285
+ text += `${indent.get()}}\n`;
286
+ }
287
+ else {
288
+ text += emitParamGroupCheck(param, indent);
289
+ indent.push();
290
+ text += emitHeaderSet(param, imports, indent);
291
+ indent.pop();
292
+ text += `${indent.get()}}\n`;
293
+ }
294
+ }
295
+ // END specific request headers
296
+ // BEGIN set body
297
+ // note that these are mutually exclusive
298
+ const bodyParam = methodParamGroups.bodyParam;
299
+ const formBodyParams = methodParamGroups.formBodyParams;
300
+ const multipartBodyParams = methodParamGroups.multipartBodyParams;
301
+ const partialBodyParams = methodParamGroups.partialBodyParams;
302
+ if (bodyParam) {
303
+ if (bodyParam.bodyFormat === "JSON" || bodyParam.bodyFormat === "XML") {
304
+ // default to the body param name
305
+ let body = helpers.getParamName(bodyParam);
306
+ if (bodyParam.type.kind === "literal") {
307
+ // if the value is constant, embed it directly
308
+ body = helpers.formatLiteralValue(bodyParam.type, true);
309
+ }
310
+ else if (bodyParam.bodyFormat === "XML" && bodyParam.type.kind === "slice") {
311
+ // for XML payloads, create a wrapper type if the payload is an array
312
+ imports.add("encoding/xml");
313
+ text += `${indent.get()}type wrapper struct {\n`;
314
+ indent.push();
315
+ let tagName;
316
+ if (bodyParam.xml?.wrapper) {
317
+ tagName = bodyParam.xml.wrapper;
318
+ }
319
+ else {
320
+ tagName = go.getTypeDeclaration(bodyParam.type, method.receiver.type.pkg);
321
+ }
322
+ text += `${indent.get()}XMLName xml.Name \`xml:"${tagName}"\`\n`;
323
+ const fieldName = naming.capitalize(bodyParam.name);
324
+ let tag = go.getTypeDeclaration(bodyParam.type.elementType, method.receiver.type.pkg);
325
+ if (bodyParam.type.elementType.kind === "model" && bodyParam.type.elementType.xml?.name) {
326
+ tag = bodyParam.type.elementType.xml.name;
327
+ }
328
+ text += `${indent.get()}${fieldName} *${go.getTypeDeclaration(bodyParam.type, method.receiver.type.pkg)} \`xml:"${tag}"\`\n`;
329
+ text += `${indent.pop().get()}}\n`;
330
+ let addr = "&";
331
+ if (!go.isRequiredParameter(bodyParam.style) && !bodyParam.byValue) {
332
+ addr = "";
333
+ }
334
+ body = `wrapper{${fieldName}: ${addr}${body}}`;
335
+ }
336
+ else if (bodyParam.type.kind === "time") {
337
+ // utc datetimes are normalized to UTC before serialization. non-RFC3339
338
+ // formats are wrapped in the internal time type; RFC3339 relies on the
339
+ // default time.Time JSON marshaler so it only needs the UTC conversion.
340
+ const bodyVal = bodyParam.type.utc ? `${body}.UTC()` : body;
341
+ if (bodyParam.type.format !== "RFC3339") {
342
+ imports.add("github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime");
343
+ body = `datetime.${bodyParam.type.format}(${bodyVal})`;
344
+ }
345
+ else {
346
+ body = bodyVal;
347
+ }
348
+ }
349
+ else if (isArrayOfDateTimeForMarshalling(bodyParam.type)) {
350
+ const timeInfo = isArrayOfDateTimeForMarshalling(bodyParam.type);
351
+ let elementPtr = "*";
352
+ if (timeInfo?.elemByVal) {
353
+ elementPtr = "";
354
+ }
355
+ imports.add("github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime");
356
+ text += `${indent.get()}aux := make([]${elementPtr}datetime.${timeInfo?.format}, len(${body}))\n`;
357
+ text += `${indent.get()}for i := 0; i < len(${body}); i++ {\n`;
358
+ if (timeInfo?.utc && elementPtr === "*") {
359
+ text += `${indent.push().get()}if ${body}[i] != nil {\n`;
360
+ text += `${indent.push().get()}utcTime := ${body}[i].UTC()\n`;
361
+ text += `${indent.get()}aux[i] = (*datetime.${timeInfo?.format})(&utcTime)\n`;
362
+ text += `${indent.pop().get()}}\n`;
363
+ indent.pop();
364
+ }
365
+ else {
366
+ const utcCall = timeInfo?.utc ? ".UTC()" : "";
367
+ text += `${indent.push().get()}aux[i] = (${elementPtr}datetime.${timeInfo?.format})(${body}[i]${utcCall})\n`;
368
+ indent.pop();
369
+ }
370
+ text += `${indent.get()}}\n`;
371
+ body = "aux";
372
+ }
373
+ else if (helpers.isMapOfDateTime(bodyParam.type)) {
374
+ const timeInfo = helpers.isMapOfDateTime(bodyParam.type);
375
+ imports.add("github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime");
376
+ text += `${indent.get()}aux := map[string]*datetime.${timeInfo?.format}{}\n`;
377
+ text += `${indent.get()}for k, v := range ${body} {\n`;
378
+ if (timeInfo?.utc) {
379
+ text += `${indent.push().get()}if v != nil {\n`;
380
+ text += `${indent.push().get()}utcTime := v.UTC()\n`;
381
+ text += `${indent.get()}aux[k] = (*datetime.${timeInfo?.format})(&utcTime)\n`;
382
+ text += `${indent.pop().get()}} else {\n`;
383
+ text += `${indent.push().get()}aux[k] = nil\n`;
384
+ text += `${indent.pop().get()}}\n`;
385
+ indent.pop();
386
+ }
387
+ else {
388
+ text += `${indent.push().get()}aux[k] = (*datetime.${timeInfo?.format})(v)\n`;
389
+ indent.pop();
390
+ }
391
+ text += `${indent.get()}}\n`;
392
+ body = "aux";
393
+ }
394
+ let setBody = `runtime.MarshalAs${helpers.getMediaFormat(bodyParam.type, bodyParam.bodyFormat, `req, ${body}`)}`;
395
+ if (bodyParam.type.kind === "rawJSON") {
396
+ imports.add("bytes");
397
+ imports.add("github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming");
398
+ setBody = `req.SetBody(streaming.NopCloser(bytes.NewReader(${body})), "application/${bodyParam.bodyFormat.toLowerCase()}")`;
399
+ }
400
+ if (go.isRequiredParameter(bodyParam.style) || go.isLiteralParameter(bodyParam.style)) {
401
+ text += emitSetBodyWithErrCheck(setBody, indent, contentType);
402
+ text += `${indent.get()}return req, nil\n`;
403
+ }
404
+ else {
405
+ text += emitParamGroupCheck(bodyParam, indent);
406
+ indent.push();
407
+ text += emitSetBodyWithErrCheck(setBody, indent, contentType);
408
+ text += `${indent.get()}return req, nil\n`;
409
+ indent.pop();
410
+ text += `${indent.get()}}\n`;
411
+ text += `${indent.get()}return req, nil\n`;
412
+ }
413
+ }
414
+ else if (bodyParam.bodyFormat === "binary") {
415
+ if (go.isRequiredParameter(bodyParam.style)) {
416
+ text += emitSetBodyWithErrCheck(`req.SetBody(${bodyParam.name}, ${getContentTypeValue(method, bodyParam.contentType)})`, indent, contentType);
417
+ text += `${indent.get()}return req, nil\n`;
418
+ }
419
+ else {
420
+ text += emitParamGroupCheck(bodyParam, indent);
421
+ indent.push();
422
+ text += emitSetBodyWithErrCheck(`req.SetBody(${helpers.getParamName(bodyParam)}, ${getContentTypeValue(method, bodyParam.contentType)})`, indent, contentType);
423
+ text += `${indent.get()}return req, nil\n`;
424
+ indent.pop();
425
+ text += `${indent.get()}}\n`;
426
+ text += `${indent.get()}return req, nil\n`;
427
+ }
428
+ }
429
+ else if (bodyParam.bodyFormat === "Text") {
430
+ imports.add("strings");
431
+ imports.add("github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming");
432
+ if (go.isRequiredParameter(bodyParam.style)) {
433
+ text += `${indent.get()}body := streaming.NopCloser(strings.NewReader(${bodyParam.name}))\n`;
434
+ text += emitSetBodyWithErrCheck(`req.SetBody(body, ${getContentTypeValue(method, bodyParam.contentType)})`, indent, contentType);
435
+ text += `${indent.get()}return req, nil\n`;
436
+ }
437
+ else {
438
+ text += emitParamGroupCheck(bodyParam, indent);
439
+ indent.push();
440
+ text += `${indent.get()}body := streaming.NopCloser(strings.NewReader(${helpers.getParamName(bodyParam)}))\n`;
441
+ text += emitSetBodyWithErrCheck(`req.SetBody(body, ${getContentTypeValue(method, bodyParam.contentType)})`, indent, contentType);
442
+ text += `${indent.get()}return req, nil\n`;
443
+ indent.pop();
444
+ text += `${indent.get()}}\n`;
445
+ text += `${indent.get()}return req, nil\n`;
446
+ }
447
+ }
448
+ }
449
+ else if (partialBodyParams.length > 0) {
450
+ // partial body params are discrete params that are all fields within an internal struct.
451
+ // define and instantiate an instance of the wire type, using the values from each param.
452
+ text += `${indent.get()}body := struct {\n`;
453
+ indent.push();
454
+ for (const partialBodyParam of partialBodyParams) {
455
+ text += `${indent.get()}${naming.capitalize(partialBodyParam.serializedName)} ${helpers.star(partialBodyParam.byValue)}${go.getTypeDeclaration(partialBodyParam.type, method.receiver.type.pkg)} \`${partialBodyParam.format.toLowerCase()}:"${partialBodyParam.serializedName}"\`\n`;
456
+ }
457
+ indent.pop();
458
+ text += `${indent.get()}}{\n`;
459
+ indent.push();
460
+ // required params are emitted as initializers in the struct literal
461
+ for (const partialBodyParam of partialBodyParams) {
462
+ if (go.isRequiredParameter(partialBodyParam.style)) {
463
+ text += `${indent.get()}${naming.capitalize(partialBodyParam.serializedName)}: ${naming.uncapitalize(partialBodyParam.name)},\n`;
464
+ }
465
+ }
466
+ indent.pop();
467
+ text += `${indent.get()}}\n`;
468
+ // now populate any optional params from the options type
469
+ for (const partialBodyParam of partialBodyParams) {
470
+ if (!go.isRequiredParameter(partialBodyParam.style)) {
471
+ text += emitParamGroupCheck(partialBodyParam, indent);
472
+ text += `${indent.push().get()}body.${naming.capitalize(partialBodyParam.serializedName)} = options.${naming.capitalize(partialBodyParam.name)}\n`;
473
+ text += `${indent.pop().get()}}\n`;
474
+ }
475
+ }
476
+ // TODO: spread params are JSON only https://github.com/Azure/autorest.go/issues/1455
477
+ text += `${indent.get()}req.Raw().Header["Content-Type"] = []string{"application/json"}\n`;
478
+ text += `${indent.get()}if err := runtime.MarshalAsJSON(req, body); err != nil {\n`;
479
+ text += `${indent.push().get()}return nil, err\n`;
480
+ text += `${indent.pop().get()}}\n`;
481
+ text += `${indent.get()}return req, nil\n`;
482
+ }
483
+ else if (multipartBodyParams.length > 0) {
484
+ // emit content type setters for direct MultipartContent params with a fixed content type.
485
+ // this handles the case where the param itself is a MultipartContent or a slice of them
486
+ // (i.e. not wrapped in a model struct with toMultipartFormData()).
487
+ // note that tsp only allows homogeneous content types, which is why it's safe
488
+ // to unwrap the first param's type and check its contentType field.
489
+ text += emitMultipartContentTypeSetter(multipartBodyParams[0].name, multipartBodyParams[0].type, indent);
490
+ if (multipartBodyParams.length === 1 &&
491
+ multipartBodyParams[0].type.kind === "model" &&
492
+ multipartBodyParams[0].type.annotations.multipartFormData) {
493
+ // emit content type setters for model fields that have a fixed content type.
494
+ // toMultipartFormData() converts the model to map[string]any but doesn't set ContentType,
495
+ // so we must set it on each MultipartContent field before the conversion.
496
+ for (const field of multipartBodyParams[0].type.fields) {
497
+ text += emitMultipartContentTypeSetter(`${multipartBodyParams[0].name}.${field.name}`, field.type, indent);
498
+ }
499
+ text += `${indent.get()}formData, err := ${multipartBodyParams[0].name}.toMultipartFormData()\n`;
500
+ text += `${indent.get()}if err != nil {\n`;
501
+ text += `${indent.push().get()}return nil, err\n`;
502
+ text += `${indent.pop().get()}}\n`;
503
+ }
504
+ else {
505
+ text += `${indent.get()}formData := map[string]any{}\n`;
506
+ for (const param of multipartBodyParams) {
507
+ const setter = `formData["${param.name}"] = ${helpers.getParamName(param)}`;
508
+ if (go.isRequiredParameter(param.style)) {
509
+ text += `${indent.get()}${setter}\n`;
510
+ }
511
+ else {
512
+ text += emitParamGroupCheck(param, indent);
513
+ text += `${indent.push().get()}${setter}\n`;
514
+ text += `${indent.pop().get()}}\n`;
515
+ }
516
+ }
517
+ }
518
+ text += `${indent.get()}if err := runtime.SetMultipartFormData(req, formData); err != nil {\n`;
519
+ text += `${indent.push().get()}return nil, err\n`;
520
+ text += `${indent.pop().get()}}\n`;
521
+ text += `${indent.get()}return req, nil\n`;
522
+ }
523
+ else if (formBodyParams.length > 0) {
524
+ imports.add("net/url");
525
+ imports.add("strings");
526
+ imports.add("github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming");
527
+ text += `${indent.get()}formData := url.Values{}\n`;
528
+ // find all the form body params
529
+ for (const param of formBodyParams) {
530
+ const setter = `formData.Set("${param.formDataName}", ${helpers.formatParamValue(param, imports, indent)})`;
531
+ if (go.isRequiredParameter(param.style)) {
532
+ text += `${indent.get()}${setter}\n`;
533
+ }
534
+ else {
535
+ text += emitParamGroupCheck(param, indent);
536
+ text += `${indent.push().get()}${setter}\n`;
537
+ text += `${indent.pop().get()}}\n`;
538
+ }
539
+ }
540
+ text += `${indent.get()}body := streaming.NopCloser(strings.NewReader(formData.Encode()))\n`;
541
+ text += emitSetBodyWithErrCheck('req.SetBody(body, "application/x-www-form-urlencoded")', indent);
542
+ text += `${indent.get()}return req, nil\n`;
543
+ }
544
+ else {
545
+ // no body
546
+ text += `${indent.get()}return req, nil\n`;
547
+ }
548
+ // END set body
549
+ text += "}\n\n";
550
+ return text;
551
+ }
552
+ /**
553
+ * emits code for handling parameters with a client-side default
554
+ *
555
+ * @param param the param with a client-side default
556
+ * @param csd the client-side default value
557
+ * @param imports the import manager currently in scope
558
+ * @param indent the indentation helper currently in scope
559
+ * @param setterFormat any custom formatting for the value
560
+ * @returns the code for handling the client-side default
561
+ */
562
+ function emitClientSideDefault(param, csd, imports, indent, setterFormat) {
563
+ const defaultVar = getClientSideDefaultVarName(param);
564
+ let text = `${indent.get()}${defaultVar} := ${helpers.formatLiteralValue(csd.defaultValue, true)}\n`;
565
+ text += `${indent.get()}if options != nil && options.${naming.capitalize(param.name)} != nil {\n`;
566
+ text += `${indent.push().get()}${defaultVar} = *options.${naming.capitalize(param.name)}\n`;
567
+ text += `${indent.pop().get()}}\n`;
568
+ let serializedName;
569
+ switch (param.kind) {
570
+ case "headerCollectionParam":
571
+ case "headerScalarParam":
572
+ serializedName = param.headerName;
573
+ break;
574
+ case "queryCollectionParam":
575
+ case "queryScalarParam":
576
+ serializedName = param.queryParameter;
577
+ break;
578
+ }
579
+ const setterFormatText = setterFormat(`"${serializedName}"`, helpers.formatValue(defaultVar, param.type, imports));
580
+ text += setterFormatText;
581
+ // setterFormat can return the empty string in some cases.
582
+ // if it does, there's no need for an extra new-line char.
583
+ if (setterFormatText.length > 0) {
584
+ text += "\n";
585
+ }
586
+ return text;
587
+ }
588
+ /**
589
+ * emits code for setting a header from a parameter.
590
+ * it includes handling for client-side defaults.
591
+ *
592
+ * @param headerParam the header param to be set
593
+ * @param imports the import manager currently in scope
594
+ * @param indent the indentation helper currently in scope
595
+ * @returns the code for setting a header
596
+ */
597
+ function emitHeaderSet(headerParam, imports, indent) {
598
+ if (headerParam.kind === "headerMapParam") {
599
+ let headerText = `${indent.get()}for k, v := range ${helpers.getParamName(headerParam)} {\n`;
600
+ headerText += `${indent.push().get()}if v != nil {\n`;
601
+ headerText += `${indent.push().get()}req.Raw().Header["${headerParam.headerName}"+k] = []string{*v}\n`;
602
+ headerText += `${indent.pop().get()}}\n`;
603
+ headerText += `${indent.pop().get()}}\n`;
604
+ return headerText;
605
+ }
606
+ else if (headerParam.location === "method" && go.isClientSideDefault(headerParam.style)) {
607
+ return emitClientSideDefault(headerParam, headerParam.style, imports, indent, (name, val) => {
608
+ return `${indent.get()}req.Raw().Header[${name}] = []string{${val}}`;
609
+ });
610
+ }
611
+ else {
612
+ return `${indent.get()}req.Raw().Header["${headerParam.headerName}"] = []string{${helpers.formatParamValue(headerParam, imports, indent)}}\n`;
613
+ }
614
+ }
615
+ /**
616
+ * emits code to URL escape a path parameter as required.
617
+ * the param name is a discrete param instead of param.name
618
+ * to handle cases where the param value was stored in a
619
+ * local variable.
620
+ *
621
+ * @param pp the path parameter
622
+ * @param paramName the path parameter var name
623
+ * @param imports the import manager currently in scope
624
+ * @returns the code that escaped the param or the param
625
+ */
626
+ function emitPathEscape(pp, paramName, imports) {
627
+ if (pp.isEncoded) {
628
+ imports.add("net/url");
629
+ return `url.PathEscape(${paramName})`;
630
+ }
631
+ return paramName;
632
+ }
633
+ /**
634
+ * emits Go code to set ContentType on a MultipartContent variable if it has a fixed content type.
635
+ * handles both direct MultipartContent and slices of MultipartContent.
636
+ * returns the empty string if there's nothing to set.
637
+ *
638
+ * @param paramName the name of the multipart param
639
+ * @param wireType the underlying type of the multipart param
640
+ * @param indent the indentation helper currently in scope
641
+ * @returns setter code or the empty string
642
+ */
643
+ function emitMultipartContentTypeSetter(paramName, wireType, indent) {
644
+ let text = "";
645
+ const unwrapped = helpers.recursiveUnwrapMapSlice(wireType);
646
+ if (unwrapped.kind !== "multipartContent" || !unwrapped.contentType) {
647
+ return text;
648
+ }
649
+ switch (wireType.kind) {
650
+ case "multipartContent":
651
+ text += `${indent.get()}${paramName}.ContentType = ${unwrapped.contentType.literal}\n`;
652
+ break;
653
+ case "slice":
654
+ text += `${indent.get()}for i := range ${paramName} {\n`;
655
+ text += `${indent.push().get()}${paramName}[i].ContentType = ${unwrapped.contentType.literal}\n`;
656
+ text += `${indent.pop().get()}}\n`;
657
+ break;
658
+ }
659
+ return text;
660
+ }
661
+ /**
662
+ * helper to build nil checks for param groups.
663
+ * this requires that param.group contains a ParameterGroup.
664
+ * it assumes that the provided param is optional.
665
+ *
666
+ * @param param the parameter for which to build the nil check
667
+ * @param indent the indentation helper currently in scope
668
+ * @returns the code for checking the param group for nil
669
+ */
670
+ function emitParamGroupCheck(param, indent) {
671
+ if (!param.group) {
672
+ throw new CodegenError("InternalError", `emitParamGroupCheck called for ungrouped parameter ${param.name}`);
673
+ }
674
+ let client = "";
675
+ if (param.location === "client") {
676
+ client = "client.";
677
+ }
678
+ const paramGroupName = naming.uncapitalize(param.group.name);
679
+ let optionalParamGroupCheck = `${client}${paramGroupName} != nil && `;
680
+ if (param.group.required) {
681
+ optionalParamGroupCheck = "";
682
+ }
683
+ return `${indent.get()}if ${optionalParamGroupCheck}${client}${paramGroupName}.${naming.capitalize(param.name)} != nil {\n`;
684
+ }
685
+ /**
686
+ * emits code for setting a query parameter.
687
+ * it handles nil checks and client-side defaults.
688
+ *
689
+ * @param qp the query param to be set
690
+ * @param imports the import manager currently in scope
691
+ * @param indent the indentation helper currently in scope
692
+ * @param setter the adjacent code for setting the query param
693
+ * @returns the code for setting the query param
694
+ */
695
+ function emitQueryParam(qp, imports, indent, setter) {
696
+ let qpText;
697
+ if (qp.location === "method" && go.isClientSideDefault(qp.style)) {
698
+ qpText = emitClientSideDefault(qp, qp.style, imports, indent, (name, val) => {
699
+ return `${indent.get()}reqQP.Set(${name}, ${val})`;
700
+ });
701
+ }
702
+ else if (go.isRequiredParameter(qp.style) ||
703
+ go.isLiteralParameter(qp.style) ||
704
+ (qp.location === "client" && go.isClientSideDefault(qp.style))) {
705
+ qpText = `${indent.get()}${setter}\n`;
706
+ }
707
+ else if (qp.location === "client" && !qp.group) {
708
+ // global optional param
709
+ qpText = `${indent.get()}if client.${qp.name} != nil {\n`;
710
+ qpText += `${indent.push().get()}${setter}\n`;
711
+ qpText += `${indent.pop().get()}}\n`;
712
+ }
713
+ else {
714
+ qpText = emitParamGroupCheck(qp, indent);
715
+ qpText += `${indent.push().get()}${setter}\n`;
716
+ qpText += `${indent.pop().get()}}\n`;
717
+ }
718
+ return qpText;
719
+ }
720
+ /**
721
+ * emits code for setting the request body and checking the resultant error.
722
+ * it's assumed that setBodyExpr is a function call that returns an error.
723
+ * also sets the Content-Type header as required.
724
+ *
725
+ * @param setBodyExpr the expression for setting the body
726
+ * @param indent the indentation helper currently in scope
727
+ * @param contentType optional value for setting the Content-Type header
728
+ * @returns the code for setting the body
729
+ */
730
+ function emitSetBodyWithErrCheck(setBodyExpr, indent, contentType) {
731
+ let content = "";
732
+ if (contentType) {
733
+ content += `${indent.get()}req.Raw().Header["Content-Type"] = []string{${contentType}}\n`;
734
+ }
735
+ content += `${indent.get()}if err := ${setBodyExpr}; err != nil {\n`;
736
+ content += `${indent.push().get()}return nil, err\n`;
737
+ content += `${indent.pop().get()}}\n`;
738
+ return content;
739
+ }
740
+ /**
741
+ * returns the var name to use for a param's client-side default value
742
+ *
743
+ * @param param the param for which to name the var
744
+ * @returns the var name
745
+ */
746
+ function getClientSideDefaultVarName(param) {
747
+ return naming.uncapitalize(param.name) + "Default";
748
+ }
749
+ /**
750
+ * returns the source value for the Content-Type header
751
+ *
752
+ * @param method the method for which to find the value depending on src
753
+ * @param src the source containing the value
754
+ * @returns the code containing the Content-Type value
755
+ */
756
+ function getContentTypeValue(method, src) {
757
+ switch (src.kind) {
758
+ case "literal":
759
+ return helpers.formatLiteralValue(src, false);
760
+ case "parameterRef": {
761
+ // find the param
762
+ for (const param of method.parameters) {
763
+ if (param.kind === "headerScalarParam" && param.name === src.name) {
764
+ if (go.isClientSideDefault(param.style)) {
765
+ return getClientSideDefaultVarName(param);
766
+ }
767
+ let paramName = helpers.getParamName(param);
768
+ if (param.type.kind === "constant") {
769
+ paramName = `string(${paramName})`;
770
+ }
771
+ return paramName;
772
+ }
773
+ }
774
+ throw new CodegenError("InternalError", `didn't find parameter reference ${src.name}`);
775
+ }
776
+ }
777
+ }
778
+ /**
779
+ * returns info for custom marshaling of slices of time.Time.
780
+ * returns undefined if the type isn't a slice of time.Time or
781
+ * if no custom marshaling is required.
782
+ *
783
+ * @param paramType the type to inspect
784
+ * @returns custom marshaling info or undefined
785
+ */
786
+ function isArrayOfDateTimeForMarshalling(paramType) {
787
+ if (paramType.kind !== "slice") {
788
+ return undefined;
789
+ }
790
+ if (paramType.elementType.kind !== "time") {
791
+ return undefined;
792
+ }
793
+ switch (paramType.elementType.format) {
794
+ case "PlainDate":
795
+ case "RFC1123":
796
+ case "RFC7231":
797
+ case "PlainTime":
798
+ case "Unix":
799
+ return {
800
+ format: paramType.elementType.format,
801
+ elemByVal: paramType.elementTypeByValue,
802
+ utc: paramType.elementType.utc,
803
+ };
804
+ case "RFC3339":
805
+ // RFC3339 normally uses the default time.Time marshaller, but utc slices
806
+ // must be normalized to UTC, which requires building the wrapper slice.
807
+ if (paramType.elementType.utc) {
808
+ return {
809
+ format: "RFC3339",
810
+ elemByVal: paramType.elementTypeByValue,
811
+ utc: true,
812
+ };
813
+ }
814
+ return undefined;
815
+ default:
816
+ return undefined;
817
+ }
818
+ }
819
+ //# sourceMappingURL=request-handler.js.map