typespec-rust-emitter 0.1.0 → 0.2.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.
@@ -1,4 +1,4 @@
1
- import { emitFile, resolvePath, navigateProgram, getDoc, isArrayModelType, isRecordModelType, getFormat, getPattern, isErrorModel, getNamespaceFullName, } from "@typespec/compiler";
1
+ import { emitFile, resolvePath, navigateProgram, getDoc, isArrayModelType, isRecordModelType, getFormat, getPattern, isErrorModel, getNamespaceFullName, getTags, } from "@typespec/compiler";
2
2
  const rustDeriveKey = Symbol("rustDerive");
3
3
  export function $rustDerive(context, target, derive) {
4
4
  if (target.kind !== "Model") {
@@ -29,6 +29,557 @@ export function $rustDerives(context, target, ...derives) {
29
29
  $rustDerive(context, target, derive);
30
30
  }
31
31
  }
32
+ function getDecoratorName(decorator) {
33
+ if (!decorator)
34
+ return "";
35
+ if (typeof decorator !== "object")
36
+ return "";
37
+ if (decorator.node?.target?.sv) {
38
+ return decorator.node.target.sv;
39
+ }
40
+ if (decorator.node?.target?.kind === "Identifier" &&
41
+ decorator.node?.target?.sv) {
42
+ return decorator.node.target.sv;
43
+ }
44
+ return "";
45
+ }
46
+ function getDecoratorArgValue(decorator, index = 0) {
47
+ if (!decorator)
48
+ return "";
49
+ const args = decorator.args || decorator.arguments;
50
+ if (!args)
51
+ return "";
52
+ const arg = args[index];
53
+ if (arg?.jsValue !== undefined)
54
+ return String(arg.jsValue);
55
+ if (arg?.value !== undefined)
56
+ return String(arg.value);
57
+ return "";
58
+ }
59
+ function getHttpMethod(_program, operation) {
60
+ const decorators = operation.decorators;
61
+ if (!decorators)
62
+ return undefined;
63
+ for (const key of Object.keys(decorators)) {
64
+ const decorator = decorators[key];
65
+ const name = getDecoratorName(decorator);
66
+ if (name === "get")
67
+ return "GET";
68
+ if (name === "post")
69
+ return "POST";
70
+ if (name === "put")
71
+ return "PUT";
72
+ if (name === "patch")
73
+ return "PATCH";
74
+ if (name === "delete")
75
+ return "DELETE";
76
+ if (name === "head")
77
+ return "HEAD";
78
+ }
79
+ return undefined;
80
+ }
81
+ function getRoute(_program, target) {
82
+ const decorators = target.decorators;
83
+ if (!decorators)
84
+ return "";
85
+ for (const key of Object.keys(decorators)) {
86
+ const decorator = decorators[key];
87
+ const name = getDecoratorName(decorator);
88
+ if (name === "route") {
89
+ return getDecoratorArgValue(decorator, 0);
90
+ }
91
+ }
92
+ return "";
93
+ }
94
+ function hasAuthDecorator(operation) {
95
+ const decorators = operation.decorators;
96
+ if (!decorators)
97
+ return false;
98
+ for (const key of Object.keys(decorators)) {
99
+ const decorator = decorators[key];
100
+ const name = getDecoratorName(decorator);
101
+ if (name === "useAuth") {
102
+ return true;
103
+ }
104
+ }
105
+ return false;
106
+ }
107
+ function getOperationParameters(program, operation, anonymousEnums) {
108
+ const params = [];
109
+ const model = operation.parameters;
110
+ for (const [propName, prop] of model.properties) {
111
+ const decorators = prop.decorators;
112
+ let location = "query";
113
+ let rustName = toRustIdent(propName);
114
+ if (decorators) {
115
+ if (decorators["$path"]) {
116
+ location = "path";
117
+ }
118
+ else if (decorators["$query"]) {
119
+ location = "query";
120
+ }
121
+ else if (decorators["$header"]) {
122
+ location = "header";
123
+ const headerDec = decorators["$header"];
124
+ if (headerDec?.value) {
125
+ rustName = headerDec.value;
126
+ }
127
+ }
128
+ else if (decorators["$cookie"]) {
129
+ location = "cookie";
130
+ }
131
+ }
132
+ const { type: rustType } = getRustTypeForProperty(prop.type, program, anonymousEnums);
133
+ params.push({
134
+ name: propName,
135
+ rustName,
136
+ rustType,
137
+ location,
138
+ required: !prop.optional,
139
+ optional: prop.optional,
140
+ });
141
+ }
142
+ return params;
143
+ }
144
+ function getOperationBody(operation) {
145
+ for (const [_propName, prop] of operation.parameters.properties) {
146
+ const decorators = prop.decorators;
147
+ if (decorators?.["$body"] || decorators?.["$bodyRoot"]) {
148
+ return prop;
149
+ }
150
+ }
151
+ return undefined;
152
+ }
153
+ function getOperationResponses(program, operation, anonymousEnums) {
154
+ const responses = [];
155
+ const returnType = operation.returnType;
156
+ if (returnType.kind === "Union") {
157
+ const union = returnType;
158
+ for (const variant of union.variants.values()) {
159
+ const statusCode = getStatusCode(variant);
160
+ const bodyInfo = getBodyFromResponse(variant, program, anonymousEnums);
161
+ responses.push({
162
+ statusCode,
163
+ bodyType: bodyInfo.type,
164
+ bodyDescription: bodyInfo.description,
165
+ });
166
+ }
167
+ }
168
+ else if (returnType.kind === "Model") {
169
+ const model = returnType;
170
+ for (const [propName, prop] of model.properties) {
171
+ if (propName === "body") {
172
+ const { type: rustType } = getRustTypeForProperty(prop.type, program, anonymousEnums);
173
+ responses.push({
174
+ statusCode: 200,
175
+ bodyType: rustType,
176
+ bodyDescription: getDoc(program, prop),
177
+ });
178
+ }
179
+ }
180
+ }
181
+ return responses;
182
+ }
183
+ function getStatusCode(variant) {
184
+ if (variant.type.kind === "Model") {
185
+ const model = variant.type;
186
+ for (const [propName, prop] of model.properties) {
187
+ if (propName === "statusCode") {
188
+ const typeAny = prop.type;
189
+ if (typeAny.value !== undefined) {
190
+ return typeAny.value;
191
+ }
192
+ }
193
+ }
194
+ }
195
+ return 200;
196
+ }
197
+ function getBodyFromResponse(variant, program, anonymousEnums) {
198
+ if (variant.type.kind === "Model") {
199
+ const model = variant.type;
200
+ for (const [propName, prop] of model.properties) {
201
+ if (propName === "body") {
202
+ const { type: rustType } = getRustTypeForProperty(prop.type, program, anonymousEnums);
203
+ return { type: rustType, description: getDoc(program, prop) };
204
+ }
205
+ }
206
+ }
207
+ return { type: undefined, description: undefined };
208
+ }
209
+ function getAllOperations(program) {
210
+ const seenNamespaces = new Set();
211
+ const namespaceOps = new Map();
212
+ navigateProgram(program, {
213
+ namespace(ns) {
214
+ const route = getRoute(program, ns);
215
+ if (!route)
216
+ return;
217
+ if (!seenNamespaces.has(ns.name)) {
218
+ seenNamespaces.add(ns.name);
219
+ namespaceOps.set(ns.name, { ns, ops: [] });
220
+ }
221
+ },
222
+ operation(op) {
223
+ const method = getHttpMethod(program, op);
224
+ if (!method)
225
+ return;
226
+ const ns = op.namespace;
227
+ if (!ns)
228
+ return;
229
+ if (!seenNamespaces.has(ns.name)) {
230
+ seenNamespaces.add(ns.name);
231
+ namespaceOps.set(ns.name, { ns, ops: [] });
232
+ }
233
+ const entry = namespaceOps.get(ns.name);
234
+ if (entry) {
235
+ entry.ops.push(op);
236
+ }
237
+ },
238
+ });
239
+ const result = [];
240
+ for (const [, entry] of namespaceOps) {
241
+ if (entry.ops.length > 0) {
242
+ result.push({ namespace: entry.ns, operations: entry.ops });
243
+ }
244
+ }
245
+ return result;
246
+ }
247
+ function buildFullPath(namespaceRoute, operationRoute) {
248
+ let fullPath = namespaceRoute + operationRoute;
249
+ fullPath = fullPath.replace(/\/+/g, "/");
250
+ if (fullPath.length > 1 && fullPath.endsWith("/")) {
251
+ fullPath = fullPath.slice(0, -1);
252
+ }
253
+ return fullPath;
254
+ }
255
+ function emitOperationInfo(program, op, nsRoute, anonymousEnums) {
256
+ const method = getHttpMethod(program, op);
257
+ if (!method)
258
+ return undefined;
259
+ const opRoute = getRoute(program, op);
260
+ const fullPath = buildFullPath(nsRoute, opRoute);
261
+ const tags = getTags(program, op) ?? [];
262
+ const params = getOperationParameters(program, op, anonymousEnums);
263
+ const body = getOperationBody(op);
264
+ const responses = getOperationResponses(program, op, anonymousEnums);
265
+ const doc = getDoc(program, op);
266
+ const opName = op.name.replace(/[^a-zA-Z0-9_]/g, "_");
267
+ return {
268
+ name: opName,
269
+ method,
270
+ path: fullPath,
271
+ tags,
272
+ parameters: params,
273
+ body: body,
274
+ responses,
275
+ doc,
276
+ };
277
+ }
278
+ function getStatusVariantName(statusCode) {
279
+ const statusNames = {
280
+ 200: "Ok",
281
+ 201: "Created",
282
+ 202: "Accepted",
283
+ 204: "NoContent",
284
+ 400: "BadRequest",
285
+ 401: "Unauthorized",
286
+ 403: "Forbidden",
287
+ 404: "NotFound",
288
+ 409: "Conflict",
289
+ 500: "InternalServerError",
290
+ };
291
+ return statusNames[statusCode] || `Status${statusCode}`;
292
+ }
293
+ function getHttpStatusCode(statusCode) {
294
+ const statusCodes = {
295
+ 200: "StatusCode::OK",
296
+ 201: "StatusCode::CREATED",
297
+ 202: "StatusCode::ACCEPTED",
298
+ 204: "StatusCode::NO_CONTENT",
299
+ 400: "StatusCode::BAD_REQUEST",
300
+ 401: "StatusCode::UNAUTHORIZED",
301
+ 403: "StatusCode::FORBIDDEN",
302
+ 404: "StatusCode::NOT_FOUND",
303
+ 409: "StatusCode::CONFLICT",
304
+ 500: "StatusCode::INTERNAL_SERVER_ERROR",
305
+ };
306
+ return statusCodes[statusCode] || `StatusCode::from_u16(${statusCode})`;
307
+ }
308
+ function generateServerTrait(program, namespaceGroups, anonymousEnums) {
309
+ const parts = [];
310
+ parts.push(`use super::types::*;
311
+ use async_trait::async_trait;
312
+ use axum::{http::StatusCode, Json};
313
+ use eyre::Result;
314
+
315
+ #[async_trait]
316
+ pub trait Server: Send + Sync {
317
+ type Claims: Send + Sync + 'static;
318
+
319
+ `);
320
+ for (const group of namespaceGroups) {
321
+ const nsName = toPascalCase(group.namespace.name.replace(/[^a-zA-Z0-9_]/g, "_"));
322
+ for (const op of group.operations) {
323
+ const opInfo = emitOperationInfo(program, op, "", anonymousEnums);
324
+ if (!opInfo)
325
+ continue;
326
+ if (opInfo.doc) {
327
+ parts.push(` ${formatDoc(opInfo.doc)}`);
328
+ }
329
+ const requestName = `${nsName}${toPascalCase(opInfo.name)}Request`;
330
+ const responseName = `${nsName}${toPascalCase(opInfo.name)}Response`;
331
+ const fnName = toRustIdent(`${nsName}_${opInfo.name}`);
332
+ const isProtected = hasAuthDecorator(op);
333
+ if (isProtected) {
334
+ parts.push(` async fn ${fnName}(&self, claims: Self::Claims, request: ${requestName}) -> Result<${responseName}>;`);
335
+ }
336
+ else {
337
+ parts.push(` async fn ${fnName}(&self, request: ${requestName}) -> Result<${responseName}>;`);
338
+ }
339
+ }
340
+ }
341
+ parts.push("}");
342
+ return parts.join("\n");
343
+ }
344
+ function generateRequestStructs(program, namespaceGroups, anonymousEnums) {
345
+ const parts = [];
346
+ for (const group of namespaceGroups) {
347
+ const nsName = toPascalCase(group.namespace.name.replace(/[^a-zA-Z0-9_]/g, "_"));
348
+ for (const op of group.operations) {
349
+ const opInfo = emitOperationInfo(program, op, "", anonymousEnums);
350
+ if (!opInfo)
351
+ continue;
352
+ const params = opInfo.parameters;
353
+ const requestName = `${nsName}${toPascalCase(opInfo.name)}Request`;
354
+ const fields = [];
355
+ for (const param of params) {
356
+ const rustType = param.optional
357
+ ? `Option<${param.rustType}>`
358
+ : param.rustType;
359
+ fields.push(` #[serde(rename = "${param.name}", flatten)]`);
360
+ fields.push(` pub ${param.rustName}: ${rustType},`);
361
+ }
362
+ if (opInfo.body) {
363
+ const bodyType = getRustTypeForProperty(opInfo.body.type, program, anonymousEnums);
364
+ fields.push(` #[serde(rename = "body")]`);
365
+ fields.push(` pub body: ${bodyType.type},`);
366
+ }
367
+ parts.push(`#[derive(Debug, Clone, serde::Deserialize)]
368
+ pub struct ${requestName} {
369
+ ${fields.join("\n")}
370
+ }
371
+ `);
372
+ }
373
+ }
374
+ return parts.join("\n");
375
+ }
376
+ function generateResponseEnums(program, namespaceGroups, anonymousEnums) {
377
+ const parts = [];
378
+ for (const group of namespaceGroups) {
379
+ const nsName = toPascalCase(group.namespace.name.replace(/[^a-zA-Z0-9_]/g, "_"));
380
+ for (const op of group.operations) {
381
+ const opInfo = emitOperationInfo(program, op, "", anonymousEnums);
382
+ if (!opInfo)
383
+ continue;
384
+ if (opInfo.responses.length === 0)
385
+ continue;
386
+ const responseName = `${nsName}${toPascalCase(opInfo.name)}Response`;
387
+ const variants = [];
388
+ for (const resp of opInfo.responses) {
389
+ const variantName = getStatusVariantName(resp.statusCode);
390
+ if (!resp.bodyType) {
391
+ variants.push(` ${variantName},`);
392
+ }
393
+ else {
394
+ variants.push(` ${variantName}(Json<${resp.bodyType}>),`);
395
+ }
396
+ }
397
+ parts.push(`pub enum ${responseName} {
398
+ ${variants.join("\n")}
399
+ }
400
+ `);
401
+ parts.push(`impl IntoResponse for ${responseName} {
402
+ fn into_response(self) -> axum::response::Response {
403
+ match self {
404
+ `);
405
+ for (const resp of opInfo.responses) {
406
+ const variantName = getStatusVariantName(resp.statusCode);
407
+ const statusCodeStr = getHttpStatusCode(resp.statusCode);
408
+ if (!resp.bodyType) {
409
+ parts.push(` ${responseName}::${variantName} => ${statusCodeStr}.into_response(),`);
410
+ }
411
+ else {
412
+ parts.push(` ${responseName}::${variantName}(body) => (${statusCodeStr}, body).into_response(),`);
413
+ }
414
+ }
415
+ parts.push(` }
416
+ }
417
+ }
418
+ `);
419
+ }
420
+ }
421
+ return parts.join("\n");
422
+ }
423
+ function generateRouter(program, namespaceGroups, anonymousEnums) {
424
+ const handlers = [];
425
+ const publicRoutes = [];
426
+ const protectedRoutes = [];
427
+ const usedMethods = new Set();
428
+ for (const group of namespaceGroups) {
429
+ const nsRoute = getRoute(program, group.namespace);
430
+ if (!nsRoute)
431
+ continue;
432
+ const nsName = toPascalCase(group.namespace.name.replace(/[^a-zA-Z0-9_]/g, "_"));
433
+ for (const op of group.operations) {
434
+ const opInfo = emitOperationInfo(program, op, nsRoute, anonymousEnums);
435
+ if (!opInfo)
436
+ continue;
437
+ const method = opInfo.method.toLowerCase();
438
+ usedMethods.add(method);
439
+ const handlerFnName = toRustIdent(`${nsName}_${opInfo.name}`);
440
+ const traitFnName = handlerFnName;
441
+ const requestName = `${nsName}${toPascalCase(opInfo.name)}Request`;
442
+ const isProtected = hasAuthDecorator(op);
443
+ const pathParams = opInfo.parameters.filter((p) => p.location === "path");
444
+ const queryParams = opInfo.parameters.filter((p) => p.location === "query");
445
+ const hasPathParams = pathParams.length > 0;
446
+ const hasQueryParams = queryParams.length > 0;
447
+ const hasBody = !!opInfo.body;
448
+ // Build extractor lines and request construction expression
449
+ const extractorLines = [];
450
+ let requestExpr = "";
451
+ if (hasPathParams) {
452
+ const pathTypes = pathParams.map((p) => p.rustType).join(", ");
453
+ const pathFields = pathParams.map((p) => p.rustName).join(", ");
454
+ if (pathParams.length === 1) {
455
+ extractorLines.push(` axum::extract::Path(${pathFields}): axum::extract::Path<${pathTypes}>,`);
456
+ }
457
+ else {
458
+ extractorLines.push(` axum::extract::Path((${pathFields})): axum::extract::Path<(${pathTypes})>,`);
459
+ }
460
+ }
461
+ if (hasQueryParams) {
462
+ extractorLines.push(` axum::extract::Query(query): axum::extract::Query<${requestName}>,`);
463
+ }
464
+ else if (hasBody) {
465
+ extractorLines.push(` axum::Json(body): axum::Json<${requestName}Body>,`);
466
+ }
467
+ if (isProtected) {
468
+ extractorLines.push(` axum::Extension(claims): axum::Extension<S::Claims>,`);
469
+ }
470
+ // Build request struct expression
471
+ if (hasOnlyPathParams(hasPathParams, hasQueryParams, hasBody)) {
472
+ const pathAssignments = pathParams
473
+ .map((p) => `${p.rustName},`)
474
+ .join(" ");
475
+ requestExpr = `${requestName} { ${pathAssignments} }`;
476
+ }
477
+ else if (hasQueryParams) {
478
+ if (hasPathParams) {
479
+ const pathAssignments = pathParams
480
+ .map((p) => `${p.rustName},`)
481
+ .join(" ");
482
+ requestExpr = `${requestName} { ${pathAssignments} ..query }`;
483
+ }
484
+ else {
485
+ requestExpr = "query";
486
+ }
487
+ }
488
+ else if (hasBody) {
489
+ if (hasPathParams) {
490
+ const pathAssignments = pathParams
491
+ .map((p) => `${p.rustName},`)
492
+ .join(" ");
493
+ requestExpr = `${requestName} { ${pathAssignments} body }`;
494
+ }
495
+ else {
496
+ requestExpr = `${requestName} { body }`;
497
+ }
498
+ }
499
+ else {
500
+ requestExpr = `${requestName} {}`;
501
+ }
502
+ // Server method call
503
+ const serverCall = isProtected
504
+ ? `service.${traitFnName}(claims, ${requestExpr}).await`
505
+ : `service.${traitFnName}(${requestExpr}).await`;
506
+ // All handlers use <S> generics, Claims is now an associated type
507
+ let handlerCode = `pub async fn ${handlerFnName}_handler<S>(
508
+ axum::extract::State(service): axum::extract::State<S>,
509
+ ${extractorLines.join("\n")}
510
+ ) -> impl axum::response::IntoResponse
511
+ where
512
+ S: Server + Clone + Send + Sync + 'static,
513
+ S::Claims: Send + Sync + Clone + 'static,
514
+ {
515
+ let result = ${serverCall};
516
+ match result {
517
+ Ok(response) => response.into_response(),
518
+ Err(e) => (
519
+ axum::http::StatusCode::INTERNAL_SERVER_ERROR,
520
+ format!("Internal error: {e}"),
521
+ )
522
+ .into_response(),
523
+ }
524
+ }`;
525
+ handlers.push(handlerCode);
526
+ let routePath = `"${opInfo.path}"`;
527
+ let routeStmt = "";
528
+ if (isProtected) {
529
+ routeStmt = `.route(${routePath}, ${method}(${handlerFnName}_handler::<S>))`;
530
+ protectedRoutes.push(routeStmt);
531
+ }
532
+ else {
533
+ routeStmt = `.route(${routePath}, ${method}(${handlerFnName}_handler::<S>))`;
534
+ publicRoutes.push(routeStmt);
535
+ }
536
+ }
537
+ }
538
+ const methodImports = Array.from(usedMethods).sort().join(", ");
539
+ const routerBody = buildRouterBody(publicRoutes, protectedRoutes);
540
+ const parts = [];
541
+ parts.push(`use axum::response::IntoResponse;
542
+ use axum::routing::{${methodImports}};
543
+ use axum::Router;
544
+
545
+ `);
546
+ parts.push(handlers.join("\n\n"));
547
+ parts.push(`
548
+ pub fn create_router<S, M>(service: S, middleware: M) -> Router
549
+ where
550
+ S: Server + Clone + Send + Sync + 'static,
551
+ S::Claims: Send + Sync + Clone + 'static,
552
+ M: FnOnce(Router<S>) -> Router<S> + Clone + Send + Sync + 'static,
553
+ {
554
+ ${routerBody}
555
+ }`);
556
+ return parts.join("\n");
557
+ }
558
+ function hasOnlyPathParams(hasPath, hasQuery, hasBody) {
559
+ return hasPath && !hasQuery && !hasBody;
560
+ }
561
+ function buildRouterBody(publicRoutes, protectedRoutes) {
562
+ const lines = [];
563
+ lines.push(" let mut router = Router::new();");
564
+ if (publicRoutes.length > 0) {
565
+ lines.push(" let public = Router::new()");
566
+ for (const r of publicRoutes) {
567
+ lines.push(` ${r.trim()}`);
568
+ }
569
+ lines.push(" ;");
570
+ lines.push(" router = router.merge(public);");
571
+ }
572
+ if (protectedRoutes.length > 0) {
573
+ lines.push(" let protected = Router::new()");
574
+ for (const r of protectedRoutes) {
575
+ lines.push(` ${r.trim()}`);
576
+ }
577
+ lines.push(" ;");
578
+ lines.push(" router = router.merge(middleware(protected));");
579
+ }
580
+ lines.push(" router.with_state(service)");
581
+ return lines.join("\n");
582
+ }
32
583
  const scalarToRust = {
33
584
  string: "String",
34
585
  int8: "i8",
@@ -284,9 +835,8 @@ function emitModel(model, program, anonymousEnums) {
284
835
  if (isError && allProps.size > 0) {
285
836
  parts.push('#[error("{code}: {message}")]');
286
837
  }
287
- parts.push(`pub struct ${name}`);
288
838
  if (allProps.size > 0) {
289
- parts.push(" {");
839
+ const fields = [];
290
840
  for (const [propName, prop] of allProps) {
291
841
  const doc = getDoc(program, prop);
292
842
  const { type: rustType } = getRustTypeForProperty(prop.type, program, anonymousEnums);
@@ -294,19 +844,22 @@ function emitModel(model, program, anonymousEnums) {
294
844
  const fieldName = toRustIdent(propName);
295
845
  const serdeRename = propName !== fieldName ? `#[serde(rename = "${propName}")]` : "";
296
846
  if (doc) {
297
- parts.push(`\n ${formatDoc(doc)}`);
847
+ fields.push(` ${formatDoc(doc)}`);
298
848
  }
299
849
  if (serdeRename) {
300
- parts.push(` ${serdeRename}`);
850
+ fields.push(` ${serdeRename}`);
301
851
  }
302
852
  if (optional) {
303
- parts.push(` #[serde(skip_serializing_if = "Option::is_none")]`);
853
+ fields.push(` #[serde(skip_serializing_if = "Option::is_none")]`);
304
854
  }
305
- parts.push(` pub ${fieldName}: ${optional ? `Option<${rustType}>` : rustType},`);
855
+ fields.push(` pub ${fieldName}: ${optional ? `Option<${rustType}>` : rustType},`);
306
856
  }
307
- parts.push("}");
857
+ parts.push(`pub struct ${name} {
858
+ ${fields.join("\n")}
859
+ }`);
308
860
  }
309
861
  else {
862
+ parts.push(`pub struct ${name}`);
310
863
  parts.push("(());");
311
864
  }
312
865
  return parts.join("\n");
@@ -481,10 +1034,27 @@ export async function $onEmit(context, _options) {
481
1034
  }
482
1035
  content.push("");
483
1036
  }
1037
+ const namespaceGroups = getAllOperations(context.program);
484
1038
  const outputContent = content.join("\n");
485
1039
  await emitFile(context.program, {
486
1040
  path: resolvePath(context.emitterOutputDir, "types.rs"),
487
1041
  content: outputContent,
488
1042
  });
1043
+ if (namespaceGroups.length > 0) {
1044
+ const serverTrait = generateServerTrait(context.program, namespaceGroups, anonymousEnums);
1045
+ const requestStructs = generateRequestStructs(context.program, namespaceGroups, anonymousEnums);
1046
+ const responseEnums = generateResponseEnums(context.program, namespaceGroups, anonymousEnums);
1047
+ const router = generateRouter(context.program, namespaceGroups, anonymousEnums);
1048
+ const serverContent = [
1049
+ serverTrait,
1050
+ requestStructs,
1051
+ responseEnums,
1052
+ router,
1053
+ ].join("\n");
1054
+ await emitFile(context.program, {
1055
+ path: resolvePath(context.emitterOutputDir, "server.rs"),
1056
+ content: serverContent,
1057
+ });
1058
+ }
489
1059
  }
490
1060
  //# sourceMappingURL=emitter.js.map