@arrirpc/codegen-kotlin 0.85.0 → 0.86.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.
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import fs from 'node:fs';
2
- import { removeDisallowedChars, pascalCase, stringStartsWithNumber, camelCase, isServiceDefinition, isRpcDefinition, defineGeneratorPlugin, unflattenProcedures, isSchemaFormType, isSchemaFormEnum, isSchemaFormProperties, isSchemaFormElements, isSchemaFormValues, isSchemaFormDiscriminator, isSchemaFormRef } from '@arrirpc/codegen-utils';
2
+ import { removeDisallowedChars, pascalCase, stringStartsWithNumber, camelCase, isSchemaFormProperties, getUnionFallbackKey, isServiceDefinition, isRpcDefinition, defineGeneratorPlugin, unflattenProcedures, isSchemaFormType, isSchemaFormEnum, isSchemaFormElements, isSchemaFormValues, isSchemaFormDiscriminator, isSchemaFormUnion, isSchemaFormRef } from '@arrirpc/codegen-utils';
3
3
 
4
4
  const reservedIdentifierKeywords = [
5
5
  "as",
@@ -98,11 +98,12 @@ function isNullable(schema, context) {
98
98
  }
99
99
  function getCodeComment(metadata, prefix, valueField) {
100
100
  if (!metadata?.description && !metadata?.isDeprecated) return "";
101
- const descriptionPart = metadata.description?.split("\n").map((line) => `${prefix ?? ""}* ${line}`).join("\n");
102
- const finalDescription = metadata.description ? `${prefix ?? ""}/**
103
- ${descriptionPart}${prefix ?? ""}
104
- */` : "";
105
- const deprecationMessage = `@Deprecated(message = "This ${valueField ?? "item"} was marked as deprecated by the server")`;
101
+ const indent = prefix ?? "";
102
+ const descriptionPart = metadata.description?.split("\n").map((line) => `${indent} * ${line}`.trimEnd()).join("\n");
103
+ const finalDescription = metadata.description ? `${indent}/**
104
+ ${descriptionPart}
105
+ ${indent} */` : "";
106
+ const deprecationMessage = `${indent}@Deprecated(message = "This ${valueField ?? "item"} was marked as deprecated by the server")`;
106
107
  if (metadata.description && metadata.isDeprecated) {
107
108
  return `${finalDescription}
108
109
  ${deprecationMessage}
@@ -118,6 +119,31 @@ ${deprecationMessage}
118
119
  }
119
120
  return "";
120
121
  }
122
+ function indentTail(input, spaces) {
123
+ const padding = " ".repeat(spaces);
124
+ return input.split("\n").map(
125
+ (line, i) => i === 0 || line.length === 0 ? line : `${padding}${line}`
126
+ ).join("\n");
127
+ }
128
+ function kotlinEncodedQueryString(schema, context, input, target, key, toValue) {
129
+ const queryKey = encodeURIComponent(key);
130
+ if (context.isOptional) {
131
+ return `if (${input} != null) {
132
+ ${target}.add("${queryKey}=\${__encodeQueryValue(${toValue(input)})}")
133
+ }`;
134
+ }
135
+ if (schema.isNullable) {
136
+ const value = toValue("it");
137
+ let nullableValue = `${input}?.let { ${value} }`;
138
+ if (value === "it") {
139
+ nullableValue = input;
140
+ } else if (value.startsWith("it.")) {
141
+ nullableValue = `${input}?.${value.slice(3)}`;
142
+ }
143
+ return `${target}.add("${queryKey}=\${__encodeQueryValue(${nullableValue})}")`;
144
+ }
145
+ return `${target}.add("${queryKey}=\${__encodeQueryValue(${toValue(input)})}")`;
146
+ }
121
147
 
122
148
  function kotlinAnyFromSchema(schema, context) {
123
149
  const nullable = isNullable(schema, context);
@@ -130,28 +156,28 @@ function kotlinAnyFromSchema(schema, context) {
130
156
  fromJson(input) {
131
157
  if (context.isOptional) {
132
158
  return `when (${input}) {
133
- null -> null
134
- else -> ${input}
135
- }`;
159
+ null -> null
160
+ else -> ${input}
161
+ }`;
136
162
  }
137
163
  if (schema.isNullable) {
138
164
  return `when (${input}) {
139
- JsonNull -> null
140
- null -> null
141
- else -> ${input}
142
- }`;
165
+ JsonNull -> null
166
+ null -> null
167
+ else -> ${input}
168
+ }`;
143
169
  }
144
170
  return `when (${input}) {
145
- is JsonElement -> ${input}!!
146
- else -> JsonNull
147
- }`;
171
+ is JsonElement -> ${input}!!
172
+ else -> JsonNull
173
+ }`;
148
174
  },
149
175
  toJson(input, target) {
150
176
  if (schema.isNullable) {
151
177
  return `${target} += when (${input}) {
152
- null -> "null"
153
- else -> JsonInstance.encodeToString(${input})
154
- }`;
178
+ null -> "null"
179
+ else -> JsonInstance.encodeToString(${input})
180
+ }`;
155
181
  }
156
182
  return `${target} += JsonInstance.encodeToString(${input})`;
157
183
  },
@@ -180,58 +206,47 @@ function kotlinArrayFromSchema(schema, context) {
180
206
  isNullable: nullable,
181
207
  defaultValue,
182
208
  fromJson(input) {
183
- if (nullable) {
184
- return `when (${input}) {
185
- is JsonArray -> {
186
- val __value: ${typeName} = mutableListOf()
187
- for (__element in ${input}!!.jsonArray) {
188
- __value.add(
189
- ${subType.fromJson("__element")}
190
- )
191
- }
192
- __value
193
- }
194
-
195
- else -> null
196
- }`;
197
- }
198
209
  return `when (${input}) {
199
- is JsonArray -> {
200
- val __value: ${typeName} = mutableListOf()
201
- for (__element in ${input}!!.jsonArray) {
202
- __value.add(
203
- ${subType.fromJson("__element")}
204
- )
205
- }
206
- __value
207
- }
210
+ is JsonArray -> {
211
+ val __value: ${typeName} = mutableListOf()
212
+ for (__element in ${input}!!.jsonArray) {
213
+ __value.add(
214
+ ${indentTail(subType.fromJson("__element"), 16)}
215
+ )
216
+ }
217
+ __value
218
+ }
208
219
 
209
- else -> mutableListOf()
210
- }`;
220
+ else -> ${defaultValue}
221
+ }`;
211
222
  },
212
223
  toJson(input, target) {
224
+ const elementToJson = indentTail(
225
+ subType.toJson("__element", target),
226
+ 4
227
+ );
213
228
  if (schema.isNullable) {
214
229
  return `if (${input} == null) {
215
- ${target} += "null"
216
- } else {
217
- ${target} += "["
218
- for ((__index, __element) in ${input}.withIndex()) {
219
- if (__index != 0) {
220
- ${target} += ","
221
- }
222
- ${subType.toJson("__element", target)}
223
- }
224
- ${target} += "]"
225
- }`;
230
+ ${target} += "null"
231
+ } else {
232
+ ${target} += "["
233
+ for ((__index, __element) in ${input}.withIndex()) {
234
+ if (__index != 0) {
235
+ ${target} += ","
236
+ }
237
+ ${indentTail(elementToJson, 4)}
238
+ }
239
+ ${target} += "]"
240
+ }`;
226
241
  }
227
242
  return `${target} += "["
228
- for ((__index, __element) in ${input}.withIndex()) {
229
- if (__index != 0) {
230
- ${target} += ","
231
- }
232
- ${subType.toJson("__element", target)}
233
- }
234
- ${target} += "]"`;
243
+ for ((__index, __element) in ${input}.withIndex()) {
244
+ if (__index != 0) {
245
+ ${target} += ","
246
+ }
247
+ ${elementToJson}
248
+ }
249
+ ${target} += "]"`;
235
250
  },
236
251
  toQueryString() {
237
252
  return `__logError("[WARNING] arrays cannot be serialized to query params. Skipping field at ${context.instancePath}.")`;
@@ -251,23 +266,14 @@ function kotlinObjectFromSchema(schema, context) {
251
266
  isNullable: nullable,
252
267
  defaultValue,
253
268
  fromJson(input, key) {
254
- if (nullable) {
255
- return `when (${input}) {
256
- is JsonObject -> ${prefixedClassName}.fromJsonElement(
257
- ${input}!!,
258
- "$instancePath/${key}",
259
- )
260
- else -> null
261
- }`;
262
- }
263
269
  return `when (${input}) {
264
- is JsonObject -> ${prefixedClassName}.fromJsonElement(
265
- ${input}!!,
266
- "$instancePath/${key}",
267
- )
270
+ is JsonObject -> ${prefixedClassName}.fromJsonElement(
271
+ ${input}!!,
272
+ "$instancePath/${key}",
273
+ )
268
274
 
269
- else -> ${prefixedClassName}.new()
270
- }`;
275
+ else -> ${defaultValue}
276
+ }`;
271
277
  },
272
278
  toJson(input, target) {
273
279
  if (schema.isNullable) {
@@ -301,7 +307,7 @@ function kotlinObjectFromSchema(schema, context) {
301
307
  `output += "\\"${context.discriminatorKey}\\":\\"${context.discriminatorValue}\\""`
302
308
  );
303
309
  toQueryParts.push(
304
- `queryParts.add("${context.discriminatorKey}=${context.discriminatorValue}")`
310
+ `queryParts.add("${encodeURIComponent(context.discriminatorKey)}=${encodeURIComponent(context.discriminatorValue)}")`
305
311
  );
306
312
  }
307
313
  for (let i = 0; i < requiredKeys.length; i++) {
@@ -333,9 +339,7 @@ function kotlinObjectFromSchema(schema, context) {
333
339
  fromJsonParts.push(
334
340
  `val ${kotlinKey}: ${type.prefixedTypeName}${type.isNullable ? "?" : ""} = ${type.fromJson(`__input.jsonObject["${key}"]`, key)}`
335
341
  );
336
- defaultParts.push(
337
- ` ${kotlinKey} = ${type.defaultValue},`
338
- );
342
+ defaultParts.push(`${kotlinKey} = ${type.defaultValue}`);
339
343
  }
340
344
  for (let i = 0; i < optionalKeys.length; i++) {
341
345
  const isFirst = i === 0 && requiredKeys.length === 0 && !context.discriminatorKey;
@@ -355,24 +359,25 @@ function kotlinObjectFromSchema(schema, context) {
355
359
  if (type.content) {
356
360
  subContent.push(type.content);
357
361
  }
358
- const addCommaPart = isFirst ? "" : `
359
- if (hasProperties) output += ","
360
- `;
361
362
  fieldParts.push(
362
363
  `${getCodeComment(schema.optionalProperties[key].metadata, " ", "field")} val ${kotlinKey}: ${type.prefixedTypeName}? = null,`
363
364
  );
365
+ const optionalToJsonParts = [];
364
366
  if (hasKnownKeys) {
365
- toJsonParts.push(`if (${kotlinKey} != null) {
366
- output += ",\\"${key}\\":"
367
- ${type.toJson(kotlinKey, "output")}
368
- }`);
367
+ optionalToJsonParts.push(`output += ",\\"${key}\\":"`);
369
368
  } else {
370
- toJsonParts.push(`if (${kotlinKey} != null) {${addCommaPart}
371
- output += "\\"${key}\\":"
372
- ${type.toJson(kotlinKey, "output")}
373
- ${isLast ? "" : " hasProperties = true"}
374
- }`);
369
+ if (!isFirst) {
370
+ optionalToJsonParts.push(`if (hasProperties) output += ","`);
371
+ }
372
+ optionalToJsonParts.push(`output += "\\"${key}\\":"`);
373
+ }
374
+ optionalToJsonParts.push(type.toJson(kotlinKey, "output"));
375
+ if (!hasKnownKeys && !isLast) {
376
+ optionalToJsonParts.push("hasProperties = true");
375
377
  }
378
+ toJsonParts.push(`if (${kotlinKey} != null) {
379
+ ${indentTail(optionalToJsonParts.join("\n"), 4)}
380
+ }`);
376
381
  toQueryParts.push(type.toQueryString(kotlinKey, "queryParts", key));
377
382
  fromJsonParts.push(
378
383
  `val ${kotlinKey}: ${type.prefixedTypeName}? = ${type.fromJson(`__input.jsonObject["${key}"]`, key)}`
@@ -393,19 +398,17 @@ ${isLast ? "" : " hasProperties = true"}
393
398
  ${fieldParts.join("\n")}${!hasProperties ? " private val placeholderKey: Short = 0" : ""}
394
399
  ) : ${implementedClass} {${discriminatorField}
395
400
  override fun toJson(): String {
396
- ${toJsonParts.join("\n")}
401
+ ${indentTail(toJsonParts.join("\n"), 8)}
397
402
  }
398
403
 
399
404
  override fun toUrlQueryParams(): String {
400
- ${toQueryParts.join("\n")}
405
+ ${indentTail(toQueryParts.join("\n"), 8)}
401
406
  }
402
407
 
403
408
  companion object Factory : ${context.clientName}ModelFactory<${prefixedClassName}> {
404
409
  @JvmStatic
405
410
  override fun new(): ${prefixedClassName} {
406
- return ${prefixedClassName}(
407
- ${defaultParts.join("\n")}
408
- )
411
+ ${indentTail(constructorCall(prefixedClassName, defaultParts), 12)}
409
412
  }
410
413
 
411
414
  @JvmStatic
@@ -419,39 +422,63 @@ ${defaultParts.join("\n")}
419
422
  __logError("[WARNING] ${prefixedClassName}.fromJsonElement() expected kotlinx.serialization.json.JsonObject at $instancePath. Got \${__input.javaClass}. Initializing empty ${prefixedClassName}.")
420
423
  return new()
421
424
  }
422
- ${fromJsonParts.join("\n")}
423
- return ${prefixedClassName}(
424
- ${kotlinKeys.join(",\n ")}${hasProperties ? `,` : ""}
425
- )
425
+ ${indentTail([...fromJsonParts, constructorCall(prefixedClassName, kotlinKeys)].join("\n"), 12)}
426
426
  }
427
427
  }
428
- }
428
+ }${subContent.length ? `
429
429
 
430
- ${subContent.join("\n\n")}`;
430
+ ${subContent.join("\n\n")}` : ""}`;
431
431
  context.existingTypeIds.push(className);
432
432
  return {
433
433
  ...result,
434
434
  content
435
435
  };
436
436
  }
437
+ function constructorCall(className, args) {
438
+ if (args.length === 0) {
439
+ return `return ${className}()`;
440
+ }
441
+ return `return ${className}(
442
+ ${args.join(",\n ")},
443
+ )`;
444
+ }
437
445
 
438
- function kotlinDiscriminatorFromSchema(schema, context) {
439
- const kotlinDiscriminatorKey = kotlinIdentifier(schema.discriminator);
446
+ function kotlinUnionFromSchema(schema, context) {
447
+ if (schema.tagKey && !schema.valueKey) {
448
+ for (const key of Object.keys(schema.union)) {
449
+ if (!isSchemaFormProperties(schema.union[key])) {
450
+ throw new Error(
451
+ `Error at ${context.schemaPath}/union/${key}: All union variants must be an object when tagKey is specified without a valueKey`
452
+ );
453
+ }
454
+ }
455
+ return kotlinInternallyTaggedSealedInterface(
456
+ schema,
457
+ schema.tagKey,
458
+ schema.union,
459
+ "union",
460
+ context
461
+ );
462
+ }
463
+ return kotlinWrappedUnionFromSchema(schema, context);
464
+ }
465
+ function kotlinInternallyTaggedSealedInterface(schema, tagKey, variants, variantsSchemaKey, context) {
466
+ const kotlinDiscriminatorKey = kotlinIdentifier(tagKey);
440
467
  const className = getClassName(schema, context);
441
468
  const prefixedClassName = `${context.typePrefix}${className}`;
442
469
  const nullable = isNullable(schema, context);
443
470
  const subTypes = [];
444
471
  const subContent = [];
445
- for (const key of Object.keys(schema.mapping)) {
446
- const subSchema = schema.mapping[key];
472
+ for (const key of Object.keys(variants)) {
473
+ const subSchema = variants[key];
447
474
  const subType = kotlinObjectFromSchema(subSchema, {
448
475
  typePrefix: context.typePrefix,
449
476
  clientName: context.clientName,
450
477
  clientVersion: context.clientVersion,
451
478
  instancePath: context.instancePath,
452
- schemaPath: `${context.schemaPath}/mapping/${key}`,
479
+ schemaPath: `${context.schemaPath}/${variantsSchemaKey}/${key}`,
453
480
  existingTypeIds: context.existingTypeIds,
454
- discriminatorKey: schema.discriminator,
481
+ discriminatorKey: tagKey,
455
482
  discriminatorValue: key,
456
483
  discriminatorParentId: className
457
484
  });
@@ -467,6 +494,10 @@ function kotlinDiscriminatorFromSchema(schema, context) {
467
494
  if (subTypes.length === 0) {
468
495
  throw new Error("Discriminator schemas must have at least one mapping");
469
496
  }
497
+ const fallbackKey = getUnionFallbackKey(variants);
498
+ const fallbackType = subTypes.find(
499
+ (type) => type.discriminatorValue === fallbackKey
500
+ );
470
501
  const defaultValue = nullable ? "null" : `${prefixedClassName}.new()`;
471
502
  const result = {
472
503
  typeName: className,
@@ -475,12 +506,13 @@ function kotlinDiscriminatorFromSchema(schema, context) {
475
506
  defaultValue,
476
507
  fromJson(input, key) {
477
508
  return `when (${input}) {
478
- is JsonObject -> ${prefixedClassName}.fromJsonElement(
479
- ${input}!!,
480
- "$instancePath/${key}",
481
- )
482
- else -> ${defaultValue}
483
- }`;
509
+ is JsonObject -> ${prefixedClassName}.fromJsonElement(
510
+ ${input}!!,
511
+ "$instancePath/${key}",
512
+ )
513
+
514
+ else -> ${defaultValue}
515
+ }`;
484
516
  },
485
517
  toJson(input, target) {
486
518
  if (schema.isNullable) {
@@ -489,7 +521,7 @@ function kotlinDiscriminatorFromSchema(schema, context) {
489
521
  return `${target} += ${input}.toJson()`;
490
522
  },
491
523
  toQueryString() {
492
- return `__logError("[WARNING] nested objects cannot be serialized to query params. Skipping field at ${context.instancePath}.")`;
524
+ return `__logError("[WARNING] nested unions cannot be serialized to query params. Skipping field at ${context.instancePath}.")`;
493
525
  },
494
526
  content: ""
495
527
  };
@@ -503,7 +535,7 @@ function kotlinDiscriminatorFromSchema(schema, context) {
503
535
  companion object Factory : ${context.clientName}ModelFactory<${prefixedClassName}> {
504
536
  @JvmStatic
505
537
  override fun new(): ${prefixedClassName} {
506
- return ${subTypes[0].prefixedTypeName}.new()
538
+ return ${fallbackType.prefixedTypeName}.new()
507
539
  }
508
540
 
509
541
  @JvmStatic
@@ -514,12 +546,12 @@ function kotlinDiscriminatorFromSchema(schema, context) {
514
546
  @JvmStatic
515
547
  override fun fromJsonElement(__input: JsonElement, instancePath: String): ${prefixedClassName} {
516
548
  if (__input !is JsonObject) {
517
- __logError("[WARNING] Discriminator.fromJsonElement() expected kotlinx.serialization.json.JsonObject at $instancePath. Got \${__input.javaClass}. Initializing empty ${prefixedClassName}.")
549
+ __logError("[WARNING] ${prefixedClassName}.fromJsonElement() expected kotlinx.serialization.json.JsonObject at $instancePath. Got \${__input.javaClass}. Initializing empty ${prefixedClassName}.")
518
550
  return new()
519
551
  }
520
- return when (__input.jsonObject["${schema.discriminator}"]) {
521
- is JsonPrimitive -> when (__input.jsonObject["${schema.discriminator}"]!!.jsonPrimitive.contentOrNull) {
522
- ${subTypes.map((type) => `"${type.discriminatorValue}" -> ${type.prefixedTypeName}.fromJsonElement(__input, instancePath)`).join("\n")}
552
+ return when (__input.jsonObject["${tagKey}"]) {
553
+ is JsonPrimitive -> when (__input.jsonObject["${tagKey}"]!!.jsonPrimitive.contentOrNull) {
554
+ ${subTypes.map((type) => `"${type.discriminatorValue}" -> ${type.prefixedTypeName}.fromJsonElement(__input, instancePath)`).join("\n ")}
523
555
  else -> new()
524
556
  }
525
557
 
@@ -527,9 +559,176 @@ function kotlinDiscriminatorFromSchema(schema, context) {
527
559
  }
528
560
  }
529
561
  }
562
+ }${subContent.length ? `
563
+
564
+ ${subContent.join("\n\n")}` : ""}`;
565
+ context.existingTypeIds.push(className);
566
+ return {
567
+ ...result,
568
+ content
569
+ };
530
570
  }
571
+ function kotlinWrappedUnionFromSchema(schema, context) {
572
+ const className = getClassName(schema, context);
573
+ const prefixedClassName = `${context.typePrefix}${className}`;
574
+ const nullable = isNullable(schema, context);
575
+ const defaultValue = nullable ? "null" : `${prefixedClassName}.new()`;
576
+ const result = {
577
+ typeName: className,
578
+ prefixedTypeName: prefixedClassName,
579
+ isNullable: nullable,
580
+ defaultValue,
581
+ fromJson(input, key) {
582
+ return `when (${input}) {
583
+ is JsonObject -> ${prefixedClassName}.fromJsonElement(
584
+ ${input}!!,
585
+ "$instancePath/${key}",
586
+ )
531
587
 
532
- ${subContent.join("\n\n")}`;
588
+ else -> ${defaultValue}
589
+ }`;
590
+ },
591
+ toJson(input, target) {
592
+ if (schema.isNullable) {
593
+ return `${target} += ${input}?.toJson()`;
594
+ }
595
+ return `${target} += ${input}.toJson()`;
596
+ },
597
+ toQueryString() {
598
+ return `__logError("[WARNING] nested unions cannot be serialized to query params. Skipping field at ${context.instancePath}.")`;
599
+ },
600
+ content: ""
601
+ };
602
+ if (context.existingTypeIds.includes(className)) {
603
+ return result;
604
+ }
605
+ const keys = Object.keys(schema.union);
606
+ if (keys.length === 0) {
607
+ throw new Error(
608
+ `Error at ${context.schemaPath}: Union schemas must have at least one variant`
609
+ );
610
+ }
611
+ const tagKey = schema.tagKey;
612
+ const tagProp = tagKey ? kotlinIdentifier(tagKey) : void 0;
613
+ const valueKey = schema.valueKey ?? "value";
614
+ const valueProp = kotlinIdentifier(valueKey);
615
+ const variants = [];
616
+ const variantContent = [];
617
+ const subContent = [];
618
+ for (const key of keys) {
619
+ const subSchema = schema.union[key];
620
+ const variantClassName = `${context.typePrefix}${kotlinClassName(`${className}_${key}`)}`;
621
+ const valueType = kotlinTypeFromSchema(subSchema, {
622
+ typePrefix: context.typePrefix,
623
+ clientName: context.clientName,
624
+ clientVersion: context.clientVersion,
625
+ instancePath: `/${className}/${key}/${valueKey}`,
626
+ schemaPath: `${context.schemaPath}/union/${key}`,
627
+ existingTypeIds: context.existingTypeIds
628
+ });
629
+ if (valueType.content) {
630
+ subContent.push(valueType.content);
631
+ }
632
+ variants.push({ key, prefixedClassName: variantClassName });
633
+ const jsonValueKey = tagKey ? valueKey : key;
634
+ const valueTypeName = `${valueType.prefixedTypeName}${valueType.isNullable ? "?" : ""}`;
635
+ const tagField = tagProp ? `
636
+ override val ${tagProp} get() = "${key}"
637
+ ` : "";
638
+ const toJsonParts = tagProp ? [
639
+ `output += "\\"${tagKey}\\":\\"${key}\\""`,
640
+ `output += ",\\"${jsonValueKey}\\":"`
641
+ ] : [`output += "\\"${jsonValueKey}\\":"`];
642
+ toJsonParts.push(valueType.toJson(valueProp, "output"));
643
+ variantContent.push(`data class ${variantClassName}(
644
+ val ${valueProp}: ${valueTypeName},
645
+ ) : ${prefixedClassName} {${tagField}
646
+ override fun toJson(): String {
647
+ var output = "{"
648
+ ${indentTail(toJsonParts.join("\n"), 8)}
649
+ output += "}"
650
+ return output
651
+ }
652
+
653
+ override fun toUrlQueryParams(): String {
654
+ __logError("[WARNING] unions cannot be serialized to query params. Skipping ${variantClassName}.")
655
+ return ""
656
+ }
657
+
658
+ companion object Factory : ${context.clientName}ModelFactory<${variantClassName}> {
659
+ @JvmStatic
660
+ override fun new(): ${variantClassName} {
661
+ return ${variantClassName}(
662
+ ${valueProp} = ${valueType.defaultValue},
663
+ )
664
+ }
665
+
666
+ @JvmStatic
667
+ override fun fromJson(input: String): ${variantClassName} {
668
+ return fromJsonElement(JsonInstance.parseToJsonElement(input))
669
+ }
670
+
671
+ @JvmStatic
672
+ override fun fromJsonElement(__input: JsonElement, instancePath: String): ${variantClassName} {
673
+ if (__input !is JsonObject) {
674
+ __logError("[WARNING] ${variantClassName}.fromJsonElement() expected kotlinx.serialization.json.JsonObject at $instancePath. Got \${__input.javaClass}. Initializing empty ${variantClassName}.")
675
+ return new()
676
+ }
677
+ val ${valueProp}: ${valueTypeName} = ${indentTail(valueType.fromJson(`__input.jsonObject["${jsonValueKey}"]`, jsonValueKey), 12)}
678
+ return ${variantClassName}(
679
+ ${valueProp},
680
+ )
681
+ }
682
+ }
683
+ }`);
684
+ }
685
+ const fallbackKey = getUnionFallbackKey(schema.union);
686
+ const fallbackVariant = variants.find(
687
+ (variant) => variant.key === fallbackKey
688
+ );
689
+ let fromJsonBody;
690
+ if (tagKey && tagProp) {
691
+ fromJsonBody = ` return when (__input.jsonObject["${tagKey}"]) {
692
+ is JsonPrimitive -> when (__input.jsonObject["${tagKey}"]!!.jsonPrimitive.contentOrNull) {
693
+ ${variants.map((variant) => `"${variant.key}" -> ${variant.prefixedClassName}.fromJsonElement(__input, instancePath)`).join("\n ")}
694
+ else -> new()
695
+ }
696
+
697
+ else -> new()
698
+ }`;
699
+ } else {
700
+ fromJsonBody = ` return when {
701
+ ${variants.map((variant) => `"${variant.key}" in __input -> ${variant.prefixedClassName}.fromJsonElement(__input, instancePath)`).join("\n ")}
702
+ else -> new()
703
+ }`;
704
+ }
705
+ const codeComment = getCodeComment(schema.metadata, "", "class");
706
+ const content = `${codeComment}sealed interface ${prefixedClassName} : ${context.clientName}Model {${tagProp ? `
707
+ val ${tagProp}: String
708
+ ` : ""}
709
+ companion object Factory : ${context.clientName}ModelFactory<${prefixedClassName}> {
710
+ @JvmStatic
711
+ override fun new(): ${prefixedClassName} {
712
+ return ${fallbackVariant.prefixedClassName}.new()
713
+ }
714
+
715
+ @JvmStatic
716
+ override fun fromJson(input: String): ${prefixedClassName} {
717
+ return fromJsonElement(JsonInstance.parseToJsonElement(input))
718
+ }
719
+
720
+ @JvmStatic
721
+ override fun fromJsonElement(__input: JsonElement, instancePath: String): ${prefixedClassName} {
722
+ if (__input !is JsonObject) {
723
+ __logError("[WARNING] ${prefixedClassName}.fromJsonElement() expected kotlinx.serialization.json.JsonObject at $instancePath. Got \${__input.javaClass}. Initializing empty ${prefixedClassName}.")
724
+ return new()
725
+ }
726
+ ${fromJsonBody}
727
+ }
728
+ }
729
+ }
730
+
731
+ ${[...variantContent, ...subContent].join("\n\n")}`;
533
732
  context.existingTypeIds.push(className);
534
733
  return {
535
734
  ...result,
@@ -537,6 +736,16 @@ ${subContent.join("\n\n")}`;
537
736
  };
538
737
  }
539
738
 
739
+ function kotlinDiscriminatorFromSchema(schema, context) {
740
+ return kotlinInternallyTaggedSealedInterface(
741
+ schema,
742
+ schema.discriminator,
743
+ schema.mapping,
744
+ "mapping",
745
+ context
746
+ );
747
+ }
748
+
540
749
  function kotlinEnumFromSchema(schema, context) {
541
750
  const nullable = isNullable(schema, context);
542
751
  const className = getClassName(schema, context);
@@ -557,11 +766,12 @@ function kotlinEnumFromSchema(schema, context) {
557
766
  if (!context.existingTypeIds.includes(className)) {
558
767
  content = `enum class ${prefixedClassName} {
559
768
  ${enumItems.map((item) => item.name).join(",\n ")};
769
+
560
770
  val serialValue: String
561
771
  get() = when (this) {
562
772
  ${enumItems.map((item) => `${item.name} -> "${item.value}"`).join("\n ")}
563
773
  }
564
-
774
+
565
775
  companion object Factory : ${context.clientName}ModelFactory<${prefixedClassName}> {
566
776
  @JvmStatic
567
777
  override fun new(): ${prefixedClassName} {
@@ -597,38 +807,30 @@ function kotlinEnumFromSchema(schema, context) {
597
807
  isNullable: nullable,
598
808
  defaultValue,
599
809
  fromJson(input, key) {
600
- if (nullable) {
601
- return `when (${input}) {
602
- is JsonNull -> null
603
- is JsonPrimitive -> ${prefixedClassName}.fromJsonElement(${input}!!, "$instancePath/${key ?? ""}")
604
- else -> null
605
- }`;
606
- }
607
810
  return `when (${input}) {
608
- is JsonNull -> ${defaultValue}
609
- is JsonPrimitive -> ${prefixedClassName}.fromJsonElement(${input}!!, "$instancePath/${key}")
610
- else -> ${defaultValue}
611
- }`;
811
+ is JsonNull -> ${defaultValue}
812
+ is JsonPrimitive -> ${prefixedClassName}.fromJsonElement(${input}!!, "$instancePath/${key ?? ""}")
813
+ else -> ${defaultValue}
814
+ }`;
612
815
  },
613
816
  toJson(input, target) {
614
817
  if (schema.isNullable) {
615
818
  return `${target} += when (${input}) {
616
- is ${prefixedClassName} -> "\\"\${${input}.serialValue}\\""
617
- else -> "null"
618
- }`;
819
+ is ${prefixedClassName} -> "\\"\${${input}.serialValue}\\""
820
+ else -> "null"
821
+ }`;
619
822
  }
620
823
  return `${target} += "\\"\${${input}.serialValue}\\""`;
621
824
  },
622
825
  toQueryString(input, target, key) {
623
- if (context.isOptional) {
624
- return `if (${input} != null) {
625
- ${target}.add("${key}=\${${input}.serialValue}")
626
- }`;
627
- }
628
- if (schema.isNullable) {
629
- return `${target}.add("${key}=\${${input}?.serialValue}")`;
630
- }
631
- return `${target}.add("${key}=\${${input}.serialValue}")`;
826
+ return kotlinEncodedQueryString(
827
+ schema,
828
+ context,
829
+ input,
830
+ target,
831
+ key,
832
+ (value) => `${value}.serialValue`
833
+ );
632
834
  },
633
835
  content
634
836
  };
@@ -653,42 +855,46 @@ function kotlinMapFromSchema(schema, context) {
653
855
  defaultValue,
654
856
  fromJson(input, key) {
655
857
  return `when (${input}) {
656
- is JsonObject -> {
657
- val __value: ${typeName} = mutableMapOf()
658
- for (__entry in ${input}!!.jsonObject.entries) {
659
- __value[__entry.key] = ${subType.fromJson("__entry.value", key)}
660
- }
661
- __value
662
- }
858
+ is JsonObject -> {
859
+ val __value: ${typeName} = mutableMapOf()
860
+ for (__entry in ${input}!!.jsonObject.entries) {
861
+ __value[__entry.key] = ${indentTail(subType.fromJson("__entry.value", key), 12)}
862
+ }
863
+ __value
864
+ }
663
865
 
664
- else -> ${defaultValue}
665
- }`;
866
+ else -> ${defaultValue}
867
+ }`;
666
868
  },
667
869
  toJson(input, target) {
870
+ const valueToJson = indentTail(
871
+ subType.toJson("__entry.value", target),
872
+ 4
873
+ );
668
874
  if (schema.isNullable) {
669
875
  return `if (${input} == null) {
670
- ${target} += "null"
671
- } else {
672
- ${target} += "{"
673
- for ((__index, __entry) in ${input}.entries.withIndex()) {
674
- if (__index != 0) {
675
- ${target} += ","
676
- }
677
- ${target} += "\${buildString { printQuoted(__entry.key) }}:"
678
- ${subType.toJson("__entry.value", target)}
679
- }
680
- ${target} += "}"
681
- }`;
876
+ ${target} += "null"
877
+ } else {
878
+ ${target} += "{"
879
+ for ((__index, __entry) in ${input}.entries.withIndex()) {
880
+ if (__index != 0) {
881
+ ${target} += ","
882
+ }
883
+ ${target} += "\${buildString { printQuoted(__entry.key) }}:"
884
+ ${indentTail(valueToJson, 4)}
885
+ }
886
+ ${target} += "}"
887
+ }`;
682
888
  }
683
889
  return `${target} += "{"
684
- for ((__index, __entry) in ${input}.entries.withIndex()) {
685
- if (__index != 0) {
686
- ${target} += ","
687
- }
688
- ${target} += "\${buildString { printQuoted(__entry.key) }}:"
689
- ${subType.toJson("__entry.value", target)}
690
- }
691
- ${target} += "}"`;
890
+ for ((__index, __entry) in ${input}.entries.withIndex()) {
891
+ if (__index != 0) {
892
+ ${target} += ","
893
+ }
894
+ ${target} += "\${buildString { printQuoted(__entry.key) }}:"
895
+ ${valueToJson}
896
+ }
897
+ ${target} += "}"`;
692
898
  },
693
899
  toQueryString() {
694
900
  return `__logError("[WARNING] nested objects cannot be serialized to query params. Skipping field at ${context.instancePath}.")`;
@@ -698,12 +904,13 @@ function kotlinMapFromSchema(schema, context) {
698
904
  }
699
905
 
700
906
  function defaultToQueryString(context, input, target, key) {
907
+ const queryKey = encodeURIComponent(key);
701
908
  if (context.isOptional) {
702
909
  return `if (${input} != null) {
703
- ${target}.add("${key}=$${input}")
704
- }`;
910
+ ${target}.add("${queryKey}=$${input}")
911
+ }`;
705
912
  }
706
- return `${target}.add("${key}=$${input}")`;
913
+ return `${target}.add("${queryKey}=$${input}")`;
707
914
  }
708
915
  function defaultToJsonString(context, input, target) {
709
916
  return `${target} += ${input}`;
@@ -719,26 +926,33 @@ function kotlinStringFromSchema(schema, context) {
719
926
  fromJson(input) {
720
927
  if (nullable) {
721
928
  return `when (${input}) {
722
- is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull
723
- else -> null
724
- }`;
929
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull
930
+ else -> null
931
+ }`;
725
932
  }
726
933
  return `when (${input}) {
727
- is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull ?: ${defaultValue}
728
- else -> ${defaultValue}
729
- }`;
934
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull ?: ${defaultValue}
935
+ else -> ${defaultValue}
936
+ }`;
730
937
  },
731
938
  toJson(input, target) {
732
939
  if (schema.isNullable) {
733
940
  return `${target} += when (${input}) {
734
- is String -> buildString { printQuoted(${input}) }
735
- else -> "null"
736
- }`;
941
+ is String -> buildString { printQuoted(${input}) }
942
+ else -> "null"
943
+ }`;
737
944
  }
738
945
  return `${target} += buildString { printQuoted(${input}) }`;
739
946
  },
740
947
  toQueryString(input, target, key) {
741
- return defaultToQueryString(context, input, target, key);
948
+ return kotlinEncodedQueryString(
949
+ schema,
950
+ context,
951
+ input,
952
+ target,
953
+ key,
954
+ (value) => value
955
+ );
742
956
  },
743
957
  content: ""
744
958
  };
@@ -754,14 +968,14 @@ function kotlinBooleanFromSchema(schema, context) {
754
968
  fromJson(input) {
755
969
  if (nullable) {
756
970
  return `when (${input}) {
757
- is JsonPrimitive -> ${input}!!.jsonPrimitive.booleanOrNull
758
- else -> null
759
- }`;
971
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.booleanOrNull
972
+ else -> null
973
+ }`;
760
974
  }
761
975
  return `when (${input}) {
762
- is JsonPrimitive -> ${input}!!.jsonPrimitive.booleanOrNull ?: ${defaultValue}
763
- else -> ${defaultValue}
764
- }`;
976
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.booleanOrNull ?: ${defaultValue}
977
+ else -> ${defaultValue}
978
+ }`;
765
979
  },
766
980
  toJson(input, target) {
767
981
  return defaultToJsonString(context, input, target);
@@ -774,7 +988,7 @@ function kotlinBooleanFromSchema(schema, context) {
774
988
  }
775
989
  function kotlinTimestampFromSchema(schema, context) {
776
990
  const nullable = isNullable(schema, context);
777
- const defaultValue = nullable ? "null" : "Instant.now()";
991
+ const defaultValue = nullable ? "null" : "Instant.EPOCH";
778
992
  return {
779
993
  typeName: "Instant",
780
994
  prefixedTypeName: "Instant",
@@ -782,48 +996,37 @@ function kotlinTimestampFromSchema(schema, context) {
782
996
  defaultValue,
783
997
  fromJson(input) {
784
998
  return `when (${input}) {
785
- is JsonPrimitive ->
786
- if (${input}!!.jsonPrimitive.isString)
787
- Instant.parse(${input}!!.jsonPrimitive.content)
788
- else
789
- ${defaultValue}
790
- else -> ${defaultValue}
791
- }`;
999
+ is JsonPrimitive ->
1000
+ if (${input}!!.jsonPrimitive.isString)
1001
+ try {
1002
+ Instant.parse(${input}!!.jsonPrimitive.content)
1003
+ } catch (e: java.time.format.DateTimeParseException) {
1004
+ ${defaultValue}
1005
+ }
1006
+ else
1007
+ ${defaultValue}
1008
+
1009
+ else -> ${defaultValue}
1010
+ }`;
792
1011
  },
793
1012
  toJson(input, target) {
794
1013
  if (schema.isNullable) {
795
1014
  return `${target} += when (${input}) {
796
- is Instant -> "\\"\${timestampFormatter.format(${input})}\\""
797
- else -> "null"
798
- }`;
1015
+ is Instant -> "\\"\${timestampFormatter.format(${input})}\\""
1016
+ else -> "null"
1017
+ }`;
799
1018
  }
800
1019
  return `${target} += "\\"\${timestampFormatter.format(${input})}\\""`;
801
1020
  },
802
1021
  toQueryString(input, target, key) {
803
- if (context.isOptional) {
804
- return `if (${input} != null) {
805
- ${target}.add(
806
- "${key}=\${
807
- timestampFormatter.format(${input})
808
- }"
809
- )
810
- }`;
811
- }
812
- if (schema.isNullable) {
813
- return `${target}.add(
814
- "${key}=\${
815
- when (${input}) {
816
- is Instant -> timestampFormatter.format(${input})
817
- else -> "null"
818
- }
819
- }"
820
- )`;
821
- }
822
- return `${target}.add(
823
- "${key}=\${
824
- timestampFormatter.format(${input})
825
- }"
826
- )`;
1022
+ return kotlinEncodedQueryString(
1023
+ schema,
1024
+ context,
1025
+ input,
1026
+ target,
1027
+ key,
1028
+ (value) => `timestampFormatter.format(${value})`
1029
+ );
827
1030
  },
828
1031
  content: ""
829
1032
  };
@@ -839,14 +1042,14 @@ function kotlinFloat32FromSchema(schema, context) {
839
1042
  fromJson(input) {
840
1043
  if (nullable) {
841
1044
  return `when (${input}) {
842
- is JsonPrimitive -> ${input}!!.jsonPrimitive.floatOrNull
843
- else -> null
844
- }`;
1045
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.floatOrNull
1046
+ else -> null
1047
+ }`;
845
1048
  }
846
1049
  return `when (${input}) {
847
- is JsonPrimitive -> ${input}!!.jsonPrimitive.floatOrNull ?: ${defaultValue}
848
- else -> ${defaultValue}
849
- }`;
1050
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.floatOrNull ?: ${defaultValue}
1051
+ else -> ${defaultValue}
1052
+ }`;
850
1053
  },
851
1054
  toJson(input, target) {
852
1055
  return defaultToJsonString(context, input, target);
@@ -868,14 +1071,14 @@ function kotlinFloat64FromSchema(schema, context) {
868
1071
  fromJson(input) {
869
1072
  if (nullable) {
870
1073
  return `when (${input}) {
871
- is JsonPrimitive -> ${input}!!.jsonPrimitive.doubleOrNull
872
- else -> null
873
- }`;
1074
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.doubleOrNull
1075
+ else -> null
1076
+ }`;
874
1077
  }
