arri 0.0.5 → 0.0.6

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.
@@ -0,0 +1,826 @@
1
+ import { u as unflattenObject, p as pascalCase, i as isProcedureDefinition, a as isJsonSchemaScalarType, b as isJsonSchemaNullType, c as isJsonSchemaObject, d as isJsonSchemaEnum, e as isJsonSchemaArray, f as camelCase } from './shared/arri.b4c5ce27.mjs';
2
+ import { f as format2 } from './shared/arri.34695f7b.mjs';
3
+ import { writeFileSync } from 'fs';
4
+ import { execSync } from 'child_process';
5
+ import 'module';
6
+ import 'url';
7
+ import 'path';
8
+ import 'process';
9
+ import 'os';
10
+ import 'tty';
11
+ import 'assert';
12
+ import 'fs/promises';
13
+ import 'v8';
14
+ import 'util';
15
+
16
+ function defineClientGeneratorPlugin(plugin) {
17
+ return plugin;
18
+ }
19
+
20
+ let createdModels = [];
21
+ const typescriptClientGenerator = defineClientGeneratorPlugin(
22
+ (options) => ({
23
+ generator: async (def) => {
24
+ if (!options.clientName) {
25
+ throw new Error("Name is requires");
26
+ }
27
+ if (!options.outputFile) {
28
+ throw new Error("No output file specified");
29
+ }
30
+ const result = await createTypescriptClient(
31
+ def,
32
+ options.clientName
33
+ );
34
+ writeFileSync(options.outputFile, result);
35
+ },
36
+ options
37
+ })
38
+ );
39
+ async function createTypescriptClient(def, prefix = "Client") {
40
+ createdModels = [];
41
+ const services = unflattenObject(def.procedures);
42
+ const serviceParts = [];
43
+ const modelParts = [];
44
+ Object.keys(services).forEach((key) => {
45
+ const serviceName = pascalCase(`${prefix}_${key}_service`);
46
+ serviceParts.push({
47
+ name: serviceName,
48
+ key,
49
+ content: tsServiceFromServiceDefinition(serviceName, services[key])
50
+ });
51
+ });
52
+ Object.keys(def.models).forEach((key) => {
53
+ const modelName = pascalCase(`${key}`);
54
+ if (!createdModels.includes(modelName)) {
55
+ modelParts.push(tsModelFromDefinition(modelName, def.models[key]));
56
+ createdModels.push(modelName);
57
+ }
58
+ });
59
+ return format2(
60
+ `/* eslint-disable */
61
+ import { arriRequest, ArriRequestError } from 'arri-client';
62
+
63
+ export class ${prefix} {
64
+ ${serviceParts.map((service) => `${service.key}: ${service.name}`).join("\n")}
65
+ constructor(opts: { baseUrl?: string; headers?: Record<string, string> }) {
66
+ ${serviceParts.map(
67
+ (service) => `this.${service.key} = new ${service.name}(opts);`
68
+ ).join("\n")}
69
+ }
70
+ }
71
+
72
+ ${serviceParts.map((service) => service.content).join("\n")}
73
+ ${modelParts.join("\n")}`,
74
+ {
75
+ parser: "typescript"
76
+ }
77
+ );
78
+ }
79
+ function tsServiceFromServiceDefinition(name, def) {
80
+ const rpcParts = [];
81
+ const subServiceParts = [];
82
+ Object.keys(def).forEach((key) => {
83
+ const val = def[key];
84
+ if (isProcedureDefinition(val)) {
85
+ rpcParts.push(tsRpcFromProcedureDefinition(key, val));
86
+ return;
87
+ }
88
+ const subServiceName = pascalCase(
89
+ `${name.split("Service").join("")}_${key}_service`
90
+ );
91
+ subServiceParts.push({
92
+ name: subServiceName,
93
+ key,
94
+ content: tsServiceFromServiceDefinition(subServiceName, val)
95
+ });
96
+ });
97
+ return `export class ${name} {
98
+ private baseUrl: string;
99
+ private headers: Record<string, string>;
100
+ ${subServiceParts.map((service) => `${service.key}: ${service.name};`).join("\n")}
101
+ constructor(opts: { baseUrl?: string; headers?: Record<string, string> }) {
102
+ this.baseUrl = opts.baseUrl ?? "";
103
+ this.headers = opts.headers ?? {};
104
+ ${subServiceParts.map(
105
+ (service) => `this.${service.key} = new ${service.name}(opts);`
106
+ ).join("\n")}
107
+ }
108
+ ${rpcParts.join("\n")}
109
+ }
110
+ ${subServiceParts.map((service) => service.content).join("\n")}`;
111
+ }
112
+ function tsRpcFromProcedureDefinition(name, def) {
113
+ let paramStr = "";
114
+ let responseName = "";
115
+ if (def.params) {
116
+ paramStr = `params: ${def.params}`;
117
+ }
118
+ if (def.response) {
119
+ responseName = def.response;
120
+ }
121
+ return `async ${name}(${paramStr}) {
122
+ return arriRequest<${responseName || "undefined"}>({
123
+ url: \`\${this.baseUrl}${def.path}\`,
124
+ method: '${def.method}',
125
+ ${paramStr.length ? `params,` : ""}
126
+ headers: this.headers,
127
+ });
128
+ }`;
129
+ }
130
+ function tsModelFromDefinition(name, def) {
131
+ const fieldParts = [];
132
+ const subModelParts = [];
133
+ Object.keys(def.properties ?? {}).forEach((key) => {
134
+ const isOptional = !def.required?.includes(key);
135
+ const prop = def.properties?.[key];
136
+ const keyPart = isOptional ? `${key}?` : key;
137
+ if (isJsonSchemaScalarType(prop)) {
138
+ fieldParts.push(
139
+ tsInterfaceScalarField(key, prop, isOptional) ?? ""
140
+ );
141
+ return;
142
+ }
143
+ if (isJsonSchemaNullType(prop)) {
144
+ switch (prop.type) {
145
+ case "null":
146
+ fieldParts.push(`${keyPart}: null;`);
147
+ break;
148
+ case "undefined":
149
+ fieldParts.push(`${keyPart}: undefined`);
150
+ break;
151
+ }
152
+ return;
153
+ }
154
+ if (isJsonSchemaObject(prop)) {
155
+ const subModelName = prop.$id ?? pascalCase(`${name}_${key}`);
156
+ if (!createdModels.includes(subModelName)) {
157
+ const content = tsModelFromDefinition(
158
+ subModelName,
159
+ prop
160
+ );
161
+ subModelParts.push(content);
162
+ }
163
+ fieldParts.push(`${keyPart}: ${subModelName};`);
164
+ return;
165
+ }
166
+ if (isJsonSchemaEnum(prop)) {
167
+ const vals = prop.anyOf.map(
168
+ (opt) => opt.type === "string" ? `'${opt.const}'` : `${opt.const}`
169
+ );
170
+ fieldParts.push(`${keyPart}: ${vals.join(" | ")};`);
171
+ return;
172
+ }
173
+ if (isJsonSchemaArray(prop)) {
174
+ if (isJsonSchemaScalarType(prop.items)) {
175
+ const part = tsInterfaceScalarField(
176
+ key,
177
+ prop.items,
178
+ isOptional
179
+ ).replace(";", "[];");
180
+ fieldParts.push(part);
181
+ return;
182
+ }
183
+ if (isJsonSchemaNullType(prop.items)) {
184
+ if (prop.items.type === "null") {
185
+ fieldParts.push(`${keyPart}: null[]`);
186
+ return;
187
+ }
188
+ fieldParts.push(`${keyPart}: undefined[]`);
189
+ return;
190
+ }
191
+ if (isJsonSchemaObject(prop.items)) {
192
+ const subModelName = prop.items.$id ?? pascalCase(`${name}_${key}_item`);
193
+ if (!createdModels.includes(subModelName)) {
194
+ subModelParts.push(
195
+ tsModelFromDefinition(subModelName, prop.items)
196
+ );
197
+ }
198
+ fieldParts.push(`${keyPart}: ${subModelName}[];`);
199
+ }
200
+ }
201
+ });
202
+ return `export interface ${name} {
203
+ ${fieldParts.join("\n")}
204
+ }
205
+ ${subModelParts.join("\n")}`;
206
+ }
207
+ function tsInterfaceScalarField(key, prop, isOptional = false) {
208
+ const keyPart = isOptional ? `${key}?` : key;
209
+ switch (prop.type) {
210
+ case "string":
211
+ return `${keyPart}: string;`;
212
+ case "bigint":
213
+ return `${keyPart}: bigint;`;
214
+ case "Date":
215
+ return `${keyPart}: Date;`;
216
+ case "boolean":
217
+ return `${keyPart}: boolean;`;
218
+ case "integer":
219
+ return `/**
220
+ * must be an integer
221
+ */
222
+ ${keyPart}: number;`;
223
+ case "number":
224
+ return `${keyPart}: number;`;
225
+ }
226
+ }
227
+
228
+ const dartClientGenerator = defineClientGeneratorPlugin(
229
+ (options) => {
230
+ return {
231
+ generator: async (def) => {
232
+ if (!options.clientName) {
233
+ throw new Error(
234
+ 'Missing "clientName" cannot generate dart client'
235
+ );
236
+ }
237
+ if (!options.outputFile) {
238
+ throw new Error(
239
+ 'Missing "outputFile" cannot generate dart client'
240
+ );
241
+ }
242
+ const result = createDartClient(def, options.clientName);
243
+ writeFileSync(options.outputFile, result);
244
+ execSync(`dart format ${options.outputFile}`);
245
+ },
246
+ options
247
+ };
248
+ }
249
+ );
250
+ const generatedModels = [];
251
+ function createDartClient(appDef, prefix = "Client") {
252
+ const { models, procedures } = appDef;
253
+ const serviceParts = [];
254
+ const services = unflattenObject(procedures);
255
+ Object.keys(services).forEach((k) => {
256
+ const service = services[k];
257
+ const serviceName = pascalCase(`$_${prefix}_${k}_service`);
258
+ serviceParts.push({
259
+ name: serviceName,
260
+ key: k,
261
+ content: dartServiceFromServiceDefinition(
262
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
263
+ serviceName,
264
+ service,
265
+ prefix
266
+ )
267
+ });
268
+ });
269
+ const endpoints = {};
270
+ Object.keys(procedures).forEach((key) => {
271
+ const rpc = procedures[key];
272
+ endpoints[rpc.path] = rpc.method;
273
+ });
274
+ const modelParts = [];
275
+ Object.keys(models).forEach((key) => {
276
+ const model = models[key];
277
+ const typeName = `${prefix}${pascalCase(key)}`;
278
+ const objModel = model;
279
+ if (!generatedModels.includes(typeName)) {
280
+ modelParts.push(
281
+ dartModelFromJsonSchema(
282
+ `${prefix}${pascalCase(key)}`,
283
+ objModel
284
+ )
285
+ );
286
+ generatedModels.push(typeName);
287
+ }
288
+ });
289
+ return `// This code was autogenerated by arri. Do not modify directly.
290
+ import "dart:convert";
291
+ import "package:http/http.dart" as http;
292
+ import "package:arri_client/arri_client.dart";
293
+
294
+ class ${prefix} {
295
+ final String _baseUrl;
296
+ final Map<String, String> _headers;
297
+ const ${prefix}({
298
+ String baseUrl = "",
299
+ Map<String, String> headers = const {},
300
+ }): _headers = headers,
301
+ _baseUrl = baseUrl;
302
+ ${prefix} withHeaders(Map<String, String> headers) {
303
+ return ${prefix}(
304
+ baseUrl: _baseUrl,
305
+ headers: headers,
306
+ );
307
+ }
308
+ ${serviceParts.map(
309
+ (service) => `${service.name} get ${service.key} {
310
+ return ${service.name}(
311
+ baseUrl: _baseUrl, headers: _headers,
312
+ );
313
+ }`
314
+ ).join("\n ")}
315
+ Future<http.Response> rawRequest(
316
+ ${prefix}Endpoints endpoint, {
317
+ Map<String, String>? query,
318
+ dynamic body,
319
+ Map<String, String>? headers,
320
+ Encoding? encoding,
321
+ }) async {
322
+ return arriRequest(
323
+ "$_baseUrl\${endpoint.path}",
324
+ method: endpoint.method,
325
+ headers: headers ?? this._headers,
326
+ body: body,
327
+ query: query,
328
+ encoding: encoding,
329
+ );
330
+ }
331
+ }
332
+ ${serviceParts.map((item) => item.content).join("\n")}
333
+ ${modelParts.join("\n")}
334
+
335
+ enum ${prefix}Endpoints implements Comparable<${prefix}Endpoints>, ArriEndpoint {
336
+ ${Object.keys(endpoints).map(
337
+ (key) => `${camelCase(key.split("/").join("_"))}(
338
+ path: "${key}",
339
+ method: HttpMethod.${endpoints[key]},
340
+ )`
341
+ ).join(",\n ")};
342
+
343
+ const ${prefix}Endpoints({
344
+ required this.path, required this.method,
345
+ });
346
+ @override
347
+ final String path;
348
+ @override
349
+ final HttpMethod method;
350
+
351
+ @override
352
+ compareTo(${prefix}Endpoints other) => name.compareTo(other.name);
353
+ }`;
354
+ }
355
+ function dartServiceFromServiceDefinition(name, def, prefix = "") {
356
+ const rpcParts = [];
357
+ const subServiceParts = [];
358
+ const serviceName = `${name}`;
359
+ Object.keys(def).forEach((key) => {
360
+ const item = def[key];
361
+ if (isProcedureDefinition(item)) {
362
+ let returnType = `Future<String>`;
363
+ let returnTypeName = "String";
364
+ if (item.response) {
365
+ returnType = `Future<${prefix}${item.response}>`;
366
+ returnTypeName = `${prefix}${item.response}`;
367
+ } else {
368
+ returnType = "Future<void>";
369
+ }
370
+ let paramsInput = "";
371
+ if (item.params) {
372
+ paramsInput = `${prefix}${item.params} params`;
373
+ }
374
+ let responseParser = "(body) => body;";
375
+ switch (returnType) {
376
+ case "Future<String>":
377
+ break;
378
+ case "Future<int>":
379
+ responseParser = `(body) => Int.parse(body)`;
380
+ break;
381
+ case "Future<double>":
382
+ responseParser = `(body) => Double.parse(body)`;
383
+ break;
384
+ case "Future<void>":
385
+ responseParser = `(body) {}`;
386
+ break;
387
+ case "Future<bool>":
388
+ responseParser = `(body) {
389
+ switch(body) {
390
+ case "true":
391
+ case "1":
392
+ return true;
393
+ case "false":
394
+ case "0":
395
+ default:
396
+ return false;
397
+ }
398
+ }`;
399
+ break;
400
+ default:
401
+ responseParser = `(body) => ${returnTypeName}.fromJson(json.decode(body))`;
402
+ break;
403
+ }
404
+ rpcParts.push(`${returnType} ${key}(${paramsInput}) {
405
+ return parsedArriRequest(
406
+ "$_baseUrl${item.path}",
407
+ method: HttpMethod.${item.method},
408
+ headers: _headers,
409
+ params: ${paramsInput.length ? `params.toJson()` : "null"},
410
+ parser: ${responseParser},
411
+ );
412
+ }`);
413
+ return;
414
+ }
415
+ const subServiceName = pascalCase(`${name}_${key}_Service`);
416
+ const subService = dartServiceFromServiceDefinition(
417
+ pascalCase(`${name}_${key}_Service`),
418
+ item,
419
+ prefix
420
+ );
421
+ subServiceParts.push({
422
+ name: subServiceName,
423
+ key,
424
+ content: subService
425
+ });
426
+ });
427
+ return `class ${serviceName} {
428
+ final String _baseUrl;
429
+ final Map<String, String> _headers;
430
+ const ${serviceName}({
431
+ String baseUrl = "",
432
+ Map<String, String> headers = const {},
433
+ }): _baseUrl = baseUrl,
434
+ _headers = headers;
435
+ ${subServiceParts.map(
436
+ (sub) => `${sub.name} get ${sub.key} {
437
+ return ${sub.name}(
438
+ baseUrl: _baseUrl,
439
+ headers: _headers,
440
+ );
441
+ }`
442
+ ).join("\n")}
443
+ ${rpcParts.join("\n ")}
444
+ }
445
+ ${subServiceParts.map((sub) => sub.content).join("\n")}
446
+ `;
447
+ }
448
+ function dartModelFromJsonSchema(name, schema) {
449
+ const fields = [];
450
+ const subModelParts = [];
451
+ Object.entries(schema.properties ?? {}).forEach(([key, val]) => {
452
+ if (typeof val !== "object") {
453
+ return;
454
+ }
455
+ const [dartType, subTypes] = dartPropertyTypeFromSchema(
456
+ name,
457
+ key,
458
+ schema
459
+ );
460
+ if (subTypes?.length) {
461
+ for (const sub of subTypes) {
462
+ subModelParts.push(sub);
463
+ }
464
+ }
465
+ fields.push({ type: dartType, name: key });
466
+ if (!isDartType(dartType) && "type" in val && val.type === "object") {
467
+ subModelParts.push(
468
+ dartModelFromJsonSchema(dartType.replace("?", ""), val)
469
+ );
470
+ }
471
+ });
472
+ return `class ${name} {
473
+ ${fields.map((field) => `final ${field.type} ${field.name};`).join("\n ")}
474
+ const ${name}({
475
+ ${fields.map(
476
+ (field) => field.type.includes("?") ? `this.${field.name},` : `required this.${field.name},`
477
+ ).join("\n ")}
478
+ });
479
+ factory ${name}.fromJson(Map<String, dynamic> json) {
480
+ return ${name}(
481
+ ${fields.map((field) => `${dartParsedJsonField(field.name, field.type)},`).join("\n ")}
482
+ );
483
+ }
484
+ Map<String, dynamic> toJson() {
485
+ return {
486
+ ${fields.map((field) => {
487
+ const isNullable = field.type.endsWith("?");
488
+ const typeName = field.type.replace("?", "");
489
+ if (isDartTypeWithNullables(field.type)) {
490
+ const transformer = transformers[typeName];
491
+ return transformer.toJsonBody(field.name, isNullable);
492
+ }
493
+ if (field.type.includes("List<")) {
494
+ return classListTransformer(typeName).toJsonBody(
495
+ field.name,
496
+ isNullable
497
+ );
498
+ }
499
+ return classTransformer(typeName, isNullable).toJsonBody(
500
+ field.name,
501
+ isNullable
502
+ );
503
+ }).join(",\n ")},
504
+ };
505
+ }
506
+ ${name} copyWith({
507
+ ${fields.map((field) => `${field.type.replace("?", "")}? ${field.name},`).join("\n ")}
508
+ }) {
509
+ return ${name}(
510
+ ${fields.map((field) => `${field.name}: ${field.name} ?? this.${field.name},`).join("\n ")}
511
+ );
512
+ }
513
+ }
514
+
515
+ ${subModelParts.join("\n")}`;
516
+ }
517
+ function dartPropertyTypeFromSchema(objectName, propertyName, schema) {
518
+ const prop = schema.properties?.[propertyName];
519
+ const isOptional = !schema.required?.includes(propertyName);
520
+ let finalType = "";
521
+ const subTypes = [];
522
+ if (isJsonSchemaEnum(prop)) {
523
+ const enumName = pascalCase(`${objectName}_${propertyName}`);
524
+ finalType = isOptional ? `${enumName}?` : enumName;
525
+ const options = [];
526
+ for (const opt of prop.anyOf) {
527
+ if (opt.type === "string") {
528
+ options.push({
529
+ name: opt.const.toString(),
530
+ type: "String",
531
+ value: opt.const
532
+ });
533
+ }
534
+ if (opt.type === "number" || opt.type === "integer") {
535
+ options.push({
536
+ name: camelCase(
537
+ `num_${opt.const}`.split(".").join("Point")
538
+ ),
539
+ type: opt.type === "number" ? "double" : "int",
540
+ value: opt.const
541
+ });
542
+ }
543
+ }
544
+ subTypes.push(`enum ${enumName} implements Comparable<${enumName}> {
545
+ ${options.map(
546
+ (opt) => `${opt.name}(${opt.type === "String" ? `"${opt.value}"` : opt.value})`
547
+ ).join(",\n ")};
548
+ const ${enumName}(this.value);
549
+ final dynamic value;
550
+
551
+ @override
552
+ compareTo(${enumName} other) => name.compareTo(other.name);
553
+
554
+ factory ${enumName}.fromJson(dynamic input) {
555
+ for(final val in values) {
556
+ if(val.value == input) {
557
+ return val;
558
+ }
559
+ }
560
+ return ${options[0].name};
561
+ }
562
+
563
+ dynamic toJson() {
564
+ return value;
565
+ }
566
+ }`);
567
+ return [finalType, subTypes];
568
+ }
569
+ if (isJsonSchemaNullType(prop)) {
570
+ finalType = "null";
571
+ return [finalType, subTypes];
572
+ }
573
+ if (isJsonSchemaScalarType(prop)) {
574
+ switch (prop.type) {
575
+ case "string":
576
+ finalType = isOptional ? "String?" : "String";
577
+ break;
578
+ case "integer":
579
+ finalType = isOptional ? "int?" : "int";
580
+ break;
581
+ case "number":
582
+ finalType = isOptional ? "double?" : "double";
583
+ break;
584
+ case "Date":
585
+ finalType = isOptional ? "DateTime?" : "DateTime";
586
+ break;
587
+ case "boolean":
588
+ finalType = isOptional ? "bool?" : "bool";
589
+ break;
590
+ }
591
+ }
592
+ if (isJsonSchemaObject(prop)) {
593
+ const joinedPropName = pascalCase(
594
+ `${objectName}_${propertyName}`
595
+ );
596
+ finalType = isOptional ? `${joinedPropName}?` : joinedPropName;
597
+ }
598
+ if (isJsonSchemaArray(prop)) {
599
+ const item = prop.items;
600
+ const type = item.type;
601
+ if (typeof type !== "string") {
602
+ throw new Error(
603
+ "Union types are not supported in arrays at this time"
604
+ );
605
+ }
606
+ switch (type) {
607
+ case "string":
608
+ finalType = isOptional ? "List<String>?" : "List<String>";
609
+ break;
610
+ case "integer":
611
+ finalType = isOptional ? "List<int>?" : "List<int>";
612
+ break;
613
+ case "number":
614
+ finalType = isOptional ? "List<double>?" : "List<double>";
615
+ break;
616
+ case "null":
617
+ finalType = isOptional ? "List<null>?" : "List<null>";
618
+ break;
619
+ case "boolean":
620
+ finalType = isOptional ? "List<bool>?" : "List<bool>";
621
+ break;
622
+ case "Date":
623
+ finalType = isOptional ? "List<DateTime>?" : "List<DateTime>";
624
+ break;
625
+ case "object": {
626
+ const subTypeName = item.$id ?? pascalCase(`${objectName}_${propertyName}_item`);
627
+ const model = dartModelFromJsonSchema(subTypeName, item);
628
+ if (!generatedModels.includes(subTypeName)) {
629
+ subTypes.push(model);
630
+ generatedModels.push(subTypeName);
631
+ }
632
+ finalType = isOptional ? `List<${subTypeName}>?` : `List<${subTypeName}>`;
633
+ break;
634
+ }
635
+ }
636
+ }
637
+ return [finalType, subTypes.length ? subTypes : void 0];
638
+ }
639
+ function dartParsedJsonField(fieldName, dartType) {
640
+ if (isDartTypeWithNullables(dartType)) {
641
+ switch (dartType) {
642
+ case "String":
643
+ return transformers.String.fromJsonBody(fieldName, '""');
644
+ case "String?":
645
+ return transformers.String.fromJsonBody(fieldName, "null");
646
+ case "bool":
647
+ return transformers.bool.fromJsonBody(fieldName, "false");
648
+ case "double":
649
+ return transformers.double.fromJsonBody(fieldName, "0.0");
650
+ case "int":
651
+ return transformers.int.fromJsonBody(fieldName, "0");
652
+ case "null":
653
+ return transformers.null.fromJsonBody(fieldName, "");
654
+ case "DateTime":
655
+ return transformers.DateTime.fromJsonBody(
656
+ fieldName,
657
+ "DateTime(0)"
658
+ );
659
+ case "DateTime?":
660
+ return transformers.DateTime.fromJsonBody(fieldName, "null");
661
+ case "List<String>":
662
+ case "List<bool>":
663
+ case "List<double>":
664
+ case "List<int>":
665
+ case "List<null>":
666
+ return defaultListFromJsonBody(
667
+ fieldName,
668
+ dartType.replace("List<", "").replace(">", ""),
669
+ "[]"
670
+ );
671
+ default:
672
+ return `${fieldName}: json["${fieldName}"] is ${dartType.replace(
673
+ "?",
674
+ ""
675
+ )} ? json["${fieldName}"] : null`;
676
+ }
677
+ }
678
+ if (dartType.includes("List<")) {
679
+ const innerType = dartType.replace("List<", "").replace(">", "").replace("?", "");
680
+ return classListTransformer(innerType).fromJsonBody(
681
+ fieldName,
682
+ dartType.endsWith("?") ? "null" : "[]"
683
+ );
684
+ }
685
+ const classType = dartType.split("?").join("").trim();
686
+ return classTransformer(classType, dartType.endsWith("?")).fromJsonBody(
687
+ fieldName,
688
+ classType
689
+ );
690
+ }
691
+ const dartTypeMap = {
692
+ integer: "int",
693
+ bigint: "int",
694
+ number: "double",
695
+ string: "String",
696
+ boolean: "bool",
697
+ null: "null",
698
+ Date: "DateTime",
699
+ object: void 0,
700
+ list: void 0,
701
+ // eslint-disable-next-line object-shorthand
702
+ undefined: void 0,
703
+ array: void 0,
704
+ Uint8Array: "Uint8List"
705
+ };
706
+ const transformers = {
707
+ null: {
708
+ fromJsonBody: (_) => `null`,
709
+ toJsonBody: defaultToJsonBody
710
+ },
711
+ int: {
712
+ fromJsonBody: (key, fallback) => defaultFromJsonBody(key, "int", fallback),
713
+ toJsonBody: defaultToJsonBody
714
+ },
715
+ double: {
716
+ fromJsonBody: (key, fallback) => defaultFromJsonBody(key, "double", fallback),
717
+ toJsonBody: defaultToJsonBody
718
+ },
719
+ String: {
720
+ fromJsonBody: (key, fallback) => defaultFromJsonBody(key, "String", fallback),
721
+ toJsonBody: defaultToJsonBody
722
+ },
723
+ bool: {
724
+ fromJsonBody: (key, fallback) => defaultFromJsonBody(key, "bool", fallback),
725
+ toJsonBody: defaultToJsonBody
726
+ },
727
+ DateTime: {
728
+ fromJsonBody: (key, fallback) => `${key}: json["${key}"] is String ? DateTime.parse(json["${key}"]) : ${fallback}`,
729
+ toJsonBody: (key, isNullable) => `"${key}": ${key}${isNullable ? "?" : ""}.toIso8601String()`
730
+ },
731
+ "List<null>": {
732
+ fromJsonBody: (key, fallback) => defaultListFromJsonBody(key, "null", fallback),
733
+ toJsonBody: defaultToJsonBody
734
+ },
735
+ "List<int>": {
736
+ fromJsonBody: (key, fallback) => defaultListFromJsonBody(key, "int", fallback),
737
+ toJsonBody: defaultToJsonBody
738
+ },
739
+ "List<double>": {
740
+ fromJsonBody: (key, fallback) => defaultListFromJsonBody(key, "double", fallback),
741
+ toJsonBody: defaultToJsonBody
742
+ },
743
+ "List<String>": {
744
+ fromJsonBody: (key, fallback) => defaultListFromJsonBody(key, "String", fallback),
745
+ toJsonBody: defaultToJsonBody
746
+ },
747
+ "List<bool>": {
748
+ fromJsonBody: (key, fallback) => defaultListFromJsonBody(key, "bool", fallback),
749
+ toJsonBody: defaultToJsonBody
750
+ },
751
+ "List<DateTime>": {
752
+ fromJsonBody: (key, fallback) => `${key}: json["${key}"] is List<String> ?
753
+ (json["${key}"] as List<String>)
754
+ .map((item) => DateTime.parse(item)).toList() : ${fallback}`,
755
+ toJsonBody: (key, isNullable) => `"${key}": ${key}${isNullable ? "?" : ""}.map((val) => val.toIso8601String()).toList()`
756
+ },
757
+ Uint8List: {
758
+ fromJsonBody: (key, fallback) => `${key}: json["${key}"] is List ? Uint8List.fromList(json["${key}"]) : ${fallback}`,
759
+ toJsonBody: (key, isNullable) => `"${key}": ${key}${isNullable ? "?" : ""}.toList()`
760
+ },
761
+ "List<Uint8List>": {
762
+ fromJsonBody: (key, fallback) => `${key}: json["${key}"] is List && (json["${key}"] as List).isNotEmpty && (json["${key}"] as List).first is List ? json["${key}"] : ${fallback}`,
763
+ toJsonBody: (key, isNullable) => `"${key}": ${key}${isNullable ? "?" : ""}.map((val) => val.toList()).toList()`
764
+ }
765
+ };
766
+ function defaultFromJsonBody(key, typename, fallback) {
767
+ return `${key}: json["${key}"] is ${typename} ? json["${key}"] : ${fallback}`;
768
+ }
769
+ function defaultListFromJsonBody(key, typename, fallback) {
770
+ return `${key}: json["${key}"] is List<${typename}> ? json["${key}"] : ${fallback}`;
771
+ }
772
+ function defaultToJsonBody(key) {
773
+ return `"${key}": ${key}`;
774
+ }
775
+ const classTransformer = (typename, nullable) => {
776
+ return {
777
+ fromJsonBody: (key, fallback) => {
778
+ if (nullable) {
779
+ return `${key}: json["${key}"] is Map<String, dynamic> ?
780
+ ${typename}.fromJson(json["${key}"]) : null`;
781
+ }
782
+ return `${key}: ${typename}.fromJson(json["${key}"])`;
783
+ },
784
+ toJsonBody: (key, isNullable) => `"${key}": ${key}${isNullable ? "?" : ""}.toJson()`
785
+ };
786
+ };
787
+ const classListTransformer = (typename) => {
788
+ return {
789
+ fromJsonBody: (key, fallback) => {
790
+ return `${key}: json["${key}"] is List<Map<String, dynamic>> ?
791
+ (json["${key}"] as List<Map<String, dynamic>>)
792
+ .map((val) => ${typename}.fromJson(val)).toList() : ${fallback}`;
793
+ },
794
+ toJsonBody: (key, isNullable) => `"${key}": ${key}${isNullable ? "?" : ""}.map((val) => val.toJson()).toList()`
795
+ };
796
+ };
797
+ function isDartType(input) {
798
+ if (typeof input !== "string") {
799
+ return false;
800
+ }
801
+ for (const val of Object.values(dartTypeMap)) {
802
+ if (input === val) {
803
+ return true;
804
+ }
805
+ if (input.replace("List<", "").replace(">", "") === val) {
806
+ return true;
807
+ }
808
+ }
809
+ return false;
810
+ }
811
+ function isDartTypeWithNullables(input) {
812
+ if (typeof input !== "string") {
813
+ return false;
814
+ }
815
+ for (const val of Object.values(dartTypeMap)) {
816
+ if (input.replace("?", "") === val) {
817
+ return true;
818
+ }
819
+ if (input.replace("?", "").replace("List<", "").replace(">", "") === val) {
820
+ return true;
821
+ }
822
+ }
823
+ return false;
824
+ }
825
+
826
+ export { classListTransformer, classTransformer, createDartClient, createTypescriptClient, dartClientGenerator, dartModelFromJsonSchema, dartParsedJsonField, dartPropertyTypeFromSchema, dartServiceFromServiceDefinition, defineClientGeneratorPlugin, isDartType, isDartTypeWithNullables, transformers, tsModelFromDefinition, tsRpcFromProcedureDefinition, tsServiceFromServiceDefinition, typescriptClientGenerator };