typespec-rust-emitter 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/AGENTS.md +82 -80
  2. package/CHANGELOG.md +17 -0
  3. package/dist/src/decorators/cache_control.d.ts +6 -0
  4. package/dist/src/decorators/cache_control.js +9 -0
  5. package/dist/src/decorators/cache_control.js.map +1 -0
  6. package/dist/src/decorators/etag_cache.d.ts +6 -0
  7. package/dist/src/decorators/etag_cache.js +9 -0
  8. package/dist/src/decorators/etag_cache.js.map +1 -0
  9. package/dist/src/decorators/index.d.ts +6 -0
  10. package/dist/src/decorators/index.js +7 -0
  11. package/dist/src/decorators/index.js.map +1 -0
  12. package/dist/src/decorators/rust_attr.d.ts +3 -0
  13. package/dist/src/decorators/rust_attr.js +45 -0
  14. package/dist/src/decorators/rust_attr.js.map +1 -0
  15. package/dist/src/decorators/rust_derive.d.ts +3 -0
  16. package/dist/src/decorators/rust_derive.js +39 -0
  17. package/dist/src/decorators/rust_derive.js.map +1 -0
  18. package/dist/src/decorators/rust_impl.d.ts +2 -0
  19. package/dist/src/decorators/rust_impl.js +19 -0
  20. package/dist/src/decorators/rust_impl.js.map +1 -0
  21. package/dist/src/decorators/rust_self.d.ts +3 -0
  22. package/dist/src/decorators/rust_self.js +35 -0
  23. package/dist/src/decorators/rust_self.js.map +1 -0
  24. package/dist/src/emitter.d.ts +2 -11
  25. package/dist/src/emitter.js +7 -1282
  26. package/dist/src/emitter.js.map +1 -1
  27. package/dist/src/formatter/index.d.ts +2 -0
  28. package/dist/src/formatter/index.js +3 -0
  29. package/dist/src/formatter/index.js.map +1 -0
  30. package/dist/src/formatter/mappings.d.ts +4 -0
  31. package/dist/src/formatter/mappings.js +68 -0
  32. package/dist/src/formatter/mappings.js.map +1 -0
  33. package/dist/src/formatter/strings.d.ts +4 -0
  34. package/dist/src/formatter/strings.js +32 -0
  35. package/dist/src/formatter/strings.js.map +1 -0
  36. package/dist/src/generator/etag_router.d.ts +30 -0
  37. package/dist/src/generator/etag_router.js +123 -0
  38. package/dist/src/generator/etag_router.js.map +1 -0
  39. package/dist/src/generator/index.d.ts +5 -0
  40. package/dist/src/generator/index.js +6 -0
  41. package/dist/src/generator/index.js.map +1 -0
  42. package/dist/src/generator/response_enums.d.ts +6 -0
  43. package/dist/src/generator/response_enums.js +58 -0
  44. package/dist/src/generator/response_enums.js.map +1 -0
  45. package/dist/src/generator/router.d.ts +7 -0
  46. package/dist/src/generator/router.js +227 -0
  47. package/dist/src/generator/router.js.map +1 -0
  48. package/dist/src/generator/server_trait.d.ts +6 -0
  49. package/dist/src/generator/server_trait.js +97 -0
  50. package/dist/src/generator/server_trait.js.map +1 -0
  51. package/dist/src/generator/types_file.d.ts +11 -0
  52. package/dist/src/generator/types_file.js +209 -0
  53. package/dist/src/generator/types_file.js.map +1 -0
  54. package/dist/src/index.d.ts +1 -1
  55. package/dist/src/index.js +1 -1
  56. package/dist/src/index.js.map +1 -1
  57. package/dist/src/lib.js +1 -1
  58. package/dist/src/lib.js.map +1 -1
  59. package/dist/src/models/index.d.ts +2 -0
  60. package/dist/src/models/index.js +3 -0
  61. package/dist/src/models/index.js.map +1 -0
  62. package/dist/src/models/keys.d.ts +6 -0
  63. package/dist/src/models/keys.js +8 -0
  64. package/dist/src/models/keys.js.map +1 -0
  65. package/dist/src/models/types.d.ts +45 -0
  66. package/dist/src/models/types.js +2 -0
  67. package/dist/src/models/types.js.map +1 -0
  68. package/dist/src/parser/decorators.d.ts +18 -0
  69. package/dist/src/parser/decorators.js +28 -0
  70. package/dist/src/parser/decorators.js.map +1 -0
  71. package/dist/src/parser/index.d.ts +6 -0
  72. package/dist/src/parser/index.js +7 -0
  73. package/dist/src/parser/index.js.map +1 -0
  74. package/dist/src/parser/operations.d.ts +13 -0
  75. package/dist/src/parser/operations.js +127 -0
  76. package/dist/src/parser/operations.js.map +1 -0
  77. package/dist/src/parser/parameters.d.ts +5 -0
  78. package/dist/src/parser/parameters.js +98 -0
  79. package/dist/src/parser/parameters.js.map +1 -0
  80. package/dist/src/parser/responses.d.ts +13 -0
  81. package/dist/src/parser/responses.js +132 -0
  82. package/dist/src/parser/responses.js.map +1 -0
  83. package/dist/src/parser/routes.d.ts +4 -0
  84. package/dist/src/parser/routes.js +36 -0
  85. package/dist/src/parser/routes.js.map +1 -0
  86. package/dist/src/parser/types.d.ts +9 -0
  87. package/dist/src/parser/types.js +157 -0
  88. package/dist/src/parser/types.js.map +1 -0
  89. package/dist/test/etag_cache.test.d.ts +1 -0
  90. package/dist/test/etag_cache.test.js +62 -0
  91. package/dist/test/etag_cache.test.js.map +1 -0
  92. package/dist/test/test-host.d.ts +11 -0
  93. package/dist/test/test-host.js +28 -0
  94. package/dist/test/test-host.js.map +1 -1
  95. package/example/main.tsp +27 -1
  96. package/example/output-rust/Cargo.lock +48 -0
  97. package/example/output-rust/Cargo.toml +1 -0
  98. package/example/output-rust/src/generated/server.rs +122 -11
  99. package/example/output-rust/src/generated/types.rs +6 -0
  100. package/example/output-rust/src/main.rs +60 -27
  101. package/justfile +31 -2
  102. package/package.json +1 -1
  103. package/scripts/update-golden.js +36 -0
  104. package/src/decorators/cache_control.ts +14 -0
  105. package/src/decorators/etag_cache.ts +14 -0
  106. package/src/decorators/index.ts +6 -0
  107. package/src/decorators/rust_attr.ts +61 -0
  108. package/src/decorators/rust_derive.ts +55 -0
  109. package/src/decorators/rust_impl.ts +29 -0
  110. package/src/decorators/rust_self.ts +42 -0
  111. package/src/emitter.ts +18 -1654
  112. package/src/formatter/index.ts +2 -0
  113. package/src/formatter/mappings.ts +70 -0
  114. package/src/formatter/strings.ts +33 -0
  115. package/src/generator/etag_router.ts +147 -0
  116. package/src/generator/index.ts +5 -0
  117. package/src/generator/response_enums.ts +76 -0
  118. package/src/generator/router.ts +280 -0
  119. package/src/generator/server_trait.ts +134 -0
  120. package/src/generator/types_file.ts +297 -0
  121. package/src/index.ts +3 -1
  122. package/src/lib.ts +1 -1
  123. package/src/lib.tsp +3 -1
  124. package/src/models/index.ts +2 -0
  125. package/src/models/keys.ts +7 -0
  126. package/src/models/types.ts +54 -0
  127. package/src/parser/decorators.ts +34 -0
  128. package/src/parser/index.ts +6 -0
  129. package/src/parser/operations.ts +158 -0
  130. package/src/parser/parameters.ts +117 -0
  131. package/src/parser/responses.ts +170 -0
  132. package/src/parser/routes.ts +47 -0
  133. package/src/parser/types.ts +215 -0
  134. package/test/etag_cache.test.ts +69 -0
  135. package/test/golden/etag_cache/server.rs +109 -0
  136. package/test/golden/etag_cache/spec.tsp +20 -0
  137. package/test/golden/etag_cache/types.rs +13 -0
  138. package/test/test-host.ts +43 -0