875
1078
  return `when (${input}) {
876
- is JsonPrimitive -> ${input}!!.jsonPrimitive.doubleOrNull ?: 0.0
877
- else -> 0.0
878
- }`;
1079
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.doubleOrNull ?: 0.0
1080
+ else -> 0.0
1081
+ }`;
879
1082
  },
880
1083
  toJson(input, target) {
881
1084
  return defaultToJsonString(context, input, target);
@@ -897,14 +1100,14 @@ function kotlinInt8FromSchema(schema, context) {
897
1100
  fromJson(input) {
898
1101
  if (nullable) {
899
1102
  return `when (${input}) {
900
- is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toByteOrNull()
901
- else -> null
902
- }`;
1103
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toByteOrNull()
1104
+ else -> null
1105
+ }`;
903
1106
  }
904
1107
  return `when (${input}) {
905
- is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toByteOrNull() ?: 0
906
- else -> 0
907
- }`;
1108
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toByteOrNull() ?: 0
1109
+ else -> 0
1110
+ }`;
908
1111
  },
909
1112
  toJson(input, target) {
910
1113
  return defaultToJsonString(context, input, target);
@@ -926,14 +1129,14 @@ function kotlinInt16FromSchema(schema, context) {
926
1129
  fromJson(input) {
927
1130
  if (nullable) {
928
1131
  return `when (${input}) {
929
- is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toShortOrNull()
930
- else -> null
931
- }`;
1132
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toShortOrNull()
1133
+ else -> null
1134
+ }`;
932
1135
  }
