-
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathTsClient.cs
More file actions
2027 lines (1918 loc) · 86.9 KB
/
Copy pathTsClient.cs
File metadata and controls
2027 lines (1918 loc) · 86.9 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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Text;
using System.Text.RegularExpressions;
using static NpgsqlRest.NpgsqlRestOptions;
namespace NpgsqlRest.TsClient;
public partial class TsClient(TsClientOptions options) : IEndpointCreateHandler
{
private IApplicationBuilder _builder = default!;
private NpgsqlRestOptions? _npgsqlRestoptions;
private const string Enabled = "tsclient";
private const string Module = "tsclient_module";
private const string SseEvents = "tsclient_events";
private const string IncludeParseUrl = "tsclient_parse_url";
private const string IncludeParseRequest = "tsclient_parse_request";
private const string IncludeStatusCode = "tsclient_status_code";
private const string ExportUrl = "tsclient_export_url";
private const string UrlOnly = "tsclient_url_only";
public void Setup(IApplicationBuilder builder, NpgsqlRestOptions npgsqlRestoptions)
{
_builder = builder;
_npgsqlRestoptions = npgsqlRestoptions;
}
private int _filesCreated;
public void Cleanup(RoutineEndpoint[] endpoints)
{
if (options.FilePath is null)
{
return;
}
_filesCreated = 0;
var containsModuleParam = endpoints.Any(e => e.CustomParameters?.ContainsKey(Module) is true);
if (!options.BySchema && containsModuleParam)
{
Run(endpoints, options.FilePath);
}
else
{
if (!options.FilePath.Contains("{0}"))
{
Logger?.LogError("TsClient Option FilePath doesn't contain {{0}} formatter and BySchema options is true. Some files may be overwritten! Existing...");
return;
}
HashSet<string> processedModules = [];
if (containsModuleParam)
{
foreach (var group in endpoints.GroupBy(e => e.CustomParameters?.GetValueOrDefault(Module)))
{
if (group.Key is null)
{
continue;
}
if (!processedModules.Contains(group.Key))
{
processedModules.Add(group.Key);
}
var filename = string.Format(options.FilePath, group.Key);
if (options.SkipTypes && filename.EndsWith(".ts"))
{
filename = filename[..^3] + ".js";
}
Run([.. group], filename);
}
}
foreach (var group in endpoints.GroupBy(e => e.Routine.Schema))
{
var filename = string.Format(options.FilePath, ConvertToCamelCase(group.Key));
if (options.SkipTypes && filename.EndsWith(".ts"))
{
filename = filename[..^3] + ".js";
}
RoutineEndpoint[] groupArray = [.. group.Where(g =>
(g.CustomParameters?.ContainsKey(Module) is false) ||
(g.CustomParameters?.GetValueOrDefault(Module) is null) ||
(!processedModules.Contains(g.CustomParameters?.GetValueOrDefault(Module) ?? ""))
)];
if (groupArray.Length == 0)
{
continue;
}
Run([.. groupArray], filename);
}
}
if (_filesCreated > 0)
{
Logger?.LogDebug("TsClient: Created {count} {type} file(s)", _filesCreated, options.SkipTypes ? "JavaScript" : "TypeScript");
}
}
private void Run(RoutineEndpoint[] endpoints, string? fileName)
{
if (fileName is null)
{
return;
}
// Internal-only endpoints have no public HTTP route (404), so a generated client function for one
// would be dead — e.g. a bare-`@mcp` MCP-only routine. Exclude them from the REST client.
RoutineEndpoint[] filtered = [.. endpoints.Where(e => e.InternalOnly is false && e.CustomParameters.ParameterEnabled(Enabled) is not false)];
Dictionary<string, string> modelsDict = [];
Dictionary<string, int> names = [];
// Track generated composite type interfaces to avoid duplicates
// Key: composite type identifier (schema.typename), Value: generated interface name
Dictionary<string, string> compositeTypeInterfaces = [];
StringBuilder contentHeader = new();
StringBuilder content = new();
StringBuilder interfaces = new();
StringBuilder compositeInterfaces = new();
bool needsStatusTypes = false;
// Plain `interface` (module-private inline / ambient in .d.ts) vs exported `export interface` (importable module).
var interfaceDecl = options.ExportTypes ? "export interface" : "interface";
foreach (var import in options.CustomImports)
{
contentHeader.AppendLine(import);
}
if (filtered.Where(e => e.RequestParamType == RequestParamType.QueryString).Any())
{
contentHeader.AppendLine(
options.ImportBaseUrlFrom is not null ?
string.Format("import {{ baseUrl }} from \"{0}\";", options.ImportBaseUrlFrom) :
string.Format("const baseUrl = \"{0}\";", GetHost()));
bool haveParseQuery = filtered
.Where(e => e.RequestParamType == RequestParamType.QueryString &&
e.Routine.ParamCount > 0 &&
e.Routine.ParamCount > (e.PathParameters?.Length ?? 0))
.Any();
if (haveParseQuery)
{
if (!options.SkipTypes)
{
contentHeader.AppendLine(options.ImportParseQueryFrom is not null ?
string.Format(
"import {{ parseQuery }} from \"{0}\";", options.ImportParseQueryFrom) :
"""
const parseQuery = (query: Record<any, any>) => "?" + Object.keys(query ? query : {})
.map(key => {
const value = (query[key] != null ? query[key] : "") as string;
if (Array.isArray(value)) {
return value.map((s: string) => s ? `${key}=${encodeURIComponent(s)}` : `${key}=`).join("&");
}
return `${key}=${encodeURIComponent(value)}`;
})
.join("&");
""");
}
else
{
contentHeader.AppendLine(options.ImportParseQueryFrom is not null ?
string.Format(
"import {{ parseQuery }} from \"{0}\";", options.ImportParseQueryFrom) :
"""
const parseQuery = query => "?" + Object.keys(query ? query : {})
.map(key => {
const value = query[key] != null ? query[key] : "";
if (Array.isArray(value)) {
return value.map(s => s ? `${key}=${encodeURIComponent(s)}` : `${key}=`).join("&");
}
return `${key}=${encodeURIComponent(value)}`;
})
.join("&");
""");
}
}
}
else
{
contentHeader.AppendLine(
options.ImportBaseUrlFrom is not null ?
string.Format("import {{ baseUrl }} from \"{0}\";", options.ImportBaseUrlFrom) :
string.Format("const baseUrl = \"{0}\";", GetHost()));
}
if (options.ExportUrls)
{
contentHeader.AppendLine();
}
bool handled = false;
var lastContentHeaderWasUrl = false;
foreach (var endpoint in filtered
.Where(e => e.Routine.Type == RoutineType.Table || e.Routine.Type == RoutineType.View)
.OrderBy(e => e.Routine.Schema)
.ThenBy(e => e.Routine.Type)
.ThenBy(e => e.Routine.Name))
{
if (Handle(endpoint) && !handled)
{
handled = true;
}
}
foreach (var endpoint in filtered
.Where(e => !(e.Routine.Type == RoutineType.Table || e.Routine.Type == RoutineType.View))
.OrderBy(e => e.Routine.Schema)
.ThenBy(e => e.Routine.Name))
{
if (Handle(endpoint) && !handled)
{
handled = true;
}
}
// Emit type aliases for error and result types when needed
if (needsStatusTypes && !options.SkipTypes)
{
var errorTypeBody = options.ErrorType.EndsWith(" | undefined")
? options.ErrorType[..^12]
: options.ErrorType;
contentHeader.AppendLine();
contentHeader.AppendLine($"type {options.ErrorTypeName} = {errorTypeBody};");
contentHeader.AppendLine($"type {options.ResultTypeName}<T> = {{status: number, response: T, error: {options.ErrorTypeName} | undefined}};");
}
if (!handled)
{
if (filtered.Length == 0 && options.FileOverwrite)
{
if (File.Exists(fileName))
{
try
{
File.Delete(fileName);
Logger?.LogTrace("Deleted file: {fileName}", fileName);
}
catch (Exception ex)
{
Logger?.LogError(ex, "Failed to delete file: {fileName}", fileName);
try
{
File.WriteAllText(fileName, "// No endpoints found.");
}
catch (Exception ex2)
{
Logger?.LogError(ex2, "Failed to empty file: {fileName}", fileName);
}
}
}
}
return;
}
if (!options.FileOverwrite && File.Exists(fileName))
{
return;
}
var dir = Path.GetDirectoryName(fileName);
if (dir is not null && !Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
// Insert composite type interfaces at the beginning of interfaces
if (compositeInterfaces.Length > 0)
{
interfaces.Insert(0, compositeInterfaces.ToString());
}
if (!options.CreateSeparateTypeFile)
{
if (!options.SkipTypes)
{
interfaces.AppendLine(content.ToString());
if (contentHeader.Length > 0)
{
contentHeader.AppendLine();
interfaces.Insert(0, contentHeader.ToString());
}
AddHeader(interfaces);
File.WriteAllText(fileName, interfaces.ToString());
_filesCreated++;
Logger?.LogTrace("Created Typescript file: {fileName}", fileName);
}
else
{
if (contentHeader.Length > 0)
{
content.Insert(0, contentHeader.ToString());
}
AddHeader(content);
File.WriteAllText(fileName, content.ToString());
_filesCreated++;
Logger?.LogTrace("Created Javascript file: {fileName}", fileName);
}
}
else
{
if (!options.SkipTypes)
{
// ExportTypes turns the separate file into an importable module (`{name}Types.ts` with `export interface`);
// otherwise it stays an ambient global declaration file (`{name}Types.d.ts`) referenced without an import.
var typeFile = fileName.Replace(".ts", options.ExportTypes ? "Types.ts" : "Types.d.ts");
if (options.ExportTypes)
{
var typeNames = ExtractExportedTypeNames(interfaces.ToString());
if (typeNames.Count > 0)
{
var moduleName = Path.GetFileNameWithoutExtension(typeFile);
contentHeader.Insert(0, $"import type {{ {string.Join(", ", typeNames)} }} from \"./{moduleName}\";{Environment.NewLine}");
}
}
AddHeader(interfaces);
File.WriteAllText(typeFile, interfaces.ToString());
Logger?.LogTrace("Created Typescript type file: {typeFile}", typeFile);
}
if (contentHeader.Length > 0)
{
content.Insert(0, contentHeader.ToString());
}
AddHeader(content);
File.WriteAllText(fileName, content.ToString());
if (!options.SkipTypes)
{
_filesCreated++;
Logger?.LogTrace("Created Typescript file: {fileName}", fileName);
}
else
{
_filesCreated++;
Logger?.LogTrace("Created Javascript file: {fileName}", fileName);
}
}
return;
void AddHeader(StringBuilder sb)
{
if (options.HeaderLines.Count == 0)
{
return;
}
var now = DateTime.Now.ToString("O");
sb.Insert(0, string.Concat(string.Join(
Environment.NewLine,
options.HeaderLines.Select(l => string.Format(l, now).Trim())), Environment.NewLine)
);
}
bool Handle(RoutineEndpoint endpoint)
{
Routine routine = endpoint.Routine;
var eventsStreamingEnabled = endpoint.SseEventsPath is not null;
if (endpoint.CustomParameters.ParameterEnabled(SseEvents) is false)
{
eventsStreamingEnabled = false;
}
var includeParseUrlParam = endpoint.CustomParameters.ParameterEnabled(IncludeParseUrl) ?? options.IncludeParseUrlParam;
var includeParseRequestParam = endpoint.CustomParameters.ParameterEnabled(IncludeParseRequest) ?? options.IncludeParseRequestParam;
var includeStatusCode = endpoint.CustomParameters.ParameterEnabled(IncludeStatusCode) ?? options.IncludeStatusCode;
if (includeStatusCode)
{
needsStatusTypes = true;
}
var exportUrl = endpoint.CustomParameters.ParameterEnabled(ExportUrl) ?? options.ExportUrls;
var urlOnly = endpoint.CustomParameters.ParameterEnabled(UrlOnly) is true;
if (urlOnly)
{
exportUrl = true;
}
if (options.SkipRoutineNames.Contains(routine.Name))
{
return false;
}
if (options.SkipSchemas.Contains(routine.Schema))
{
return false;
}
if (options.SkipPaths.Contains(endpoint.Path))
{
return false;
}
string? name;
try
{
if (options.UseRoutineNameInsteadOfEndpoint)
{
name = options.IncludeSchemaInNames ? string.Concat(routine.Schema, "/", routine.Name) : routine.Name;
}
else
{
string pathName;
if (string.IsNullOrEmpty(_npgsqlRestoptions?.UrlPathPrefix) || _npgsqlRestoptions.UrlPathPrefix.Length > endpoint.Path.Length)
{
pathName = endpoint.Path;
}
else
{
pathName = endpoint.Path[_npgsqlRestoptions.UrlPathPrefix.Length..];
}
name = options.IncludeSchemaInNames ? string.Concat(routine.Schema, "/", pathName) : pathName;
}
}
catch
{
name = options.IncludeSchemaInNames ? string.Concat(routine.Schema, "/", routine.Name) : routine.Name;
}
if (name.Length < 3)
{
name = options.IncludeSchemaInNames ? string.Concat(routine.Schema, "/", routine.Name) : routine.Name;
}
var routineType = routine.Type;
var paramCount = routine.ParamCount;
//var paramTypeDescriptors = routine.ParamTypeDescriptor;
var isVoid = routine.IsVoid;
var returnsSet = routine.ReturnsSet;
var columnCount = routine.ColumnCount;
var returnsRecordType = routine.ReturnsRecordType;
var columnsTypeDescriptor = routine.ColumnsTypeDescriptor;
var returnsUnnamedSet = routine.ReturnsUnnamedSet;
if (endpoint.Login)
{
isVoid = false;
returnsSet = false;
columnCount = 1;
returnsRecordType = false;
columnsTypeDescriptor = [new TypeDescriptor("text")];
}
if (endpoint.Logout)
{
isVoid = true;
}
if (routineType == RoutineType.Table || routineType == RoutineType.View)
{
name = string.Concat(name, "-", endpoint.Method.ToString().ToLowerInvariant());
}
if (names.TryGetValue(name, out var count))
{
names[name] = count + 1;
name = string.Concat(name, "-", count);
}
else
{
names.Add(name, 1);
}
name = SanitizeJavaScriptVariableName(name);
var pascal = ConvertToPascalCase(name);
var camel = ConvertToCamelCase(name);
if (options.SkipFunctionNames.Contains(camel))
{
return false;
}
content.AppendLine();
string? requestName = null;
string[] paramNames = new string[paramCount];
// Parameters that are filled server-side and cannot be set by the client are omitted from the
// generated request shape when OmitAutomaticParameters is enabled (interface, query, body).
bool[] omitParam = new bool[paramCount];
int requestParamCount = 0;
string? bodyParameterName = null;
for (var i = 0; i < paramCount; i++)
{
var parameter = routine.Parameters[i];
var descriptor = parameter.TypeDescriptor;//paramTypeDescriptors[i];
if (options.OmitAutomaticParameters && endpoint.OmitParameterFromGeneratedRequest(parameter))
{
omitParam[i] = true;
continue;
}
requestParamCount++;
var nameSuffix = (descriptor.HasDefault || descriptor.CustomType is not null) ? "?" : "";
paramNames[i] = QuoteJavaScriptVariableName($"{parameter.ConvertedName}{nameSuffix}");
if (endpoint.IsBodyParameter(parameter))
{
// Use the bare converted name for emission — NOT paramNames[i], which carries the TS
// optional "?" suffix (e.g. "responseBody?"). That suffix is only for the interface
// property declaration; it must not leak into the runtime property name used for the
// body expression (request.responseBody) or the query-exclusion key (["responseBody"]).
bodyParameterName = parameter.ConvertedName;
}
}
string requestDesc = "";
if (requestParamCount > 0)
{
StringBuilder req = new();
requestName = $"I{pascal}Request";
requestDesc = string.Concat(requestDesc, "{");
var seenParamNames = new HashSet<string>(StringComparer.Ordinal);
for (var i = 0; i < paramCount; i++)
{
// Skip omitted (server-filled) parameters — their name was not assigned.
if (omitParam[i])
{
continue;
}
// Skip duplicate parameter names (e.g., when multiple HTTP custom types share field names)
if (!seenParamNames.Add(paramNames[i]))
{
continue;
}
var descriptor = routine.Parameters[i].TypeDescriptor;
var type = GetTsType(descriptor, false);
req.AppendLine($" {paramNames[i]}: {type} | null;");
requestDesc = string.Concat(requestDesc, $"{paramNames[i]}: {type} | null;");
}
requestDesc = string.Concat(requestDesc, "}");
if (modelsDict.TryGetValue(req.ToString(), out var newName))
{
requestName = newName;
}
else
{
if (!options.SkipTypes)
{
if (options.UniqueModels)
{
modelsDict.Add(req.ToString(), requestName);
}
req.Insert(0, $"{interfaceDecl} {requestName} {{{Environment.NewLine}");
req.AppendLine("}");
req.AppendLine();
interfaces.Append(req);
}
}
}
string responseName = "void";
bool json = false;
string? returnExp = null;
string GetReturnExp(string responseExp)
{
if (includeStatusCode)
{
var errorCast = options.SkipTypes
? options.ErrorExpression
: $"{options.ErrorExpression} as {options.ErrorTypeName}";
return string.Concat(
"return {",
Environment.NewLine,
" status: response.status,",
Environment.NewLine,
" response: ",
(responseExp == "await response.text()" ?
"response.ok ? " + responseExp + " : undefined!" :
string.Concat("response.ok ? ", responseExp, " : undefined!")),
",",
Environment.NewLine,
$" error: !response.ok && response.headers.get(\"content-length\") !== \"0\" ? {errorCast} : undefined",
Environment.NewLine,
" };");
}
return string.Concat("return ", responseExp, ";");
}
// proxy_out: always returns raw upstream response (function runs first, then proxies to upstream).
// proxy pass-through: when the routine is void, returns raw upstream response.
// Transform proxies (non-void @proxy routines) return processed data — fall through to normal handling.
if ((endpoint.IsProxyOut || (endpoint.IsProxy && routine.IsVoid)) && !urlOnly)
{
responseName = "Response";
returnExp = "return response;";
}
else if (routine.IsMultiCommand && routine.MultiCommandInfo is not null && !urlOnly)
{
// Multi-command SQL file: generate response interface with one property per command result
responseName = $"I{pascal}Response";
StringBuilder mcResp = new();
mcResp.AppendLine($"{interfaceDecl} {responseName} {{");
foreach (var cmdInfo in routine.MultiCommandInfo)
{
if (cmdInfo.IsSkipped) continue;
if (cmdInfo.ColumnCount == 0)
{
// Void command → rows affected count
mcResp.AppendLine($" {cmdInfo.Name}: number;");
}
else if (cmdInfo.ColumnCount == 1 && cmdInfo.ReturnsUnnamedSet)
{
// Single column with UnnamedSingleColumnSet — flat array or scalar with @single
var tsType = GetTsType(cmdInfo.ColumnTypeDescriptors[0], true);
var arraySuffix = cmdInfo.IsSingle ? "" : "[]";
mcResp.AppendLine($" {cmdInfo.Name}: {tsType}{arraySuffix};");
}
else if (cmdInfo.ColumnCount == 1)
{
// Single column — object array or object with @single
var tsType = GetTsType(cmdInfo.ColumnTypeDescriptors[0], true);
var arraySuffix = cmdInfo.IsSingle ? "" : "[]";
mcResp.AppendLine($" {cmdInfo.Name}: {{ {cmdInfo.ColumnNames[0]}: {tsType} }}{arraySuffix};");
}
else
{
// Multiple columns — inline object type array or object with @single
var fields = new StringBuilder();
for (int ci = 0; ci < cmdInfo.ColumnCount; ci++)
{
if (ci > 0) fields.Append(", ");
fields.Append(cmdInfo.ColumnNames[ci]);
fields.Append(": ");
fields.Append(GetTsType(cmdInfo.ColumnTypeDescriptors[ci], true));
}
var arraySuffix = cmdInfo.IsSingle ? "" : "[]";
mcResp.AppendLine($" {cmdInfo.Name}: {{ {fields} }}{arraySuffix};");
}
}
mcResp.AppendLine("}");
mcResp.AppendLine();
if (!options.SkipTypes)
{
interfaces.Append(mcResp);
}
returnExp = GetReturnExp($"await response.json() as {responseName}");
}
else if (!isVoid && !urlOnly)
{
if (endpoint.Upload)
{
responseName = $"I{pascal}Response";
StringBuilder resp = new();
resp.AppendLine($"{interfaceDecl} {responseName} {{");
resp.AppendLine(" type: string;");
resp.AppendLine(" fileName: string;");
resp.AppendLine(" contentType: string;");
resp.AppendLine(" size: number;");
resp.AppendLine(" success: boolean;");
resp.AppendLine(" status: string;");
resp.AppendLine(" [key: string]: string | number | boolean;");
resp.AppendLine("}");
resp.AppendLine();
interfaces.Append(resp);
responseName = string.Concat(responseName, "[]");
// Note: Don't set json = true here because upload endpoints use FormData,
// and the Content-Type header should be set automatically by the browser
if (!options.SkipTypes)
{
returnExp = GetReturnExp($"await response.json() as {responseName}");
}
else
{
returnExp = GetReturnExp("await response.json()");
}
}
else if (returnsSet == false && columnCount == 1 && !returnsRecordType)
{
var descriptor = columnsTypeDescriptor[0];
responseName = descriptor.IsJson ? "any" : GetTsType(descriptor, true);
if (descriptor.IsArray)
{
json = true;
//if (options.SkipTypes is false)
//{
// returnExp = GetReturnExp($"await response.json() as {responseName}[]");
//}
//else
//{
// returnExp = GetReturnExp("await response.json()");
//}
returnExp = GetReturnExp("await response.json()");
}
else
{
if (descriptor.IsDate || descriptor.IsDateTime)
{
returnExp = GetReturnExp("new Date(await response.text())");
}
else if (descriptor.IsNumeric)
{
returnExp = GetReturnExp("Number(await response.text())");
}
else if (descriptor.IsBoolean)
{
returnExp = GetReturnExp("await response.text() == \"t\"");
}
else if (descriptor.IsJson)
{
returnExp = GetReturnExp("await response.json()");
}
else
{
returnExp = GetReturnExp("await response.text()");
}
}
}
else
{
json = true;
if (returnsUnnamedSet)
{
if (columnCount > 0)
{
responseName = GetTsType(columnsTypeDescriptor[0], false);
}
else
{
responseName = "string[]";
}
}
else
{
StringBuilder resp = new();
responseName = $"I{pascal}Response";
// Check if nested JSON for composite types is enabled
// When false (default), composite fields are flattened in the JSON response
// When true, composite fields are nested under their column name
var useNestedCompositeTypes = endpoint.NestedJsonForCompositeTypes == true;
// Collect column indices to skip (expanded composite columns) - only when using nested types
HashSet<int> skipIndices = [];
if (useNestedCompositeTypes && routine.CompositeColumnInfo is not null)
{
foreach (var kvp in routine.CompositeColumnInfo)
{
// Skip all expanded column indices except the first one (which becomes the composite property)
foreach (var idx in kvp.Value.ExpandedColumnIndices.Skip(1))
{
skipIndices.Add(idx);
}
}
}
for (var i = 0; i < columnCount; i++)
{
// Skip expanded composite columns (only when nested types are enabled)
if (skipIndices.Contains(i))
{
continue;
}
// Check if this is a nested composite column - only generate nested interface when NestedJsonForCompositeTypes is true
if (useNestedCompositeTypes &&
routine.CompositeColumnInfo is not null &&
routine.CompositeColumnInfo.TryGetValue(i, out var compositeInfo))
{
// Generate interface for this composite type if not already done
var compositeInterfaceName = GetOrCreateCompositeInterface(
compositeInfo.FieldNames,
compositeInfo.FieldDescriptors,
compositeInfo.ConvertedColumnName,
compositeTypeInterfaces,
compositeInterfaces);
resp.AppendLine($" {compositeInfo.ConvertedColumnName}: {compositeInterfaceName} | null;");
continue;
}
// Check if this is an array of composite types
if (routine.ArrayCompositeColumnInfo is not null &&
routine.ArrayCompositeColumnInfo.TryGetValue(i, out var arrayCompositeInfo))
{
// Generate interface for this composite type if not already done
var compositeInterfaceName = GetOrCreateCompositeInterface(
arrayCompositeInfo.FieldNames,
arrayCompositeInfo.FieldDescriptors,
routine.ColumnNames[i],
compositeTypeInterfaces,
compositeInterfaces);
resp.AppendLine($" {routine.ColumnNames[i]}: {compositeInterfaceName}[] | null;");
continue;
}
var descriptor = columnsTypeDescriptor[i];
// SQL file composite type column: expand fields to match actual JSON response
if (descriptor.IsCompositeType &&
descriptor.CompositeFieldNames is not null &&
descriptor.CompositeFieldDescriptors is not null)
{
if (useNestedCompositeTypes)
{
// Nested mode: generate nested interface under column name
var compositeInterfaceName = GetOrCreateCompositeInterface(
descriptor.CompositeFieldNames,
descriptor.CompositeFieldDescriptors,
routine.ColumnNames[i],
compositeTypeInterfaces,
compositeInterfaces);
resp.AppendLine($" {routine.ColumnNames[i]}: {compositeInterfaceName} | null;");
}
else
{
// Flat mode: inline each composite field as a separate property
for (var fi = 0; fi < descriptor.CompositeFieldNames.Length; fi++)
{
var fieldName = ConvertToCamelCase(descriptor.CompositeFieldNames[fi]);
var fieldDescriptor = descriptor.CompositeFieldDescriptors[fi];
// Handle nested composite fields
if (fieldDescriptor.CompositeFieldNames is not null &&
fieldDescriptor.CompositeFieldDescriptors is not null)
{
var nestedInterfaceName = GetOrCreateCompositeInterface(
fieldDescriptor.CompositeFieldNames,
fieldDescriptor.CompositeFieldDescriptors,
fieldName,
compositeTypeInterfaces,
compositeInterfaces);
resp.AppendLine($" {fieldName}: {nestedInterfaceName} | null;");
}
else if (fieldDescriptor.ArrayCompositeFieldNames is not null &&
fieldDescriptor.ArrayCompositeFieldDescriptors is not null)
{
var nestedInterfaceName = GetOrCreateCompositeInterface(
fieldDescriptor.ArrayCompositeFieldNames,
fieldDescriptor.ArrayCompositeFieldDescriptors,
fieldName,
compositeTypeInterfaces,
compositeInterfaces);
resp.AppendLine($" {fieldName}: {nestedInterfaceName}[] | null;");
}
else
{
var fieldType = GetTsType(fieldDescriptor, false);
resp.AppendLine($" {fieldName}: {fieldType} | null;");
}
}
}
continue;
}
var type = GetTsType(descriptor, false);
if (descriptor.IsJson)
{
resp.AppendLine($" {routine.ColumnNames[i]}: any; // JSON");
}
else
{
resp.AppendLine($" {routine.ColumnNames[i]}: {type} | null;");
}
}
if (modelsDict.TryGetValue(resp.ToString(), out var newName))
{
responseName = newName;
}
else
{
if (!options.SkipTypes)
{
if (options.UniqueModels)
{
modelsDict.Add(resp.ToString(), responseName);
}
resp.Insert(0, $"{interfaceDecl} {responseName} {{{Environment.NewLine}");
resp.AppendLine("}");
resp.AppendLine();
interfaces.Append(resp);
}
}
}
if (returnsSet && !endpoint.ReturnSingleRecord)
{
responseName = string.Concat(responseName, "[]");
}
if (!options.SkipTypes)
{
returnExp = GetReturnExp($"await response.json() as {responseName}");
}
else
{
returnExp = GetReturnExp("await response.json()");
}
}
}
else
{
if (includeStatusCode)
{
var errorCast = options.SkipTypes
? options.ErrorExpression
: $"{options.ErrorExpression} as {options.ErrorTypeName}";
returnExp = string.Concat(
"return {",
Environment.NewLine,
" status: response.status,",
Environment.NewLine,
$" error: !response.ok && response.headers.get(\"content-length\") !== \"0\" ? {errorCast} : undefined",
Environment.NewLine,
" };");
}
}
string NewLine(string? input, int ident) =>
input is null ? "" : string.Concat(Environment.NewLine, string.Concat(Enumerable.Repeat(" ", ident)), input);
Dictionary<string, string> headersDict = [];
if (json)
{
headersDict.Add("Content-Type", "\"application/json\"");
}
if (eventsStreamingEnabled && _npgsqlRestoptions?.ExecutionIdHeaderName is not null)
{
headersDict.Add(_npgsqlRestoptions.ExecutionIdHeaderName, "executionId");
}
if (options.CustomHeaders.Count > 0)
{
foreach (var header in options.CustomHeaders)
{
if (string.IsNullOrEmpty(header.Value))
{
headersDict.Remove(header.Key);
}
else
{
headersDict[header.Key] = header.Value;
}
}
}
var body = endpoint.RequestParamType == RequestParamType.BodyJson && requestName is not null ?
@"body: JSON.stringify(request)" : null;
// For path parameters, we need to exclude them from the query string and from the body
var hasPathParams = endpoint.HasPathParameters;
var pathParamCount = endpoint.PathParameters?.Length ?? 0;
var bodyParamCount = bodyParameterName is not null ? 1 : 0;
// requestParamCount already excludes omitted (server-filled) parameters; path parameters are
// never omitted, so subtracting them and the body parameter yields the query parameter count.
var queryParamCount = requestParamCount - pathParamCount - bodyParamCount;
string qs;
if (endpoint.RequestParamType == RequestParamType.QueryString && requestName is not null && queryParamCount > 0)
{
if (hasPathParams || bodyParameterName is not null)
{
// Exclude path parameters and body parameter from query string
var exclusion = CreatePathParamExclusionExpression(
endpoint.PathParameters ?? [],
bodyParameterName);
qs = $" + parseQuery(({exclusion})";
}
else
{
qs = " + parseQuery(request)";
}
}
else
{
qs = "";
}
string? parameters = null;
List<(string name, string type, string desc)> paramComments = new();
if (requestName is not null)
{
if (!string.IsNullOrEmpty(parameters))
{
parameters = string.Concat(parameters, ",", Environment.NewLine);
}
else
{
parameters = string.Concat(parameters, Environment.NewLine);
}
if (!options.SkipTypes)
{
parameters = string.Concat(parameters, " request: ", requestName);
}
else
{
parameters = string.Concat(parameters, " request");
}
paramComments.Add(("request", requestDesc, "Object containing request parameters."));
}
if (eventsStreamingEnabled)
{
if (!string.IsNullOrEmpty(parameters))
{
parameters = string.Concat(parameters, ",", Environment.NewLine);
}
else
{
parameters = string.Concat(parameters, Environment.NewLine);
}
if (!options.SkipTypes)
{
parameters = string.Concat(parameters, " onMessage?: (message: string) => void");
}
else
{
parameters = string.Concat(parameters, " onMessage");
}
paramComments.Add(("onMessage", "(message: string) => void", "Optional callback function to handle incoming SSE messages."));
parameters = string.Concat(parameters, ",", Environment.NewLine);
if (!options.SkipTypes)
{