forked from github/copilot-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate-csharp-session-types.ts
More file actions
615 lines (543 loc) · 20.2 KB
/
generate-csharp-session-types.ts
File metadata and controls
615 lines (543 loc) · 20.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------------------------------------------*/
/**
* Custom C# code generator for session event types with proper polymorphic serialization.
*
* This generator produces:
* - A base SessionEvent class with [JsonPolymorphic] and [JsonDerivedType] attributes
* - Separate event classes (SessionStartEvent, AssistantMessageEvent, etc.) with strongly-typed Data
* - Separate Data classes for each event type with only the relevant properties
*
* This approach provides type-safe access to event data instead of a single Data class with 60+ nullable properties.
*/
import type { JSONSchema7 } from "json-schema";
interface EventVariant {
typeName: string; // e.g., "session.start"
className: string; // e.g., "SessionStartEvent"
dataClassName: string; // e.g., "SessionStartData"
dataSchema: JSONSchema7;
ephemeralConst?: boolean; // if ephemeral has a const value
}
/**
* Convert a type string like "session.start" to PascalCase class name like "SessionStart"
*/
function typeToClassName(typeName: string): string {
return typeName
.split(/[._]/)
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
.join("");
}
/**
* Convert a property name to PascalCase for C#
*/
function toPascalCase(name: string): string {
// Handle snake_case
if (name.includes("_")) {
return name
.split("_")
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
.join("");
}
// Handle camelCase
return name.charAt(0).toUpperCase() + name.slice(1);
}
/**
* Map JSON Schema type to C# type
*/
function schemaTypeToCSharp(
schema: JSONSchema7,
required: boolean,
knownTypes: Map<string, string>,
parentClassName?: string,
propName?: string,
enumOutput?: string[]
): string {
if (schema.anyOf) {
// Handle nullable types (anyOf with null)
const nonNull = schema.anyOf.filter((s) => typeof s === "object" && s.type !== "null");
if (nonNull.length === 1 && typeof nonNull[0] === "object") {
return (
schemaTypeToCSharp(
nonNull[0] as JSONSchema7,
false,
knownTypes,
parentClassName,
propName,
enumOutput
) + "?"
);
}
}
if (schema.enum && parentClassName && propName && enumOutput) {
// Generate C# enum
const enumName = getOrCreateEnum(
parentClassName,
propName,
schema.enum as string[],
enumOutput
);
return required ? enumName : `${enumName}?`;
}
if (schema.$ref) {
const refName = schema.$ref.split("/").pop()!;
return knownTypes.get(refName) || refName;
}
const type = schema.type;
const format = schema.format;
if (type === "string") {
if (format === "uuid") return required ? "Guid" : "Guid?";
if (format === "date-time") return required ? "DateTimeOffset" : "DateTimeOffset?";
return required ? "string" : "string?";
}
if (type === "number" || type === "integer") {
return required ? "double" : "double?";
}
if (type === "boolean") {
return required ? "bool" : "bool?";
}
if (type === "array") {
const items = schema.items as JSONSchema7 | undefined;
const itemType = items ? schemaTypeToCSharp(items, true, knownTypes) : "object";
return required ? `${itemType}[]` : `${itemType}[]?`;
}
if (type === "object") {
if (schema.additionalProperties) {
const valueSchema = schema.additionalProperties;
if (typeof valueSchema === "object") {
const valueType = schemaTypeToCSharp(valueSchema as JSONSchema7, true, knownTypes);
return required ? `Dictionary<string, ${valueType}>` : `Dictionary<string, ${valueType}>?`;
}
return required ? "Dictionary<string, object>" : "Dictionary<string, object>?";
}
return required ? "object" : "object?";
}
return required ? "object" : "object?";
}
/**
* Event types to exclude from generation (internal/legacy types)
*/
const EXCLUDED_EVENT_TYPES = new Set(["session.import_legacy"]);
/**
* Track enums that have been generated to avoid duplicates
*/
const generatedEnums = new Map<string, { enumName: string; values: string[] }>();
/**
* Generate a C# enum name from the context
*/
function generateEnumName(parentClassName: string, propName: string): string {
return `${parentClassName}${propName}`;
}
/**
* Get or create an enum for a given set of values.
* Returns the enum name and whether it's newly generated.
*/
function getOrCreateEnum(
parentClassName: string,
propName: string,
values: string[],
enumOutput: string[]
): string {
// Create a key based on the sorted values to detect duplicates
const valuesKey = [...values].sort().join("|");
// Check if we already have an enum with these exact values
for (const [, existing] of generatedEnums) {
const existingKey = [...existing.values].sort().join("|");
if (existingKey === valuesKey) {
return existing.enumName;
}
}
const enumName = generateEnumName(parentClassName, propName);
generatedEnums.set(enumName, { enumName, values });
// Generate the enum code with JsonConverter and JsonStringEnumMemberName attributes
const lines: string[] = [];
lines.push(`[JsonConverter(typeof(JsonStringEnumConverter<${enumName}>))]`);
lines.push(`public enum ${enumName}`);
lines.push(`{`);
for (const value of values) {
const memberName = toPascalCaseEnumMember(value);
lines.push(` [JsonStringEnumMemberName("${value}")]`);
lines.push(` ${memberName},`);
}
lines.push(`}`);
lines.push("");
enumOutput.push(lines.join("\n"));
return enumName;
}
/**
* Convert a string value to a valid C# enum member name
*/
function toPascalCaseEnumMember(value: string): string {
// Handle special characters and convert to PascalCase
return value
.split(/[-_.]/)
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
.join("");
}
/**
* Extract event variants from the schema's anyOf
*/
function extractEventVariants(schema: JSONSchema7): EventVariant[] {
const sessionEvent = schema.definitions?.SessionEvent as JSONSchema7;
if (!sessionEvent?.anyOf) {
throw new Error("Schema must have SessionEvent definition with anyOf");
}
return sessionEvent.anyOf
.map((variant) => {
if (typeof variant !== "object" || !variant.properties) {
throw new Error("Invalid variant in anyOf");
}
const typeSchema = variant.properties.type as JSONSchema7;
const typeName = typeSchema?.const as string;
if (!typeName) {
throw new Error("Variant must have type.const");
}
const baseName = typeToClassName(typeName);
const ephemeralSchema = variant.properties.ephemeral as JSONSchema7 | undefined;
return {
typeName,
className: `${baseName}Event`,
dataClassName: `${baseName}Data`,
dataSchema: variant.properties.data as JSONSchema7,
ephemeralConst: ephemeralSchema?.const as boolean | undefined,
};
})
.filter((variant) => !EXCLUDED_EVENT_TYPES.has(variant.typeName));
}
/**
* Generate C# code for a Data class
*/
function generateDataClass(
variant: EventVariant,
knownTypes: Map<string, string>,
nestedClasses: Map<string, string>,
enumOutput: string[]
): string {
const lines: string[] = [];
const dataSchema = variant.dataSchema;
if (!dataSchema?.properties) {
lines.push(`public partial class ${variant.dataClassName} { }`);
return lines.join("\n");
}
const required = new Set(dataSchema.required || []);
lines.push(`public partial class ${variant.dataClassName}`);
lines.push(`{`);
for (const [propName, propSchema] of Object.entries(dataSchema.properties)) {
if (typeof propSchema !== "object") continue;
const isRequired = required.has(propName);
const csharpName = toPascalCase(propName);
const csharpType = resolvePropertyType(
propSchema as JSONSchema7,
variant.dataClassName,
csharpName,
isRequired,
knownTypes,
nestedClasses,
enumOutput
);
const isNullableType = csharpType.endsWith("?");
if (!isRequired) {
lines.push(
` [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]`
);
}
lines.push(` [JsonPropertyName("${propName}")]`);
const requiredModifier = isRequired && !isNullableType ? "required " : "";
lines.push(` public ${requiredModifier}${csharpType} ${csharpName} { get; set; }`);
lines.push("");
}
// Remove trailing empty line
if (lines[lines.length - 1] === "") {
lines.pop();
}
lines.push(`}`);
return lines.join("\n");
}
/**
* Generate a nested class for complex object properties.
* This function recursively handles nested objects, arrays of objects, and anyOf unions.
*/
function generateNestedClass(
className: string,
schema: JSONSchema7,
knownTypes: Map<string, string>,
nestedClasses: Map<string, string>,
enumOutput: string[]
): string {
const lines: string[] = [];
const required = new Set(schema.required || []);
lines.push(`public partial class ${className}`);
lines.push(`{`);
if (schema.properties) {
for (const [propName, propSchema] of Object.entries(schema.properties)) {
if (typeof propSchema !== "object") continue;
const isRequired = required.has(propName);
const csharpName = toPascalCase(propName);
let csharpType = resolvePropertyType(
propSchema as JSONSchema7,
className,
csharpName,
isRequired,
knownTypes,
nestedClasses,
enumOutput
);
if (!isRequired) {
lines.push(
` [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]`
);
}
lines.push(` [JsonPropertyName("${propName}")]`);
const isNullableType = csharpType.endsWith("?");
const requiredModifier = isRequired && !isNullableType ? "required " : "";
lines.push(` public ${requiredModifier}${csharpType} ${csharpName} { get; set; }`);
lines.push("");
}
}
// Remove trailing empty line
if (lines[lines.length - 1] === "") {
lines.pop();
}
lines.push(`}`);
return lines.join("\n");
}
/**
* Resolve the C# type for a property, generating nested classes as needed.
* Handles objects and arrays of objects.
*/
function resolvePropertyType(
propSchema: JSONSchema7,
parentClassName: string,
propName: string,
isRequired: boolean,
knownTypes: Map<string, string>,
nestedClasses: Map<string, string>,
enumOutput: string[]
): string {
// Handle anyOf - simplify to nullable of the non-null type or object
if (propSchema.anyOf) {
const hasNull = propSchema.anyOf.some(
(s) => typeof s === "object" && (s as JSONSchema7).type === "null"
);
const nonNullTypes = propSchema.anyOf.filter(
(s) => typeof s === "object" && (s as JSONSchema7).type !== "null"
);
if (nonNullTypes.length === 1) {
// Simple nullable - recurse with the inner type, marking as not required if null is an option
return resolvePropertyType(
nonNullTypes[0] as JSONSchema7,
parentClassName,
propName,
isRequired && !hasNull,
knownTypes,
nestedClasses,
enumOutput
);
}
// Complex union - use object, nullable if null is in the union or property is not required
return (hasNull || !isRequired) ? "object?" : "object";
}
// Handle enum types
if (propSchema.enum && Array.isArray(propSchema.enum)) {
const enumName = getOrCreateEnum(
parentClassName,
propName,
propSchema.enum as string[],
enumOutput
);
return isRequired ? enumName : `${enumName}?`;
}
// Handle nested object types
if (propSchema.type === "object" && propSchema.properties) {
const nestedClassName = `${parentClassName}${propName}`;
const nestedCode = generateNestedClass(
nestedClassName,
propSchema,
knownTypes,
nestedClasses,
enumOutput
);
nestedClasses.set(nestedClassName, nestedCode);
return isRequired ? nestedClassName : `${nestedClassName}?`;
}
// Handle array of objects
if (propSchema.type === "array" && propSchema.items) {
const items = propSchema.items as JSONSchema7;
// Array of objects with properties
if (items.type === "object" && items.properties) {
const itemClassName = `${parentClassName}${propName}Item`;
const nestedCode = generateNestedClass(
itemClassName,
items,
knownTypes,
nestedClasses,
enumOutput
);
nestedClasses.set(itemClassName, nestedCode);
return isRequired ? `${itemClassName}[]` : `${itemClassName}[]?`;
}
// Array of enums
if (items.enum && Array.isArray(items.enum)) {
const enumName = getOrCreateEnum(
parentClassName,
`${propName}Item`,
items.enum as string[],
enumOutput
);
return isRequired ? `${enumName}[]` : `${enumName}[]?`;
}
// Simple array type
const itemType = schemaTypeToCSharp(
items,
true,
knownTypes,
parentClassName,
propName,
enumOutput
);
return isRequired ? `${itemType}[]` : `${itemType}[]?`;
}
// Default: use basic type mapping
return schemaTypeToCSharp(
propSchema,
isRequired,
knownTypes,
parentClassName,
propName,
enumOutput
);
}
/**
* Generate the complete C# file
*/
export function generateCSharpSessionTypes(schema: JSONSchema7, generatedAt: string): string {
// Clear the generated enums map from any previous run
generatedEnums.clear();
const variants = extractEventVariants(schema);
const knownTypes = new Map<string, string>();
const nestedClasses = new Map<string, string>();
const enumOutput: string[] = [];
const lines: string[] = [];
// File header
lines.push(`/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------------------------------------------*/
// AUTO-GENERATED FILE - DO NOT EDIT
//
// Generated from: @github/copilot/session-events.schema.json
// Generated by: scripts/generate-session-types.ts
// Generated at: ${generatedAt}
//
// To update these types:
// 1. Update the schema in copilot-agent-runtime
// 2. Run: npm run generate:session-types
using System.Text.Json;
using System.Text.Json.Serialization;
namespace GitHub.Copilot.SDK;
`);
// Generate base class with JsonPolymorphic attributes
lines.push(`/// <summary>`);
lines.push(
`/// Base class for all session events with polymorphic JSON serialization.`
);
lines.push(`/// </summary>`);
lines.push(`[JsonPolymorphic(`);
lines.push(` TypeDiscriminatorPropertyName = "type",`);
lines.push(
` UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FailSerialization)]`
);
// Generate JsonDerivedType attributes for each variant (alphabetized)
for (const variant of [...variants].sort((a, b) => a.typeName.localeCompare(b.typeName))) {
lines.push(
`[JsonDerivedType(typeof(${variant.className}), "${variant.typeName}")]`
);
}
lines.push(`public abstract partial class SessionEvent`);
lines.push(`{`);
lines.push(` [JsonPropertyName("id")]`);
lines.push(` public Guid Id { get; set; }`);
lines.push("");
lines.push(` [JsonPropertyName("timestamp")]`);
lines.push(` public DateTimeOffset Timestamp { get; set; }`);
lines.push("");
lines.push(` [JsonPropertyName("parentId")]`);
lines.push(` public Guid? ParentId { get; set; }`);
lines.push("");
lines.push(` [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]`);
lines.push(` [JsonPropertyName("ephemeral")]`);
lines.push(` public bool? Ephemeral { get; set; }`);
lines.push("");
lines.push(` /// <summary>`);
lines.push(` /// The event type discriminator.`);
lines.push(` /// </summary>`);
lines.push(` [JsonIgnore]`);
lines.push(` public abstract string Type { get; }`);
lines.push("");
lines.push(` public static SessionEvent FromJson(string json) =>`);
lines.push(
` JsonSerializer.Deserialize(json, SessionEventsJsonContext.Default.SessionEvent)!;`
);
lines.push("");
lines.push(` public string ToJson() =>`);
lines.push(
` JsonSerializer.Serialize(this, SessionEventsJsonContext.Default.SessionEvent);`
);
lines.push(`}`);
lines.push("");
// Generate each event class
for (const variant of variants) {
lines.push(`/// <summary>`);
lines.push(`/// Event: ${variant.typeName}`);
lines.push(`/// </summary>`);
lines.push(`public partial class ${variant.className} : SessionEvent`);
lines.push(`{`);
lines.push(` [JsonIgnore]`);
lines.push(` public override string Type => "${variant.typeName}";`);
lines.push("");
lines.push(` [JsonPropertyName("data")]`);
lines.push(` public required ${variant.dataClassName} Data { get; set; }`);
lines.push(`}`);
lines.push("");
}
// Generate data classes
for (const variant of variants) {
const dataClass = generateDataClass(variant, knownTypes, nestedClasses, enumOutput);
lines.push(dataClass);
lines.push("");
}
// Generate nested classes
for (const [, nestedCode] of nestedClasses) {
lines.push(nestedCode);
lines.push("");
}
// Generate enums
for (const enumCode of enumOutput) {
lines.push(enumCode);
}
// Collect all serializable types (sorted alphabetically)
const serializableTypes: string[] = [];
// Add SessionEvent base class
serializableTypes.push("SessionEvent");
// Add all event classes and their data classes
for (const variant of variants) {
serializableTypes.push(variant.className);
serializableTypes.push(variant.dataClassName);
}
// Add all nested classes
for (const [className] of nestedClasses) {
serializableTypes.push(className);
}
// Sort alphabetically
serializableTypes.sort((a, b) => a.localeCompare(b));
// Generate JsonSerializerContext with JsonSerializable attributes
lines.push(`[JsonSourceGenerationOptions(`);
lines.push(` JsonSerializerDefaults.Web,`);
lines.push(` AllowOutOfOrderMetadataProperties = true,`);
lines.push(` NumberHandling = JsonNumberHandling.AllowReadingFromString,`);
lines.push(` DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]`);
for (const typeName of serializableTypes) {
lines.push(`[JsonSerializable(typeof(${typeName}))]`);
}
lines.push(`internal partial class SessionEventsJsonContext : JsonSerializerContext;`);
return lines.join("\n");
}