933
1136
  return `when (${input}) {
934
- is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toShortOrNull() ?: 0
935
- else -> 0
936
- }`;
1137
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toShortOrNull() ?: 0
1138
+ else -> 0
1139
+ }`;
937
1140
  },
938
1141
  toJson(input, target) {
939
1142
  return defaultToJsonString(context, input, target);
@@ -955,14 +1158,14 @@ function kotlinInt32FromSchema(schema, context) {
955
1158
  fromJson(input) {
956
1159
  if (nullable) {
957
1160
  return `when (${input}) {
958
- is JsonPrimitive -> ${input}!!.jsonPrimitive.intOrNull
959
- else -> null
960
- }`;
1161
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.intOrNull
1162
+ else -> null
1163
+ }`;
961
1164
  }
962
1165
  return `when (${input}) {
963
- is JsonPrimitive -> ${input}!!.jsonPrimitive.intOrNull ?: 0
964
- else -> 0
965
- }`;
1166
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.intOrNull ?: 0
1167
+ else -> 0
1168
+ }`;
966
1169
  },
967
1170
  toJson(input, target) {
968
1171
  return defaultToJsonString(context, input, target);
@@ -984,21 +1187,21 @@ function kotlinInt64FromSchema(schema, context) {
984
1187
  fromJson(input) {
985
1188
  if (nullable) {
986
1189
  return `when (${input}) {
987
- is JsonPrimitive -> ${input}!!.jsonPrimitive.longOrNull
988
- else -> null
989
- }`;
1190
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.longOrNull
1191
+ else -> null
1192
+ }`;
990
1193
  }