@@ -1,1284 +1,9 @@
1
- import { emitFile, resolvePath, navigateProgram, getDoc, isArrayModelType, isRecordModelType, getFormat, getPattern, getNamespaceFullName, getTags, } from "@typespec/compiler";
2
- const rustDeriveKey = Symbol("rustDerive");
3
- const rustAttrKey = Symbol("rustAttr");
4
- const rustImplKey = Symbol("rustImpl");
5
- const rustSelfReceiverKey = Symbol("rustSelfReceiver");
6
- export function $rustDerive(context, target, derive) {
7
- if (target.kind !== "Model" && target.kind !== "Enum") {
8
- context.program.reportDiagnostic({
9
- code: "rust-derive-invalid-target",
10
- message: `@rustDerive can only be applied to models and enums`,
11
- severity: "error",
12
- target: context.decoratorTarget,
13
- });
14
- return;
15
- }
16
- const ns = target.kind === "Model"
17
- ? target.namespace
18
- ? getNamespaceFullName(target.namespace)
19
- : ""
20
- : target.namespace
21
- ? getNamespaceFullName(target.namespace)
22
- : "";
23
- if (!ns.startsWith("TypeSpec")) {
24
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
25
- const info = target[rustDeriveKey];
26
- if (info) {
27
- if (!info.derives.includes(derive)) {
28
- info.derives.push(derive);
29
- }
30
- }
31
- else {
32
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
33
- target[rustDeriveKey] = { derives: [derive] };
34
- }
35
- }
36
- }
37
- export function $rustDerives(context, target, ...derives) {
38
- for (const derive of derives) {
39
- $rustDerive(context, target, derive);
40
- }
41
- }
42
- export function $rustAttr(context, target, attr) {
43
- if (target.kind !== "Model" &&
44
- target.kind !== "Enum" &&
45
- target.kind !== "ModelProperty") {
46
- context.program.reportDiagnostic({
47
- code: "rust-attr-invalid-target",
48
- message: `@rustAttr can only be applied to models, enums, and model properties`,
49
- severity: "error",
50
- target: context.decoratorTarget,
51
- });
52
- return;
53
- }
54
- let ns;
55
- if (target.kind === "Model") {
56
- ns = target.namespace;
57
- }
58
- else if (target.kind === "Enum") {
59
- ns = target.namespace;
60
- }
61
- else if (target.kind === "ModelProperty") {
62
- ns = target.model?.namespace;
63
- }
64
- const nsFullName = ns ? getNamespaceFullName(ns) : "";
65
- if (!nsFullName.startsWith("TypeSpec")) {
66
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
67
- const info = target[rustAttrKey];
68
- if (info) {
69
- if (!info.attrs.includes(attr)) {
70
- info.attrs.push(attr);
71
- }
72
- }
73
- else {
74
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
75
- target[rustAttrKey] = { attrs: [attr] };
76
- }
77
- }
78
- }
79
- export function $rustAttrs(context, target, ...attrs) {
80
- for (const attr of attrs) {
81
- $rustAttr(context, target, attr);
82
- }
83
- }
84
- export function $rustImpl(context, target, impl) {
85
- if (target.kind !== "Model") {
86
- context.program.reportDiagnostic({
87
- code: "rust-impl-invalid-target",
88
- message: `@rustImpl can only be applied to models`,
89
- severity: "error",
90
- target: context.decoratorTarget,
91
- });
92
- return;
93
- }
94
- const ns = target.namespace ? getNamespaceFullName(target.namespace) : "";
95
- if (!ns.startsWith("TypeSpec")) {
96
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
97
- target[rustImplKey] = { impl: impl };
98
- }
99
- }
100
- export function $rustMut(context, target) {
101
- if (target.kind !== "Operation") {
102
- context.program.reportDiagnostic({
103
- code: "rust-mut-invalid-target",
104
- message: `@rustMut can only be applied to operations`,
105
- severity: "error",
106
- target: context.decoratorTarget,
107
- });
108
- return;
109
- }
110
- const ns = target.namespace ? getNamespaceFullName(target.namespace) : "";
111
- if (!ns.startsWith("TypeSpec")) {
112
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
113
- target[rustSelfReceiverKey] = "&mut self";
114
- }
115
- }
116
- export function $rustOwn(context, target) {
117
- if (target.kind !== "Operation") {
118
- context.program.reportDiagnostic({
119
- code: "rust-own-invalid-target",
120
- message: `@rustOwn can only be applied to operations`,
121
- severity: "error",
122
- target: context.decoratorTarget,
123
- });
124
- return;
125
- }
126
- const ns = target.namespace ? getNamespaceFullName(target.namespace) : "";
127
- if (!ns.startsWith("TypeSpec")) {
128
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
129
- target[rustSelfReceiverKey] = "self";
130
- }
131
- }
132
- function getDecoratorName(decorator) {
133
- if (!decorator)
134
- return "";
135
- if (typeof decorator !== "object")
136
- return "";
137
- if (decorator.node?.target?.sv) {
138
- return decorator.node.target.sv;
139
- }
140
- if (decorator.node?.target?.kind === "Identifier" &&
141
- decorator.node?.target?.sv) {
142
- return decorator.node.target.sv;
143
- }
144
- return "";
145
- }
146
- function getDecoratorArgValue(decorator, index = 0) {
147
- if (!decorator)
148
- return "";
149
- const args = decorator.args || decorator.arguments;
150
- if (!args)
151
- return "";
152
- const arg = args[index];
153
- if (arg?.jsValue !== undefined)
154
- return String(arg.jsValue);
155
- if (arg?.value !== undefined)
156
- return String(arg.value);
157
- return "";
158
- }
159
- function getHttpMethod(_program, operation) {
160
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
161
- const decorators = operation.decorators;
162
- if (!decorators)
163
- return undefined;
164
- for (const key of Object.keys(decorators)) {
165
- const decorator = decorators[key];
166
- const name = getDecoratorName(decorator);
167
- if (name === "get")
168
- return "GET";
169
- if (name === "post")
170
- return "POST";
171
- if (name === "put")
172
- return "PUT";
173
- if (name === "patch")
174
- return "PATCH";
175
- if (name === "delete")
176
- return "DELETE";
177
- if (name === "head")
178
- return "HEAD";
179
- }
180
- return undefined;
181
- }
182
- function getRoute(_program, target) {
183
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
184
- const decorators = target.decorators;
185
- if (!decorators)
186
- return "";
187
- for (const key of Object.keys(decorators)) {
188
- const decorator = decorators[key];
189
- const name = getDecoratorName(decorator);
190
- if (name === "route") {
191
- return getDecoratorArgValue(decorator, 0);
192
- }
193
- }
194
- return "";
195
- }
196
- function getFullRoute(program, ns) {
197
- const routes = [];
198
- let current = ns;
199
- while (current) {
200
- const route = getRoute(program, current);
201
- if (route) {
202
- routes.unshift(route);
203
- }
204
- current = current.namespace;
205
- }
206
- return routes.join("");
207
- }
208
- function hasAuthDecorator(operation) {
209
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
210
- const decorators = operation.decorators;
211
- if (!decorators)
212
- return false;
213
- for (const key of Object.keys(decorators)) {
214
- const decorator = decorators[key];
215
- const name = getDecoratorName(decorator);
216
- if (name === "useAuth") {
217
- return true;
218
- }
219
- }
220
- return false;
221
- }
222
- function getSelfReceiver(operation) {
223
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
224
- const receiver = operation[rustSelfReceiverKey];
225
- return receiver ?? "&self";
226
- }
227
- function getOperationParameters(program, operation, anonymousEnums) {
228
- const params = [];
229
- const model = operation.parameters;
230
- for (const [propName, prop] of model.properties) {
231
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
232
- const decorators = prop.decorators;
233
- // Skip body parameters - they are handled separately
234
- let isBody = false;
235
- if (decorators) {
236
- for (const key of Object.keys(decorators)) {
237
- const decorator = decorators[key];
238
- const name = getDecoratorName(decorator);
239
- if (name === "body" ||
240
- name === "bodyRoot" ||
241
- name === "multipartBody") {
242
- isBody = true;
243
- break;
244
- }
245
- }
246
- }
247
- if (isBody)
248
- continue;
249
- let location = "query";
250
- let rustName = toRustIdent(propName);
251
- if (decorators) {
252
- for (const key of Object.keys(decorators)) {
253
- const decorator = decorators[key];
254
- const name = getDecoratorName(decorator);
255
- if (name === "path") {
256
- location = "path";
257
- break;
258
- }
259
- else if (name === "query") {
260
- location = "query";
261
- break;
262
- }
263
- else if (name === "header") {
264
- location = "header";
265
- const headerVal = getDecoratorArgValue(decorator, 0);
266
- if (headerVal) {
267
- rustName = toRustIdent(headerVal);
268
- }
269
- break;
270
- }
271
- else if (name === "cookie") {
272
- location = "cookie";
273
- break;
274
- }
275
- }
276
- }
277
- const { type: rustType } = getRustTypeForProperty(prop.type, program, anonymousEnums);
278
- params.push({
279
- name: propName,
280
- rustName,
281
- rustType,
282
- location,
283
- required: !prop.optional,
284
- optional: prop.optional,
285
- });
286
- }
287
- return params;
288
- }
289
- function getOperationBody(operation) {
290
- for (const [_propName, prop] of operation.parameters.properties) {
291
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
292
- const decorators = prop.decorators;
293
- if (!decorators)
294
- continue;
295
- for (const key of Object.keys(decorators)) {
296
- const decorator = decorators[key];
297
- const name = getDecoratorName(decorator);
298
- if (name === "body" || name === "bodyRoot" || name === "multipartBody") {
299
- return prop;
300
- }
301
- }
302
- }
303
- return undefined;
304
- }
305
- function hasMultipartBody(operation) {
306
- for (const [_propName, prop] of operation.parameters.properties) {
307
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
308
- const decorators = prop.decorators;
309
- if (!decorators)
310
- continue;
311
- for (const key of Object.keys(decorators)) {
312
- const decorator = decorators[key];
313
- const name = getDecoratorName(decorator);
314
- if (name === "multipartBody") {
315
- return true;
316
- }
317
- }
318
- }
319
- return false;
320
- }
321
- function getOperationResponses(program, operation, anonymousEnums) {
322
- const responses = [];
323
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
324
- const returnType = operation.returnType;
325
- // Check for Array return type first (use runtime check since TS doesn't narrow Array)
326
- if (returnType.kind !== "Union" &&
327
- returnType.kind !== "Model" &&
328
- returnType.valueType) {
329
- // This is an Array type
330
- const { type: rustType } = getRustTypeForProperty(returnType.valueType, program, anonymousEnums);
331
- responses.push({
332
- statusCode: 200,
333
- bodyType: rustType,
334
- bodyDescription: "",
335
- });
336
- return responses;
337
- }
338
- if (returnType.kind === "Union") {
339
- const union = returnType;
340
- for (const variant of union.variants.values()) {
341
- const statusCode = getStatusCode(variant);
342
- const bodyInfo = getBodyFromResponse(variant, program, anonymousEnums);
343
- responses.push({
344
- statusCode,
345
- bodyType: bodyInfo.type,
346
- bodyDescription: bodyInfo.description,
347
- isSse: bodyInfo.isSse,
348
- });
349
- }
350
- }
351
- else if (returnType.kind === "Model") {
352
- const model = returnType;
353
- if (model.name === "SSEStream") {
354
- responses.push({
355
- statusCode: 200,
356
- bodyType: "axum::response::Response",
357
- bodyDescription: "Server-Sent Events stream",
358
- isSse: true,
359
- });
360
- return responses;
361
- }
362
- let foundStatusCode = false;
363
- for (const [propName, prop] of model.properties) {
364
- if (propName === "body") {
365
- const { type: rustType } = getRustTypeForProperty(prop.type, program, anonymousEnums);
366
- responses.push({
367
- statusCode: 200,
368
- bodyType: rustType,
369
- bodyDescription: getDoc(program, prop),
370
- });
371
- }
372
- else if (propName === "statusCode") {
373
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
374
- const typeAny = prop.type;
375
- if (typeAny.value !== undefined) {
376
- const statusCode = typeAny.value;
377
- responses.push({
378
- statusCode,
379
- bodyType: undefined,
380
- bodyDescription: undefined,
381
- });
382
- foundStatusCode = true;
383
- }
384
- }
385
- }
386
- if (!foundStatusCode && responses.length === 0) {
387
- responses.push({
388
- statusCode: 200,
389
- bodyType: undefined,
390
- bodyDescription: undefined,
391
- });
392
- }
393
- }
394
- return responses;
395
- }
396
- function getStatusCode(variant) {
397
- if (variant.type.kind === "Model") {
398
- const model = variant.type;
399
- for (const [propName, prop] of model.properties) {
400
- if (propName === "statusCode") {
401
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
402
- const typeAny = prop.type;
403
- if (typeAny.value !== undefined) {
404
- return typeAny.value;
405
- }
406
- }
407
- }
408
- }
409
- return 200;
410
- }
411
- function getBodyFromResponse(variant, program, anonymousEnums) {
412
- if (variant.type.kind === "Model") {
413
- const model = variant.type;
414
- if (model.name === "SSEStream") {
415
- return {
416
- type: "axum::response::Response",
417
- description: "Server-Sent Events stream",
418
- isSse: true,
419
- };
420
- }
421
- for (const [_propName, prop] of model.properties) {
422
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
423
- const decorators = prop.decorators;
424
- let isBody = false;
425
- if (decorators) {
426
- for (const key of Object.keys(decorators)) {
427
- const decorator = decorators[key];
428
- const name = getDecoratorName(decorator);
429
- if (name === "body" || name === "bodyRoot") {
430
- isBody = true;
431
- break;
432
- }
433
- }
434
- }
435
- if (isBody) {
436
- const { type: rustType } = getRustTypeForProperty(prop.type, program, anonymousEnums);
437
- return { type: rustType, description: getDoc(program, prop) };
438
- }
439
- }
440
- }
441
- return { type: undefined, description: undefined };
442
- }
443
- function getAllOperations(program) {
444
- const seenNamespaces = new Set();
445
- const namespaceOps = new Map();
446
- navigateProgram(program, {
447
- namespace(ns) {
448
- const route = getRoute(program, ns);
449
- if (!route)
450
- return;
451
- const fullName = getNamespaceFullName(ns);
452
- if (!seenNamespaces.has(fullName)) {
453
- seenNamespaces.add(fullName);
454
- namespaceOps.set(fullName, { ns, ops: [] });
455
- }
456
- },
457
- operation(op) {
458
- const method = getHttpMethod(program, op);
459
- if (!method)
460
- return;
461
- const ns = op.namespace;
462
- if (!ns)
463
- return;
464
- const fullName = getNamespaceFullName(ns);
465
- if (!seenNamespaces.has(fullName)) {
466
- seenNamespaces.add(fullName);
467
- namespaceOps.set(fullName, { ns, ops: [] });
468
- }
469
- const entry = namespaceOps.get(fullName);
470
- if (entry) {
471
- entry.ops.push(op);
472
- }
473
- },
474
- });
475
- const result = [];
476
- for (const [, entry] of namespaceOps) {
477
- if (entry.ops.length > 0) {
478
- result.push({ namespace: entry.ns, operations: entry.ops });
479
- }
480
- }
481
- return result;
482
- }
483
- function buildFullPath(namespaceRoute, operationRoute) {
484
- let fullPath = namespaceRoute + operationRoute;
485
- fullPath = fullPath.replace(/\/+/g, "/");
486
- if (fullPath.length > 1 && fullPath.endsWith("/")) {
487
- fullPath = fullPath.slice(0, -1);
488
- }
489
- return fullPath;
490
- }
491
- function emitOperationInfo(program, op, nsRoute, anonymousEnums) {
492
- const method = getHttpMethod(program, op);
493
- if (!method)
494
- return undefined;
495
- const opRoute = getRoute(program, op);
496
- const fullPath = buildFullPath(nsRoute, opRoute);
497
- const tags = getTags(program, op) ?? [];
498
- const params = getOperationParameters(program, op, anonymousEnums);
499
- const body = getOperationBody(op);
500
- const responses = getOperationResponses(program, op, anonymousEnums);
501
- const doc = getDoc(program, op);
502
- const opName = op.name.replace(/[^a-zA-Z0-9_]/g, "_");
503
- return {
504
- name: opName,
505
- method,
506
- path: fullPath,
507
- tags,
508
- parameters: params,
509
- body: body,
510
- responses,
511
- doc,
512
- };
513
- }
514
- function getStatusVariantName(statusCode) {
515
- const statusNames = {
516
- 200: "Ok",
517
- 201: "Created",
518
- 202: "Accepted",
519
- 204: "NoContent",
520
- 400: "BadRequest",
521
- 401: "Unauthorized",
522
- 403: "Forbidden",
523
- 404: "NotFound",
524
- 409: "Conflict",
525
- 500: "InternalServerError",
526
- };
527
- return statusNames[statusCode] || `Status${statusCode}`;
528
- }
529
- function getHttpStatusCode(statusCode) {
530
- const statusCodes = {
531
- 200: "StatusCode::OK",
532
- 201: "StatusCode::CREATED",
533
- 202: "StatusCode::ACCEPTED",
534
- 204: "StatusCode::NO_CONTENT",
535
- 400: "StatusCode::BAD_REQUEST",
536
- 401: "StatusCode::UNAUTHORIZED",
537
- 403: "StatusCode::FORBIDDEN",
538
- 404: "StatusCode::NOT_FOUND",
539
- 409: "StatusCode::CONFLICT",
540
- 500: "StatusCode::INTERNAL_SERVER_ERROR",
541
- };
542
- return statusCodes[statusCode] || `StatusCode::from_u16(${statusCode})`;
543
- }
544
- function generateServerTrait(program, namespaceGroups, anonymousEnums) {
545
- const parts = [];
546
- parts.push(`use super::types::*;
547
- use async_trait::async_trait;
548
- use axum::extract::Path;
549
- use axum::Extension;
550
- use axum::http::StatusCode;
551
- use axum::response::IntoResponse;
552
- use axum::Json;
553
- use eyre::Result;
554
-
555
- #[async_trait]
556
- pub trait Server: Send + Sync {
557
- type Claims: Send + Sync + 'static;
558
-
559
- `);
560
- for (const group of namespaceGroups) {
561
- const nsName = toPascalCase(group.namespace.name.replace(/[^a-zA-Z0-9_]/g, "_"));
562
- for (const op of group.operations) {
563
- const opInfo = emitOperationInfo(program, op, "", anonymousEnums);
564
- if (!opInfo)
565
- continue;
566
- if (opInfo.doc) {
567
- parts.push(` ${formatDoc(opInfo.doc)}`);
568
- }
569
- const responseName = `${nsName}${toPascalCase(opInfo.name)}Response`;
570
- const fnName = toRustIdent(`${nsName}_${opInfo.name}`);
571
- const isProtected = hasAuthDecorator(op);
572
- // Build parameter list for the trait method
573
- const paramParts = [];
574
- // Add path parameters
575
- for (const param of opInfo.parameters) {
576
- if (param.location === "path") {
577
- paramParts.push(`${param.rustName}: ${param.rustType}`);
578
- }
579
- }
580
- // Add query parameters
581
- for (const param of opInfo.parameters) {
582
- if (param.location === "query") {
583
- paramParts.push(`${param.rustName}: ${param.rustType}`);
584
- }
585
- }
586
- // Add body parameter
587
- if (opInfo.body) {
588
- if (hasMultipartBody(op)) {
589
- paramParts.push(`body: Multipart`);
590
- }
591
- else {
592
- const bodyType = getRustTypeForProperty(opInfo.body.type, program, anonymousEnums);
593
- paramParts.push(`body: ${bodyType.type}`);
594
- }
595
- }
596
- const paramsStr = paramParts.join(", ");
597
- const selfReceiver = getSelfReceiver(op);
598
- if (isProtected) {
599
- if (paramsStr) {
600
- parts.push(` async fn ${fnName}(${selfReceiver}, claims: Self::Claims, ${paramsStr}) -> Result<${responseName}>;`);
601
- }
602
- else {
603
- parts.push(` async fn ${fnName}(${selfReceiver}, claims: Self::Claims) -> Result<${responseName}>;`);
604
- }
605
- }
606
- else {
607
- if (paramsStr) {
608
- parts.push(` async fn ${fnName}(${selfReceiver}, ${paramsStr}) -> Result<${responseName}>;`);
609
- }
610
- else {
611
- parts.push(` async fn ${fnName}(${selfReceiver}) -> Result<${responseName}>;`);
612
- }
613
- }
614
- }
615
- }
616
- parts.push("}");
617
- return parts.join("\n");
618
- }
619
- function generateResponseEnums(program, namespaceGroups, anonymousEnums) {
620
- const parts = [];
621
- for (const group of namespaceGroups) {
622
- const nsName = toPascalCase(group.namespace.name.replace(/[^a-zA-Z0-9_]/g, "_"));
623
- for (const op of group.operations) {
624
- const opInfo = emitOperationInfo(program, op, "", anonymousEnums);
625
- if (!opInfo)
626
- continue;
627
- if (opInfo.responses.length === 0)
628
- continue;
629
- const responseName = `${nsName}${toPascalCase(opInfo.name)}Response`;
630
- const variants = [];
631
- for (const resp of opInfo.responses) {
632
- const variantName = getStatusVariantName(resp.statusCode);
633
- if (!resp.bodyType) {
634
- variants.push(` ${variantName},`);
635
- }
636
- else if (resp.isSse) {
637
- variants.push(` ${variantName}(${resp.bodyType}),`);
638
- }
639
- else {
640
- variants.push(` ${variantName}(Json<${resp.bodyType}>),`);
641
- }
642
- }
643
- parts.push(`#[allow(clippy::type_complexity)]
644
- pub enum ${responseName} {
645
- ${variants.join("\n")}
646
- }
647
- `);
648
- parts.push(`impl IntoResponse for ${responseName} {
649
- fn into_response(self) -> axum::response::Response {
650
- match self {
651
- `);
652
- for (const resp of opInfo.responses) {
653
- const variantName = getStatusVariantName(resp.statusCode);
654
- const statusCodeStr = getHttpStatusCode(resp.statusCode);
655
- if (!resp.bodyType) {
656
- parts.push(` ${responseName}::${variantName} => ${statusCodeStr}.into_response(),`);
657
- }
658
- else if (resp.isSse) {
659
- parts.push(` ${responseName}::${variantName}(body) => body.into_response(),`);
660
- }
661
- else {
662
- parts.push(` ${responseName}::${variantName}(body) => (${statusCodeStr}, body).into_response(),`);
663
- }
664
- }
665
- parts.push(` }
666
- }
667
- }
668
- `);
669
- }
670
- }
671
- return parts.join("\n");
672
- }
673
- function generateRouter(program, namespaceGroups, anonymousEnums) {
674
- const handlers = [];
675
- const queryTypeStructs = [];
676
- const publicRoutes = [];
677
- const protectedRoutes = [];
678
- const usedMethods = new Set();
679
- for (const group of namespaceGroups) {
680
- const nsRoute = getFullRoute(program, group.namespace);
681
- if (!nsRoute)
682
- continue;
683
- const nsName = toPascalCase(group.namespace.name.replace(/[^a-zA-Z0-9_]/g, "_"));
684
- for (const op of group.operations) {
685
- const opInfo = emitOperationInfo(program, op, nsRoute, anonymousEnums);
686
- if (!opInfo)
687
- continue;
688
- const method = opInfo.method.toLowerCase();
689
- usedMethods.add(method);
690
- const handlerFnName = toRustIdent(`${nsName}_${opInfo.name}`);
691
- const traitFnName = handlerFnName;
692
- const isProtected = hasAuthDecorator(op);
693
- const selfReceiver = getSelfReceiver(op);
694
- const pathParams = opInfo.parameters.filter((p) => p.location === "path");
695
- const hasPathParams = pathParams.length > 0;
696
- const queryParams = opInfo.parameters.filter((p) => p.location === "query");
697
- const hasQueryParams = queryParams.length > 0;
698
- const hasBody = !!opInfo.body;
699
- const isMultipartBody = hasMultipartBody(op);
700
- // Build extractor lines and server method call arguments
701
- // IMPORTANT: axum requires specific extractor order:
702
- // State -> Extension -> Path -> Query -> Json/Multipart -> Body
703
- const extractorLines = [];
704
- const serverArgs = [];
705
- // State is always first (added in handler template)
706
- const serviceBinding = selfReceiver === "&mut self" ? "mut service" : "service";
707
- // Extension (claims) comes after State
708
- if (isProtected) {
709
- extractorLines.push(` Extension(claims): Extension<S::Claims>,`);
710
- serverArgs.push(`claims`);
711
- }
712
- // Path params come after Extension
713
- if (hasPathParams) {
714
- const pathTypes = pathParams.map((p) => p.rustType).join(", ");
715
- const pathFields = pathParams.map((p) => p.rustName).join(", ");
716
- if (pathParams.length === 1) {
717
- extractorLines.push(` Path(${pathFields}): Path<${pathTypes}>,`);
718
- }
719
- else {
720
- extractorLines.push(` Path((${pathFields})): Path<(${pathTypes})>,`);
721
- }
722
- // Add path params to server method args
723
- for (const param of pathParams) {
724
- serverArgs.push(param.rustName);
725
- }
726
- }
727
- // Query params come after Path
728
- if (hasQueryParams && queryParams.length > 0) {
729
- const queryTypeName = `${toPascalCase(handlerFnName)}Query`;
730
- const queryFields = queryParams
731
- .map((p) => ` #[serde(rename = "${p.name}")]\n pub ${p.rustName}: ${p.rustType}`)
732
- .join(",\n");
733
- queryTypeStructs.push(`#[derive(Debug, Clone, serde::Deserialize)]\npub struct ${queryTypeName} {\n${queryFields}\n}`);
734
- extractorLines.push(` Query(params): Query<${queryTypeName}>,`);
735
- for (const param of queryParams) {
736
- serverArgs.push(`params.${param.rustName}`);
737
- }
738
- }
739
- // Body comes last (Json or Multipart based on decorator)
740
- if (hasBody && opInfo.body) {
741
- if (isMultipartBody) {
742
- extractorLines.push(` multipart: axum::extract::Multipart,`);
743
- serverArgs.push(`multipart`);
744
- }
745
- else {
746
- const bodyType = getRustTypeForProperty(opInfo.body.type, program, anonymousEnums);
747
- extractorLines.push(` Json(payload): Json<${bodyType.type}>,`);
748
- serverArgs.push(`payload`);
749
- }
750
- }
751
- // Build server method call
752
- const serverArgsStr = serverArgs.join(", ");
753
- const serverCall = `service.${traitFnName}(${serverArgsStr}).await`;
754
- // All handlers use <S> generics, Claims is now an associated type
755
- // For &mut self, we need Clone because service is extracted multiple times
756
- // For self, we can't use Clone (would need Arc/Mutex or different pattern)
757
- const needsClone = selfReceiver !== "self" ? "+ Clone" : "";
758
- const handlerCode = selfReceiver === "self"
759
- ? `// NOTE: ${handlerFnName} takes self and cannot be used with the router pattern.
760
- // It consumes the service, so you need to implement your own handler pattern.
761
- pub async fn ${handlerFnName}_handler<S>(
762
- axum::extract::State(service): axum::extract::State<S>,
763
- ${extractorLines.join("\n")}
764
- ) -> impl axum::response::IntoResponse
765
- where
766
- S: Server + Send + Sync + 'static,
767
- S::Claims: Send + Sync + Clone + 'static,
768
- {
769
- let result = service.${traitFnName}(${serverArgsStr}).await;
770
- match result {
771
- Ok(response) => response.into_response(),
772
- Err(e) => (
773
- axum::http::StatusCode::INTERNAL_SERVER_ERROR,
774
- format!("Internal error: {e}"),
775
- )
776
- .into_response(),
777
- }
778
- }`
779
- : `pub async fn ${handlerFnName}_handler<S>(
780
- axum::extract::State(${serviceBinding}): axum::extract::State<S>,
781
- ${extractorLines.join("\n")}
782
- ) -> impl axum::response::IntoResponse
783
- where
784
- S: Server${needsClone} + Send + Sync + 'static,
785
- S::Claims: Send + Sync + Clone + 'static,
786
- {
787
- let result = ${serverCall};
788
- match result {
789
- Ok(response) => response.into_response(),
790
- Err(e) => (
791
- axum::http::StatusCode::INTERNAL_SERVER_ERROR,
792
- format!("Internal error: {e}"),
793
- )
794
- .into_response(),
795
- }
796
- }`;
797
- handlers.push(handlerCode);
798
- // Don't add routes for self methods (they consume the service)
799
- if (selfReceiver === "self") {
800
- continue;
801
- }
802
- const routePath = `"${opInfo.path}"`;
803
- let routeStmt = "";
804
- if (isProtected) {
805
- routeStmt = `.route(${routePath}, ${method}(${handlerFnName}_handler::<S>))`;
806
- protectedRoutes.push(routeStmt);
807
- }
808
- else {
809
- routeStmt = `.route(${routePath}, ${method}(${handlerFnName}_handler::<S>))`;
810
- publicRoutes.push(routeStmt);
811
- }
812
- }
813
- }
814
- const methodImports = Array.from(usedMethods).sort().join(", ");
815
- const routerBody = buildRouterBody(publicRoutes, protectedRoutes);
816
- const parts = [];
817
- parts.push(`use axum::extract::{Query, Multipart};
818
- use axum::routing::{${methodImports}};
819
- use axum::Router;
820
-
821
- `);
822
- if (queryTypeStructs.length > 0) {
823
- parts.push(queryTypeStructs.join("\n\n"));
824
- parts.push("\n\n");
825
- }
826
- parts.push(handlers.join("\n\n"));
827
- parts.push(`
828
- pub fn create_router<S, M>(service: S, middleware: M) -> Router
829
- where
830
- S: Server + Clone + Send + Sync + 'static,
831
- S::Claims: Send + Sync + Clone + 'static,
832
- M: FnOnce(Router<S>) -> Router<S> + Clone + Send + Sync + 'static,
833
- {
834
- ${routerBody}
835
- }`);
836
- return parts.join("\n");
837
- }
838
- function buildRouterBody(publicRoutes, protectedRoutes) {
839
- const lines = [];
840
- lines.push(" let mut router = Router::new();");
841
- if (publicRoutes.length > 0) {
842
- lines.push(" let public = Router::new()");
843
- for (const r of publicRoutes) {
844
- lines.push(` ${r.trim()}`);
845
- }
846
- lines.push(" ;");
847
- lines.push(" router = router.merge(public);");
848
- }
849
- if (protectedRoutes.length > 0) {
850
- lines.push(" let protected = Router::new()");
851
- for (const r of protectedRoutes) {
852
- lines.push(` ${r.trim()}`);
853
- }
854
- lines.push(" ;");
855
- lines.push(" router = router.merge(middleware(protected));");
856
- }
857
- lines.push(" router.with_state(service)");
858
- return lines.join("\n");
859
- }
860
- const scalarToRust = {
861
- string: "String",
862
- int8: "i8",
863
- int16: "i16",
864
- int32: "i32",
865
- int64: "i64",
866
- uint8: "u8",
867
- uint16: "u16",
868
- uint32: "u32",
869
- uint64: "u64",
870
- float32: "f32",
871
- float64: "f64",
872
- boolean: "bool",
873
- bytes: "Vec<u8>",
874
- plainDate: "chrono::NaiveDate",
875
- plainTime: "chrono::NaiveTime",
876
- utcDateTime: "chrono::DateTime<chrono::Utc>",
877
- offsetDateTime: "chrono::DateTime<chrono::FixedOffset>",
878
- plainDateTime: "chrono::NaiveDateTime",
879
- duration: "String",
880
- numeric: "f64",
881
- integer: "i64",
882
- float: "f64",
883
- safeint: "i64",
884
- decimal: "f64",
885
- decimal128: "f64",
886
- url: "String",
887
- };
888
- const formatToRust = {
889
- uuid: "uuid::Uuid",
890
- date: "chrono::NaiveDate",
891
- time: "chrono::NaiveTime",
892
- dateTime: "chrono::DateTime<chrono::Utc>",
893
- "date-time": "chrono::DateTime<chrono::Utc>",
894
- };
895
- const typeSpecNamespaces = new Set([
896
- "TypeSpec",
897
- "@typespec/http",
898
- "@typespec/rest",
899
- "@typespec/openapi",
900
- "@typespec/openapi3",
901
- "@typespec/json-schema",
902
- ]);
903
- function isStdLibNamespace(ns) {
904
- if (!ns)
905
- return false;
906
- const fullName = ns.name;
907
- if (typeSpecNamespaces.has(fullName))
908
- return true;
909
- if (ns.namespace)
910
- return isStdLibNamespace(ns.namespace);
911
- return false;
912
- }
913
- function isStdLibType(type) {
914
- if ("namespace" in type) {
915
- const ns = type.namespace;
916
- if (isStdLibNamespace(ns))
917
- return true;
918
- }
919
- return false;
920
- }
921
- function getRustTypeForProperty(type, program, anonymousEnums) {
922
- const kind = type.kind;
923
- if (kind === "Model") {
924
- const model = type;
925
- if (isArrayModelType(model) && model.indexer?.value) {
926
- const element = getRustTypeForProperty(model.indexer.value, program, anonymousEnums);
927
- return { type: `Vec<${element.type}>`, isStringLiteral: false };
928
- }
929
- if (isRecordModelType(model) && model.indexer?.value) {
930
- const value = getRustTypeForProperty(model.indexer.value, program, anonymousEnums);
931
- return {
932
- type: `std::collections::HashMap<String, ${value.type}>`,
933
- isStringLiteral: false,
934
- };
935
- }
936
- return { type: toPascalCase(model.name), isStringLiteral: false };
937
- }
938
- if (kind === "ModelProperty") {
939
- return getRustTypeForProperty(type.type, program, anonymousEnums);
940
- }
941
- if (kind === "Enum") {
942
- return { type: toPascalCase(type.name), isStringLiteral: false };
943
- }
944
- if (kind === "Union") {
945
- const unionType = type;
946
- const variants = Array.from(unionType.variants.values());
947
- const allStringLiterals = variants.every((v) => v.type.kind === "String");
948
- if (allStringLiterals) {
949
- if (unionType.name) {
950
- return {
951
- type: toPascalCase(unionType.name),
952
- isStringLiteral: false,
953
- };
954
- }
955
- const values = variants.map((v) => v.type.value);
956
- const sanitized = values.map((v) => v.replace(/_/g, ""));
957
- const firstTwo = sanitized.slice(0, 2).map(toPascalCase).join("");
958
- const enumName = `Enum${firstTwo}${sanitized.length}`;
959
- if (!anonymousEnums.has(enumName)) {
960
- anonymousEnums.set(enumName, {
961
- enumName,
962
- variants: variants.map((v) => v.type),
963
- });
964
- }
965
- return { type: enumName, isStringLiteral: false };
966
- }
967
- const nonNullVariants = variants.filter((v) => {
968
- const vt = v.type;
969
- if (vt.kind === "Null")
970
- return false;
971
- if (vt.kind === "Intrinsic" &&
972
- vt.name === "null")
973
- return false;
974
- return true;
975
- });
976
- if (nonNullVariants.length === 1 &&
977
- (variants.length === 2 ||
978
- variants.some((v) => {
979
- const vt = v.type;
980
- return (vt.kind === "Null" ||
981
- (vt.kind === "Intrinsic" &&
982
- vt.name === "null"));
983
- }))) {
984
- const vt = getRustTypeForProperty(nonNullVariants[0].type, program, anonymousEnums);
985
- return { type: `Option<${vt.type}>`, isStringLiteral: false };
986
- }
987
- const variantStrings = [];
988
- for (const v of variants) {
989
- const vt = v.type;
990
- if (vt.kind === "Null")
991
- continue;
992
- if (vt.kind === "Intrinsic" &&
993
- vt.name === "null")
994
- continue;
995
- const rustVt = getRustTypeForProperty(vt, program, anonymousEnums);
996
- variantStrings.push(rustVt.type);
997
- }
998
- const uniqueTypes = [...new Set(variantStrings)];
999
- const resultType = uniqueTypes.length === 1
1000
- ? uniqueTypes[0]
1001
- : `(${uniqueTypes.join(" | ")})`;
1002
- return { type: resultType, isStringLiteral: false };
1003
- }
1004
- if (kind === "Scalar") {
1005
- const scalar = type;
1006
- const format = getFormat(program, scalar);
1007
- const pattern = getPattern(program, scalar);
1008
- if (format && formatToRust[format] && !pattern) {
1009
- return { type: formatToRust[format], isStringLiteral: false };
1010
- }
1011
- if (pattern) {
1012
- return { type: toPascalCase(scalar.name), isStringLiteral: false };
1013
- }
1014
- return {
1015
- type: scalarToRust[scalar.name] ?? scalar.name,
1016
- isStringLiteral: false,
1017
- };
1018
- }
1019
- if (kind === "Intrinsic") {
1020
- const intrinsic = type;
1021
- const format = getFormat(program, type);
1022
- if (format && formatToRust[format]) {
1023
- return { type: formatToRust[format], isStringLiteral: false };
1024
- }
1025
- return {
1026
- type: scalarToRust[intrinsic.name] ?? "serde_json::Value",
1027
- isStringLiteral: false,
1028
- };
1029
- }
1030
- if (kind === "String") {
1031
- return { type: "String", isStringLiteral: false };
1032
- }
1033
- if (kind === "StringLiteral") {
1034
- return {
1035
- type: "String",
1036
- isStringLiteral: true,
1037
- stringLiteralValue: type.value,
1038
- };
1039
- }
1040
- if (kind === "Boolean" || kind === "BooleanLiteral") {
1041
- return { type: "bool", isStringLiteral: false };
1042
- }
1043
- if (kind === "Number" || kind === "NumericLiteral") {
1044
- return { type: "f64", isStringLiteral: false };
1045
- }
1046
- return { type: "serde_json::Value", isStringLiteral: false };
1047
- }
1048
- function toRustIdent(name) {
1049
- const snakeCase = name.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase();
1050
- const result = snakeCase.replace(/[^a-z0-9_]/g, "_");
1051
- if (/^[0-9]/.test(result)) {
1052
- return "_" + result;
1053
- }
1054
- return result;
1055
- }
1056
- function toPascalCase(name) {
1057
- if (/^[^a-z]+$/.test(name)) {
1058
- return name;
1059
- }
1060
- if (/[-_]/.test(name)) {
1061
- return name
1062
- .split(/[-_]/)
1063
- .map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
1064
- .join("");
1065
- }
1066
- return name.charAt(0).toUpperCase() + name.slice(1);
1067
- }
1068
- function toRustVariantName(name) {
1069
- return toPascalCase(name);
1070
- }
1071
- function formatDoc(doc) {
1072
- if (!doc)
1073
- return "";
1074
- return doc
1075
- .split("\n")
1076
- .map((line) => `/// ${line.trim()}`)
1077
- .join("\n");
1078
- }
1079
- function emitStringLiteralUnion(union) {
1080
- const parts = [];
1081
- const name = toPascalCase(union.name ?? "Value");
1082
- const variants = Array.from(union.variants.values());
1083
- parts.push(`#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Serialize, serde::Deserialize)]\n#[allow(clippy::enum_variant_names)]\npub enum ${name} {`);
1084
- for (let i = 0; i < variants.length; i++) {
1085
- const literalType = variants[i].type;
1086
- const variantName = toPascalCase(literalType.value);
1087
- const serdeValue = literalType.value;
1088
- if (i === 0) {
1089
- parts.push(` #[default]`);
1090
- }
1091
- parts.push(` #[serde(rename = "${serdeValue}")]`);
1092
- parts.push(` ${variantName},`);
1093
- }
1094
- parts.push("}");
1095
- return parts.join("\n");
1096
- }
1097
- function emitModel(model, program, anonymousEnums) {
1098
- const parts = [];
1099
- const name = toPascalCase(model.name);
1100
- const allProps = getAllProperties(model, program);
1101
- const deriveAttrs = [
1102
- "Debug",
1103
- "Clone",
1104
- "serde::Serialize",
1105
- "serde::Deserialize",
1106
- ];
1107
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1108
- const customDerives = model[rustDeriveKey];
1109
- if (customDerives) {
1110
- deriveAttrs.push(...customDerives.derives);
1111
- }
1112
- parts.push(`#[derive(${deriveAttrs.join(", ")})]`);
1113
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1114
- const customAttrs = model[rustAttrKey];
1115
- if (customAttrs) {
1116
- for (const attr of customAttrs.attrs) {
1117
- parts.push(`#[${attr}]`);
1118
- }
1119
- }
1120
- if (allProps.size > 0) {
1121
- const fields = [];
1122
- for (const [propName, prop] of allProps) {
1123
- const doc = getDoc(program, prop);
1124
- const { type: rustType } = getRustTypeForProperty(prop.type, program, anonymousEnums);
1125
- const optional = prop.optional ? true : false;
1126
- const fieldName = toRustIdent(propName);
1127
- const serdeRename = propName !== fieldName ? `#[serde(rename = "${propName}")]` : "";
1128
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1129
- const propAttrs = prop[rustAttrKey];
1130
- if (doc) {
1131
- fields.push(` ${formatDoc(doc)}`);
1132
- }
1133
- if (propAttrs) {
1134
- for (const attr of propAttrs.attrs) {
1135
- fields.push(` #[${attr}]`);
1136
- }
1137
- }
1138
- if (serdeRename) {
1139
- fields.push(` ${serdeRename}`);
1140
- }
1141
- if (optional) {
1142
- fields.push(` #[serde(skip_serializing_if = "Option::is_none")]`);
1143
- }
1144
- fields.push(` pub ${fieldName}: ${optional ? `Option<${rustType}>` : rustType},`);
1145
- }
1146
- parts.push(`pub struct ${name} {
1147
- ${fields.join("\n")}
1148
- }`);
1149
- }
1150
- else {
1151
- parts.push(`pub struct ${name}`);
1152
- parts.push("(());");
1153
- }
1154
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1155
- const customImpl = model[rustImplKey];
1156
- if (customImpl) {
1157
- parts.push(`
1158
- ${customImpl.impl}`);
1159
- }
1160
- return parts.join("\n");
1161
- }
1162
- function getAllProperties(model, _program) {
1163
- const props = new Map();
1164
- if (model.baseModel) {
1165
- const baseProps = getAllProperties(model.baseModel, _program);
1166
- for (const [key, value] of baseProps) {
1167
- props.set(key, value);
1168
- }
1169
- }
1170
- for (const [key, value] of model.properties) {
1171
- props.set(key, value);
1172
- }
1173
- return props;
1174
- }
1175
- function emitEnum(enumType) {
1176
- const parts = [];
1177
- const name = toPascalCase(enumType.name);
1178
- const members = Array.from(enumType.members.values());
1179
- const isString = members.every((m) => m.value === undefined || typeof m.value === "string");
1180
- const baseDerives = [
1181
- "Debug",
1182
- "Clone",
1183
- "Copy",
1184
- "PartialEq",
1185
- "Eq",
1186
- "Hash",
1187
- "Default",
1188
- "serde::Serialize",
1189
- "serde::Deserialize",
1190
- ];
1191
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1192
- const customDerives = enumType[rustDeriveKey];
1193
- const allDerives = [...baseDerives];
1194
- if (customDerives) {
1195
- allDerives.push(...customDerives.derives);
1196
- }
1197
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1198
- const customAttrs = enumType[rustAttrKey];
1199
- const attrLines = [];
1200
- if (customAttrs) {
1201
- for (const attr of customAttrs.attrs) {
1202
- attrLines.push(`#[${attr}]`);
1203
- }
1204
- }
1205
- if (isString) {
1206
- parts.push(`#[derive(${allDerives.join(", ")})]`);
1207
- if (attrLines.length > 0) {
1208
- parts.push(...attrLines);
1209
- }
1210
- parts.push(`pub enum ${name} {`);
1211
- for (let i = 0; i < members.length; i++) {
1212
- const variantName = toRustVariantName(members[i].name);
1213
- const serdeValue = members[i].value ?? members[i].name;
1214
- if (i === 0) {
1215
- parts.push(` #[default]`);
1216
- }
1217
- parts.push(` #[serde(rename = "${serdeValue}")]`);
1218
- parts.push(` ${variantName},`);
1219
- }
1220
- }
1221
- else {
1222
- parts.push(`#[derive(${allDerives.join(", ")})]`);
1223
- if (attrLines.length > 0) {
1224
- parts.push(...attrLines);
1225
- }
1226
- parts.push(`pub enum ${name} {`);
1227
- for (let i = 0; i < members.length; i++) {
1228
- const variantName = toRustVariantName(members[i].name);
1229
- const enumValue = members[i].value ?? 0;
1230
- if (i === 0) {
1231
- parts.push(` #[default]`);
1232
- }
1233
- parts.push(` ${variantName} = ${enumValue},`);
1234
- }
1235
- }
1236
- parts.push("}");
1237
- return parts.join("\n");
1238
- }
1239
- function emitUnion(union, program) {
1240
- const parts = [];
1241
- const name = toPascalCase(union.name ?? "Union");
1242
- const variants = Array.from(union.variants.values());
1243
- if (variants.length === 0) {
1244
- parts.push(`#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]\npub enum ${name} {}\nimpl ${name} {\n pub fn new() -> Self { unreachable!() }\n}`);
1245
- return parts.join("\n");
1246
- }
1247
- parts.push(`#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]\n#[serde(untagged)]\npub enum ${name} {`);
1248
- for (let i = 0; i < variants.length; i++) {
1249
- const variant = variants[i];
1250
- const variantName = `Variant${i + 1}`;
1251
- const { type: rustType } = getRustTypeForProperty(variant.type, program, new Map());
1252
- parts.push(` ${variantName}(${rustType}),`);
1253
- }
1254
- parts.push("}");
1255
- return parts.join("\n");
1256
- }
1257
- function emitScalar(scalar, program) {
1258
- const format = getFormat(program, scalar);
1259
- const pattern = getPattern(program, scalar);
1260
- const structName = toPascalCase(scalar.name);
1261
- const impls = [];
1262
- if (format && formatToRust[format]) {
1263
- return {
1264
- typeDef: `pub type ${structName} = ${formatToRust[format]};`,
1265
- impls: [],
1266
- };
1267
- }
1268
- if (pattern) {
1269
- const rustType = scalarToRust[scalar.name] ?? "String";
1270
- impls.push(`\nimpl TryFrom<String> for ${structName} {\n type Error = String;\n\n fn try_from(value: String) -> Result<Self, Self::Error> {\n let re = regex::Regex::new(r"${pattern}").unwrap();\n if re.is_match(&value) { Ok(Self(value)) } else { Err(format!("Invalid value: {}", value)) }\n }\n}`);
1271
- return {
1272
- typeDef: `#[derive(Debug, Clone, PartialEq, Eq, Hash, Default, serde::Serialize, serde::Deserialize)]\npub struct ${structName}(pub ${rustType});`,
1273
- impls,
1274
- };
1275
- }
1276
- const rustType = scalarToRust[scalar.name] ?? "serde_json::Value";
1277
- return {
1278
- typeDef: `pub type ${structName} = ${rustType};`,
1279
- impls: [],
1280
- };
1281
- }
1
+ import { emitFile, resolvePath, navigateProgram, } from "@typespec/compiler";
2
+ import { isStdLibType, getAllOperations } from "./parser/index.js";
3
+ import { emitModel, emitEnum, emitUnion, emitScalar, emitStringLiteralUnion, } from "./generator/types_file.js";
4
+ import { generateServerTrait } from "./generator/server_trait.js";
5
+ import { generateResponseEnums } from "./generator/response_enums.js";
6
+ import { generateRouter } from "./generator/router.js";
1282
7
  export async function $onEmit(context, _options) {
1283
8
  const content = [];
1284
9
  const models = [];
@@ -1336,7 +61,7 @@ export async function $onEmit(context, _options) {
1336
61
  parts.push(`#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Serialize, serde::Deserialize)]\n#[allow(clippy::enum_variant_names)]\npub enum ${enumName} {`);
1337
62
  for (let i = 0; i < anonEnum.variants.length; i++) {
1338
63
  const literal = anonEnum.variants[i];
1339
- const variantName = toPascalCase(literal.value);
64
+ const variantName = (literal.value.charAt(0).toUpperCase() + literal.value.slice(1)).replace(/[^a-zA-Z0-9]/g, "");
1340
65
  if (i === 0) {
1341
66
  parts.push(` #[default]`);
1342
67
  }