991
1194
  return `when (${input}) {
992
- is JsonPrimitive -> ${input}!!.jsonPrimitive.longOrNull ?: 0L
993
- else -> 0L
994
- }`;
1195
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.longOrNull ?: 0L
1196
+ else -> 0L
1197
+ }`;
995
1198
  },
996
1199
  toJson(input, target) {
997
1200
  if (schema.isNullable) {
998
1201
  return `${target} += when (${input}) {
999
- is Long -> "\\"\${${input}}\\""
1000
- else -> "null"
1001
- }`;
1202
+ is Long -> "\\"\${${input}}\\""
1203
+ else -> "null"
1204
+ }`;
1002
1205
  }
1003
1206
  return `${target} += "\\"\${${input}}\\""`;
1004
1207
  },
@@ -1019,14 +1222,14 @@ function kotlinUint8FromSchema(schema, context) {
1019
1222
  fromJson(input) {
1020
1223
  if (nullable) {
1021
1224
  return `when (${input}) {
1022
- is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toUByteOrNull()
1023
- else -> null
1024
- }`;
1225
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toUByteOrNull()
1226
+ else -> null
1227
+ }`;
1025
1228
  }
1026
1229
  return `when (${input}) {
1027
- is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toUByteOrNull() ?: 0u
1028
- else -> 0u
1029
- }`;
1230
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toUByteOrNull() ?: 0u
1231
+ else -> 0u
1232
+ }`;
1030
1233
  },
1031
1234
  toJson(input, target) {
1032
1235
  return defaultToJsonString(context, input, target);
@@ -1048,14 +1251,14 @@ function kotlinUint16FromSchema(schema, context) {
1048
1251
  fromJson(input) {
1049
1252
  if (nullable) {
1050
1253
  return `when (${input}) {
1051
- is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toUShortOrNull()
1052
- else -> null
1053
- }`;
1254
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toUShortOrNull()
1255
+ else -> null
1256
+ }`;
1054
1257
  }
1055
1258
  return `when (${input}) {
1056
- is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toUShortOrNull() ?: 0u
1057
- else -> 0u
1058
- }`;
1259
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toUShortOrNull() ?: 0u
1260
+ else -> 0u
1261
+ }`;
1059
1262
  },
1060
1263
  toJson(input, target) {
1061
1264
  return defaultToJsonString(context, input, target);
@@ -1077,14 +1280,14 @@ function kotlinUint32FromSchema(schema, context) {
1077
1280
  fromJson(input) {
1078
1281
  if (nullable) {
1079
1282
  return `when (${input}) {
1080
- is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toUIntOrNull()
1081
- else -> null
1082
- }`;
1283
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toUIntOrNull()
1284
+ else -> null
1285
+ }`;
1083
1286
  }
1084
1287
  return `when (${input}) {
1085
- is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toUIntOrNull() ?: 0u
1086
- else -> 0u
1087
- }`;
1288
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toUIntOrNull() ?: 0u
1289
+ else -> 0u
1290
+ }`;
1088
1291
  },
1089
1292
  toJson(input, target) {
1090
1293
  return defaultToJsonString(context, input, target);
@@ -1106,21 +1309,21 @@ function kotlinUint64FromSchema(schema, context) {
1106
1309
  fromJson(input) {
1107
1310
  if (nullable) {
1108
1311
  return `when (${input}) {
1109
- is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toULongOrNull()
1110
- else -> null
1111
- }`;
1312
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toULongOrNull()
1313
+ else -> null
1314
+ }`;
1112
1315
  }
1113
1316
  return `when (${input}) {
1114
- is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toULongOrNull() ?: 0UL
1115
- else -> 0UL
1116
- }`;
1317
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toULongOrNull() ?: 0UL
1318
+ else -> 0UL
1319
+ }`;
1117
1320
  },
1118
1321
  toJson(input, target) {
1119
1322
  if (schema.isNullable) {
1120
1323
  return `${target} += when (${input}) {
1121
- is ULong -> "\\"\${${input}}\\""
1122
- else -> "null"
1123
- }`;
1324
+ is ULong -> "\\"\${${input}}\\""
1325
+ else -> "null"
1326
+ }`;
1124
1327
  }
1125
1328
  return `${target} += "\\"\${${input}}\\""`;
1126
1329
  },
@@ -1158,37 +1361,37 @@ function kotlinHttpRpcFromSchema(schema, context) {
1158
1361
  );
1159
1362
  if (schema.isEventStream) {
1160
1363
  return `${codeComment}suspend fun ${name}(
1161
- ${params ? `params: ${params},` : ""}
1162
- lastEventId: String? = null,
1163
- bufferCapacity: Int = 1024 * 1024,
1164
- onOpen: ((response: HttpResponse) -> Unit) = {},
1165
- onClose: (() -> Unit) = {},
1166
- onRequestError: ((error: Exception) -> Unit) = {},
1167
- onResponseError: ((error: ${context.clientName}Error) -> Unit) = {},
1168
- onData: ((${response ? `data: ${response}` : ""}) -> Unit) = {},
1169
- maxBackoffTime: Long? = null,
1170
- ): Unit {
1171
- __handleSseRequest(
1172
- httpClient = httpClient,
1173
- url = "$baseUrl${schema.path}",
1174
- method = HttpMethod.${pascalCase(schema.method, { normalize: true })},
1175
- params = ${params ? "params" : "null"},
1176
- headers = headers,
1177
- backoffTime = 0,
1178
- maxBackoffTime = maxBackoffTime ?: 30000L,
1179
- lastEventId = lastEventId,
1180
- bufferCapacity = bufferCapacity,
1181
- onOpen = onOpen,
1182
- onClose = onClose,
1183
- onError = onError,
1184
- onRequestError = onRequestError,
1185
- onResponseError = onResponseError,
1186
- onData = { str ->
1187
- ${response ? `val data = ${response}.fromJson(str)` : ""}
1188
- onData(${response ? "data" : ""})
1189
- }
1190
- )
1191
- }`;
1364
+ ${params ? `params: ${params},
1365
+ ` : ""}lastEventId: String? = null,
1366
+ bufferCapacity: Int = 1024 * 1024,
1367
+ onOpen: ((response: HttpResponse) -> Unit) = {},
1368
+ onClose: (() -> Unit) = {},
1369
+ onRequestError: ((error: Exception) -> Unit) = {},
1370
+ onResponseError: ((error: ${context.clientName}Error) -> Unit) = {},
1371
+ onData: ((${response ? `data: ${response}` : ""}) -> Unit) = {},
1372
+ maxBackoffTime: Long? = null,
1373
+ ): Unit {
1374
+ __handleSseRequest(
1375
+ httpClient = httpClient,
1376
+ url = "$baseUrl${schema.path}",
1377
+ method = HttpMethod.${pascalCase(schema.method, { normalize: true })},
1378
+ params = ${params ? "params" : "null"},
1379
+ headers = headers,
1380
+ backoffTime = 0,
1381
+ maxBackoffTime = maxBackoffTime ?: 30000L,
1382
+ lastEventId = lastEventId,
1383
+ bufferCapacity = bufferCapacity,
1384
+ onOpen = onOpen,
1385
+ onClose = onClose,
1386
+ onError = onError,
1387
+ onRequestError = onRequestError,
1388
+ onResponseError = onResponseError,
1389
+ onData = { str ->
1390
+ ${response ? `val data = ${response}.fromJson(str)
1391
+ ` : ""}onData(${response ? "data" : ""})
1392
+ }
1393
+ )
1394
+ }`;
1192
1395
  }
1193
1396
  const headingCheck = `if (response.headers["Content-Type"] != "application/json") {
1194
1397
  throw ${context.clientName}Error(
@@ -1197,26 +1400,26 @@ function kotlinHttpRpcFromSchema(schema, context) {
1197
1400
  data = JsonPrimitive(response.bodyAsText()),
1198
1401
  stack = null,
1199
1402
  )
1200
- }`;
1403
+ }
1404
+ `;
1201
1405
  return `${codeComment}suspend fun ${name}(${params ? `params: ${params}` : ""}): ${response ?? "Unit"} {
1202
- try {
1203
- val response = __prepareRequest(
1204
- client = httpClient,
1205
- url = "$baseUrl${schema.path}",
1206
- method = HttpMethod.${pascalCase(schema.method, { normalize: true })},
1207
- params = ${params ? "params" : null},
1208
- headers = headers?.invoke(),
1209
- ).execute()
1210
- ${response ? headingCheck : ""}
1211
- if (response.status.value in 200..299) {
1212
- return ${response ? `${response}.fromJson(response.bodyAsText())` : ""}
1213
- }
1214
- throw ${context.clientName}Error.fromJson(response.bodyAsText())
1215
- } catch (e: Exception) {
1216
- onError(e)
1217
- throw e
1406
+ try {
1407
+ val response = __prepareRequest(
1408
+ client = httpClient,
1409
+ url = "$baseUrl${schema.path}",
1410
+ method = HttpMethod.${pascalCase(schema.method, { normalize: true })},
1411
+ params = ${params ? "params" : null},
1412
+ headers = headers?.invoke(),
1413
+ ).execute()
1414
+ ${response ? headingCheck : ""}if (response.status.value in 200..299) {
1415
+ return${response ? ` ${response}.fromJson(response.bodyAsText())` : ""}
1218
1416
  }
1219
- }`;
1417
+ throw ${context.clientName}Error.fromJson(response.bodyAsText())
1418
+ } catch (e: Exception) {
1419
+ onError(e)
1420
+ throw e
1421
+ }
1422
+ }`;
1220
1423
  }
1221
1424
  function kotlinWsRpcFromSchema(_schema, _context) {
1222
1425
  return "";
@@ -1233,12 +1436,9 @@ function kotlinServiceFromSchema(schema, context) {
1233
1436
  ...context,
1234
1437
  instancePath: `${context.instancePath}.${key}`
1235
1438
  });
1236
- procedureParts.push(`val ${kotlinKey}: ${subService.name} = ${subService.name}(
1237
- httpClient = httpClient,
1238
- baseUrl = baseUrl,
1239
- headers = headers,
1240
- onError = onError,
1241
- )`);
1439
+ procedureParts.push(
1440
+ kotlinSubServiceField(kotlinKey, subService.name)
1441
+ );
1242
1442
  if (subService.content) {
1243
1443
  subServiceParts.push(subService.content);
1244
1444
  }
@@ -1263,12 +1463,20 @@ function kotlinServiceFromSchema(schema, context) {
1263
1463
  private val headers: __${context.clientName}HeadersFn,
1264
1464
  private val onError: ((err: Exception) -> Unit) = {},
1265
1465
  ) {
1266
- ${procedureParts.join("\n\n ")}
1267
- }
1466
+ ${indentTail(procedureParts.join("\n\n"), 4)}
1467
+ }${subServiceParts.length ? `
1268
1468
 
1269
- ${subServiceParts.join("\n\n")}`
1469
+ ${subServiceParts.join("\n\n")}` : ""}`
1270
1470
  };
1271
1471
  }
1472
+ function kotlinSubServiceField(key, serviceName) {
1473
+ return `val ${key}: ${serviceName} = ${serviceName}(
1474
+ httpClient = httpClient,
1475
+ baseUrl = baseUrl,
1476
+ headers = headers,
1477
+ onError = onError,
1478
+ )`;
1479
+ }
1272
1480
  function getProcedureName(context) {
1273
1481
  const name = context.instancePath.split(".").pop() ?? "";
1274
1482
  return kotlinIdentifier(name);
@@ -1290,12 +1498,13 @@ function kotlinRefFromSchema(schema, context) {
1290
1498
  defaultValue,
1291
1499
  fromJson(input, key) {
1292
1500
  return `when (${input}) {
1293
- is JsonObject -> ${prefixedTypeName}.fromJsonElement(
1294
- ${input}!!,
1295
- "$instancePath/${key}",
1296
- )
1297
- else -> ${defaultValue}
1298
- }`;
1501
+ is JsonObject -> ${prefixedTypeName}.fromJsonElement(
1502
+ ${input}!!,
1503
+ "$instancePath/${key}",
1504
+ )
1505
+
1506
+ else -> ${defaultValue}
1507
+ }`;
1299
1508
  },
1300
1509
  toJson(input, target) {
1301
1510
  if (schema.isNullable) {
@@ -1357,12 +1566,9 @@ function kotlinClientFromAppDefinition(def, options) {
1357
1566
  ...context,
1358
1567
  instancePath: `${key}`
1359
1568
  });
1360
- procedureParts.push(`val ${kotlinKey}: ${subService.name} = ${subService.name}(
1361
- httpClient = httpClient,
1362
- baseUrl = baseUrl,
1363
- headers = headers,
1364
- onError = onError,
1365
- )`);
1569
+ procedureParts.push(
1570
+ kotlinSubServiceField(kotlinKey, subService.name)
1571
+ );
1366
1572
  if (subService.content) {
1367
1573
  subServiceParts.push(subService.content);
1368
1574
  }
@@ -1395,7 +1601,7 @@ class ${clientName}(
1395
1601
  private val headers: __${clientName}HeadersFn,
1396
1602
  private val onError: ((err: Exception) -> Unit) = {},
1397
1603
  ) {
1398
- ${procedureParts.join("\n\n ")}
1604
+ ${indentTail(procedureParts.join("\n\n"), 4)}
1399
1605
  }
1400
1606
 
1401
1607
  ${subServiceParts.join("\n\n")}
@@ -1455,6 +1661,9 @@ function kotlinTypeFromSchema(schema, context) {
1455
1661
  if (isSchemaFormDiscriminator(schema)) {
1456
1662
  return kotlinDiscriminatorFromSchema(schema, context);
1457
1663
  }
1664
+ if (isSchemaFormUnion(schema)) {
1665
+ return kotlinUnionFromSchema(schema, context);
1666
+ }
1458
1667
  if (isSchemaFormRef(schema)) {
1459
1668
  return kotlinRefFromSchema(schema, context);
1460
1669
  }
@@ -1633,6 +1842,13 @@ private fun __logError(string: String) {
1633
1842
  System.err.println(string)
1634
1843
  }
1635
1844
 
1845
+ /**
1846
+ * URL encodes a query param value. Null values are serialized as "null".
1847
+ */
1848
+ private fun __encodeQueryValue(value: String?): String {
1849
+ return value?.encodeURLParameter(spaceToPlus = true) ?: "null"
1850
+ }
1851
+
1636
1852
  private suspend fun __prepareRequest(
1637
1853
  client: HttpClient,
1638
1854
  url: String,
@@ -1800,7 +2016,7 @@ private suspend fun __handleSseRequest(
1800
2016
  if (httpResponse.status.value !in 200..299) {
1801
2017
  try {
1802
2018
  if (httpResponse.headers["Content-Type"] == "application/json") {
1803
- val err = ${clientName}Error.fromJson(httpResponse.bodyAsText())
2019
+ val err = ${clientName}Error.fromJson(httpResponse.bodyAsText())
1804
2020
  onError(err)
1805
2021
  onResponseError(err)
1806
2022
  } else {
@@ -1869,11 +2085,23 @@ private suspend fun __handleSseRequest(
1869
2085
  )
1870
2086
  }
1871
2087
  newBackoffTime = 0
2088
+ val heartbeatIntervalMs = httpResponse.headers["heartbeat-interval"]?.toLongOrNull() ?: 0L
1872
2089
  val channel: ByteReadChannel = httpResponse.body()
1873
2090
  var pendingData = ""
1874
2091
  while (!channel.isClosedForRead) {
1875
2092
  val buffer = ByteBuffer.allocateDirect(bufferCapacity)
1876
- val read = channel.readAvailable(buffer)
2093
+ val read = if (heartbeatIntervalMs > 0L) {
2094
+ withTimeoutOrNull(heartbeatIntervalMs * 2L) {
2095
+ channel.readAvailable(buffer)
2096
+ }
2097
+ } else {
2098
+ channel.readAvailable(buffer)
2099
+ }
2100
+ if (read == null) {
2101
+ // no data or heartbeat was received in time so assume the connection is dead and reconnect
2102
+ httpResponse.cancel()
2103
+ break
2104
+ }
1877
2105
  if (read == -1) break
1878
2106
  buffer.flip()
1879
2107
  val input = Charsets.UTF_8.decode(buffer).toString()
@@ -1981,6 +2209,7 @@ import io.ktor.utils.io.*
1981
2209
  import kotlinx.coroutines.cancel
1982
2210
  import kotlinx.coroutines.currentCoroutineContext
1983
2211
  import kotlinx.coroutines.withContext
2212
+ import kotlinx.coroutines.withTimeoutOrNull
1984
2213
  import kotlinx.serialization.encodeToString
1985
2214
  import kotlinx.serialization.json.*
1986
2215
  import java.nio.ByteBuffer