@arrirpc/codegen-kotlin 0.84.1 → 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.cjs CHANGED
@@ -104,11 +104,12 @@ function isNullable(schema, context) {
104
104
  }
105
105
  function getCodeComment(metadata, prefix, valueField) {
106
106
  if (!metadata?.description && !metadata?.isDeprecated) return "";
107
- const descriptionPart = metadata.description?.split("\n").map((line) => `${prefix ?? ""}* ${line}`).join("\n");
108
- const finalDescription = metadata.description ? `${prefix ?? ""}/**
109
- ${descriptionPart}${prefix ?? ""}
110
- */` : "";
111
- const deprecationMessage = `@Deprecated(message = "This ${valueField ?? "item"} was marked as deprecated by the server")`;
107
+ const indent = prefix ?? "";
108
+ const descriptionPart = metadata.description?.split("\n").map((line) => `${indent} * ${line}`.trimEnd()).join("\n");
109
+ const finalDescription = metadata.description ? `${indent}/**
110
+ ${descriptionPart}
111
+ ${indent} */` : "";
112
+ const deprecationMessage = `${indent}@Deprecated(message = "This ${valueField ?? "item"} was marked as deprecated by the server")`;
112
113
  if (metadata.description && metadata.isDeprecated) {
113
114
  return `${finalDescription}
114
115
  ${deprecationMessage}
@@ -124,6 +125,31 @@ ${deprecationMessage}
124
125
  }
125
126
  return "";
126
127
  }
128
+ function indentTail(input, spaces) {
129
+ const padding = " ".repeat(spaces);
130
+ return input.split("\n").map(
131
+ (line, i) => i === 0 || line.length === 0 ? line : `${padding}${line}`
132
+ ).join("\n");
133
+ }
134
+ function kotlinEncodedQueryString(schema, context, input, target, key, toValue) {
135
+ const queryKey = encodeURIComponent(key);
136
+ if (context.isOptional) {
137
+ return `if (${input} != null) {
138
+ ${target}.add("${queryKey}=\${__encodeQueryValue(${toValue(input)})}")
139
+ }`;
140
+ }
141
+ if (schema.isNullable) {
142
+ const value = toValue("it");
143
+ let nullableValue = `${input}?.let { ${value} }`;
144
+ if (value === "it") {
145
+ nullableValue = input;
146
+ } else if (value.startsWith("it.")) {
147
+ nullableValue = `${input}?.${value.slice(3)}`;
148
+ }
149
+ return `${target}.add("${queryKey}=\${__encodeQueryValue(${nullableValue})}")`;
150
+ }
151
+ return `${target}.add("${queryKey}=\${__encodeQueryValue(${toValue(input)})}")`;
152
+ }
127
153
 
128
154
  function kotlinAnyFromSchema(schema, context) {
129
155
  const nullable = isNullable(schema, context);
@@ -136,28 +162,28 @@ function kotlinAnyFromSchema(schema, context) {
136
162
  fromJson(input) {
137
163
  if (context.isOptional) {
138
164
  return `when (${input}) {
139
- null -> null
140
- else -> ${input}
141
- }`;
165
+ null -> null
166
+ else -> ${input}
167
+ }`;
142
168
  }
143
169
  if (schema.isNullable) {
144
170
  return `when (${input}) {
145
- JsonNull -> null
146
- null -> null
147
- else -> ${input}
148
- }`;
171
+ JsonNull -> null
172
+ null -> null
173
+ else -> ${input}
174
+ }`;
149
175
  }
150
176
  return `when (${input}) {
151
- is JsonElement -> ${input}!!
152
- else -> JsonNull
153
- }`;
177
+ is JsonElement -> ${input}!!
178
+ else -> JsonNull
179
+ }`;
154
180
  },
155
181
  toJson(input, target) {
156
182
  if (schema.isNullable) {
157
183
  return `${target} += when (${input}) {
158
- null -> "null"
159
- else -> JsonInstance.encodeToString(${input})
160
- }`;
184
+ null -> "null"
185
+ else -> JsonInstance.encodeToString(${input})
186
+ }`;
161
187
  }
162
188
  return `${target} += JsonInstance.encodeToString(${input})`;
163
189
  },
@@ -186,58 +212,47 @@ function kotlinArrayFromSchema(schema, context) {
186
212
  isNullable: nullable,
187
213
  defaultValue,
188
214
  fromJson(input) {
189
- if (nullable) {
190
- return `when (${input}) {
191
- is JsonArray -> {
192
- val __value: ${typeName} = mutableListOf()
193
- for (__element in ${input}!!.jsonArray) {
194
- __value.add(
195
- ${subType.fromJson("__element")}
196
- )
197
- }
198
- __value
199
- }
200
-
201
- else -> null
202
- }`;
203
- }
204
215
  return `when (${input}) {
205
- is JsonArray -> {
206
- val __value: ${typeName} = mutableListOf()
207
- for (__element in ${input}!!.jsonArray) {
208
- __value.add(
209
- ${subType.fromJson("__element")}
210
- )
211
- }
212
- __value
213
- }
216
+ is JsonArray -> {
217
+ val __value: ${typeName} = mutableListOf()
218
+ for (__element in ${input}!!.jsonArray) {
219
+ __value.add(
220
+ ${indentTail(subType.fromJson("__element"), 16)}
221
+ )
222
+ }
223
+ __value
224
+ }
214
225
 
215
- else -> mutableListOf()
216
- }`;
226
+ else -> ${defaultValue}
227
+ }`;
217
228
  },
218
229
  toJson(input, target) {
230
+ const elementToJson = indentTail(
231
+ subType.toJson("__element", target),
232
+ 4
233
+ );
219
234
  if (schema.isNullable) {
220
235
  return `if (${input} == null) {
221
- ${target} += "null"
222
- } else {
223
- ${target} += "["
224
- for ((__index, __element) in ${input}.withIndex()) {
225
- if (__index != 0) {
226
- ${target} += ","
227
- }
228
- ${subType.toJson("__element", target)}
229
- }
230
- ${target} += "]"
231
- }`;
236
+ ${target} += "null"
237
+ } else {
238
+ ${target} += "["
239
+ for ((__index, __element) in ${input}.withIndex()) {
240
+ if (__index != 0) {
241
+ ${target} += ","
242
+ }
243
+ ${indentTail(elementToJson, 4)}
244
+ }
245
+ ${target} += "]"
246
+ }`;
232
247
  }
233
248
  return `${target} += "["
234
- for ((__index, __element) in ${input}.withIndex()) {
235
- if (__index != 0) {
236
- ${target} += ","
237
- }
238
- ${subType.toJson("__element", target)}
239
- }
240
- ${target} += "]"`;
249
+ for ((__index, __element) in ${input}.withIndex()) {
250
+ if (__index != 0) {
251
+ ${target} += ","
252
+ }
253
+ ${elementToJson}
254
+ }
255
+ ${target} += "]"`;
241
256
  },
242
257
  toQueryString() {
243
258
  return `__logError("[WARNING] arrays cannot be serialized to query params. Skipping field at ${context.instancePath}.")`;
@@ -257,23 +272,14 @@ function kotlinObjectFromSchema(schema, context) {
257
272
  isNullable: nullable,
258
273
  defaultValue,
259
274
  fromJson(input, key) {
260
- if (nullable) {
261
- return `when (${input}) {
262
- is JsonObject -> ${prefixedClassName}.fromJsonElement(
263
- ${input}!!,
264
- "$instancePath/${key}",
265
- )
266
- else -> null
267
- }`;
268
- }
269
275
  return `when (${input}) {
270
- is JsonObject -> ${prefixedClassName}.fromJsonElement(
271
- ${input}!!,
272
- "$instancePath/${key}",
273
- )
276
+ is JsonObject -> ${prefixedClassName}.fromJsonElement(
277
+ ${input}!!,
278
+ "$instancePath/${key}",
279
+ )
274
280
 
275
- else -> ${prefixedClassName}.new()
276
- }`;
281
+ else -> ${defaultValue}
282
+ }`;
277
283
  },
278
284
  toJson(input, target) {
279
285
  if (schema.isNullable) {
@@ -307,7 +313,7 @@ function kotlinObjectFromSchema(schema, context) {
307
313
  `output += "\\"${context.discriminatorKey}\\":\\"${context.discriminatorValue}\\""`
308
314
  );
309
315
  toQueryParts.push(
310
- `queryParts.add("${context.discriminatorKey}=${context.discriminatorValue}")`
316
+ `queryParts.add("${encodeURIComponent(context.discriminatorKey)}=${encodeURIComponent(context.discriminatorValue)}")`
311
317
  );
312
318
  }
313
319
  for (let i = 0; i < requiredKeys.length; i++) {
@@ -339,9 +345,7 @@ function kotlinObjectFromSchema(schema, context) {
339
345
  fromJsonParts.push(
340
346
  `val ${kotlinKey}: ${type.prefixedTypeName}${type.isNullable ? "?" : ""} = ${type.fromJson(`__input.jsonObject["${key}"]`, key)}`
341
347
  );
342
- defaultParts.push(
343
- ` ${kotlinKey} = ${type.defaultValue},`
344
- );
348
+ defaultParts.push(`${kotlinKey} = ${type.defaultValue}`);
345
349
  }
346
350
  for (let i = 0; i < optionalKeys.length; i++) {
347
351
  const isFirst = i === 0 && requiredKeys.length === 0 && !context.discriminatorKey;
@@ -361,24 +365,25 @@ function kotlinObjectFromSchema(schema, context) {
361
365
  if (type.content) {
362
366
  subContent.push(type.content);
363
367
  }
364
- const addCommaPart = isFirst ? "" : `
365
- if (hasProperties) output += ","
366
- `;
367
368
  fieldParts.push(
368
369
  `${getCodeComment(schema.optionalProperties[key].metadata, " ", "field")} val ${kotlinKey}: ${type.prefixedTypeName}? = null,`
369
370
  );
371
+ const optionalToJsonParts = [];
370
372
  if (hasKnownKeys) {
371
- toJsonParts.push(`if (${kotlinKey} != null) {
372
- output += ",\\"${key}\\":"
373
- ${type.toJson(kotlinKey, "output")}
374
- }`);
373
+ optionalToJsonParts.push(`output += ",\\"${key}\\":"`);
375
374
  } else {
376
- toJsonParts.push(`if (${kotlinKey} != null) {${addCommaPart}
377
- output += "\\"${key}\\":"
378
- ${type.toJson(kotlinKey, "output")}
379
- ${isLast ? "" : " hasProperties = true"}
380
- }`);
375
+ if (!isFirst) {
376
+ optionalToJsonParts.push(`if (hasProperties) output += ","`);
377
+ }
378
+ optionalToJsonParts.push(`output += "\\"${key}\\":"`);
379
+ }
380
+ optionalToJsonParts.push(type.toJson(kotlinKey, "output"));
381
+ if (!hasKnownKeys && !isLast) {
382
+ optionalToJsonParts.push("hasProperties = true");
381
383
  }
384
+ toJsonParts.push(`if (${kotlinKey} != null) {
385
+ ${indentTail(optionalToJsonParts.join("\n"), 4)}
386
+ }`);
382
387
  toQueryParts.push(type.toQueryString(kotlinKey, "queryParts", key));
383
388
  fromJsonParts.push(
384
389
  `val ${kotlinKey}: ${type.prefixedTypeName}? = ${type.fromJson(`__input.jsonObject["${key}"]`, key)}`
@@ -399,19 +404,17 @@ ${isLast ? "" : " hasProperties = true"}
399
404
  ${fieldParts.join("\n")}${!hasProperties ? " private val placeholderKey: Short = 0" : ""}
400
405
  ) : ${implementedClass} {${discriminatorField}
401
406
  override fun toJson(): String {
402
- ${toJsonParts.join("\n")}
407
+ ${indentTail(toJsonParts.join("\n"), 8)}
403
408
  }
404
409
 
405
410
  override fun toUrlQueryParams(): String {
406
- ${toQueryParts.join("\n")}
411
+ ${indentTail(toQueryParts.join("\n"), 8)}
407
412
  }
408
413
 
409
414
  companion object Factory : ${context.clientName}ModelFactory<${prefixedClassName}> {
410
415
  @JvmStatic
411
416
  override fun new(): ${prefixedClassName} {
412
- return ${prefixedClassName}(
413
- ${defaultParts.join("\n")}
414
- )
417
+ ${indentTail(constructorCall(prefixedClassName, defaultParts), 12)}
415
418
  }
416
419
 
417
420
  @JvmStatic
@@ -425,39 +428,63 @@ ${defaultParts.join("\n")}
425
428
  __logError("[WARNING] ${prefixedClassName}.fromJsonElement() expected kotlinx.serialization.json.JsonObject at $instancePath. Got \${__input.javaClass}. Initializing empty ${prefixedClassName}.")
426
429
  return new()
427
430
  }
428
- ${fromJsonParts.join("\n")}
429
- return ${prefixedClassName}(
430
- ${kotlinKeys.join(",\n ")}${hasProperties ? `,` : ""}
431
- )
431
+ ${indentTail([...fromJsonParts, constructorCall(prefixedClassName, kotlinKeys)].join("\n"), 12)}
432
432
  }
433
433
  }
434
- }
434
+ }${subContent.length ? `
435
435
 
436
- ${subContent.join("\n\n")}`;
436
+ ${subContent.join("\n\n")}` : ""}`;
437
437
  context.existingTypeIds.push(className);
438
438
  return {
439
439
  ...result,
440
440
  content
441
441
  };
442
442
  }
443
+ function constructorCall(className, args) {
444
+ if (args.length === 0) {
445
+ return `return ${className}()`;
446
+ }
447
+ return `return ${className}(
448
+ ${args.join(",\n ")},
449
+ )`;
450
+ }
443
451
 
444
- function kotlinDiscriminatorFromSchema(schema, context) {
445
- const kotlinDiscriminatorKey = kotlinIdentifier(schema.discriminator);
452
+ function kotlinUnionFromSchema(schema, context) {
453
+ if (schema.tagKey && !schema.valueKey) {
454
+ for (const key of Object.keys(schema.union)) {
455
+ if (!codegenUtils.isSchemaFormProperties(schema.union[key])) {
456
+ throw new Error(
457
+ `Error at ${context.schemaPath}/union/${key}: All union variants must be an object when tagKey is specified without a valueKey`
458
+ );
459
+ }
460
+ }
461
+ return kotlinInternallyTaggedSealedInterface(
462
+ schema,
463
+ schema.tagKey,
464
+ schema.union,
465
+ "union",
466
+ context
467
+ );
468
+ }
469
+ return kotlinWrappedUnionFromSchema(schema, context);
470
+ }
471
+ function kotlinInternallyTaggedSealedInterface(schema, tagKey, variants, variantsSchemaKey, context) {
472
+ const kotlinDiscriminatorKey = kotlinIdentifier(tagKey);
446
473
  const className = getClassName(schema, context);
447
474
  const prefixedClassName = `${context.typePrefix}${className}`;
448
475
  const nullable = isNullable(schema, context);
449
476
  const subTypes = [];
450
477
  const subContent = [];
451
- for (const key of Object.keys(schema.mapping)) {
452
- const subSchema = schema.mapping[key];
478
+ for (const key of Object.keys(variants)) {
479
+ const subSchema = variants[key];
453
480
  const subType = kotlinObjectFromSchema(subSchema, {
454
481
  typePrefix: context.typePrefix,
455
482
  clientName: context.clientName,
456
483
  clientVersion: context.clientVersion,
457
484
  instancePath: context.instancePath,
458
- schemaPath: `${context.schemaPath}/mapping/${key}`,
485
+ schemaPath: `${context.schemaPath}/${variantsSchemaKey}/${key}`,
459
486
  existingTypeIds: context.existingTypeIds,
460
- discriminatorKey: schema.discriminator,
487
+ discriminatorKey: tagKey,
461
488
  discriminatorValue: key,
462
489
  discriminatorParentId: className
463
490
  });
@@ -473,6 +500,10 @@ function kotlinDiscriminatorFromSchema(schema, context) {
473
500
  if (subTypes.length === 0) {
474
501
  throw new Error("Discriminator schemas must have at least one mapping");
475
502
  }
503
+ const fallbackKey = codegenUtils.getUnionFallbackKey(variants);
504
+ const fallbackType = subTypes.find(
505
+ (type) => type.discriminatorValue === fallbackKey
506
+ );
476
507
  const defaultValue = nullable ? "null" : `${prefixedClassName}.new()`;
477
508
  const result = {
478
509
  typeName: className,
@@ -481,12 +512,13 @@ function kotlinDiscriminatorFromSchema(schema, context) {
481
512
  defaultValue,
482
513
  fromJson(input, key) {
483
514
  return `when (${input}) {
484
- is JsonObject -> ${prefixedClassName}.fromJsonElement(
485
- ${input}!!,
486
- "$instancePath/${key}",
487
- )
488
- else -> ${defaultValue}
489
- }`;
515
+ is JsonObject -> ${prefixedClassName}.fromJsonElement(
516
+ ${input}!!,
517
+ "$instancePath/${key}",
518
+ )
519
+
520
+ else -> ${defaultValue}
521
+ }`;
490
522
  },
491
523
  toJson(input, target) {
492
524
  if (schema.isNullable) {
@@ -495,7 +527,7 @@ function kotlinDiscriminatorFromSchema(schema, context) {
495
527
  return `${target} += ${input}.toJson()`;
496
528
  },
497
529
  toQueryString() {
498
- return `__logError("[WARNING] nested objects cannot be serialized to query params. Skipping field at ${context.instancePath}.")`;
530
+ return `__logError("[WARNING] nested unions cannot be serialized to query params. Skipping field at ${context.instancePath}.")`;
499
531
  },
500
532
  content: ""
501
533
  };
@@ -509,7 +541,7 @@ function kotlinDiscriminatorFromSchema(schema, context) {
509
541
  companion object Factory : ${context.clientName}ModelFactory<${prefixedClassName}> {
510
542
  @JvmStatic
511
543
  override fun new(): ${prefixedClassName} {
512
- return ${subTypes[0].prefixedTypeName}.new()
544
+ return ${fallbackType.prefixedTypeName}.new()
513
545
  }
514
546
 
515
547
  @JvmStatic
@@ -520,12 +552,12 @@ function kotlinDiscriminatorFromSchema(schema, context) {
520
552
  @JvmStatic
521
553
  override fun fromJsonElement(__input: JsonElement, instancePath: String): ${prefixedClassName} {
522
554
  if (__input !is JsonObject) {
523
- __logError("[WARNING] Discriminator.fromJsonElement() expected kotlinx.serialization.json.JsonObject at $instancePath. Got \${__input.javaClass}. Initializing empty ${prefixedClassName}.")
555
+ __logError("[WARNING] ${prefixedClassName}.fromJsonElement() expected kotlinx.serialization.json.JsonObject at $instancePath. Got \${__input.javaClass}. Initializing empty ${prefixedClassName}.")
524
556
  return new()
525
557
  }
526
- return when (__input.jsonObject["${schema.discriminator}"]) {
527
- is JsonPrimitive -> when (__input.jsonObject["${schema.discriminator}"]!!.jsonPrimitive.contentOrNull) {
528
- ${subTypes.map((type) => `"${type.discriminatorValue}" -> ${type.prefixedTypeName}.fromJsonElement(__input, instancePath)`).join("\n")}
558
+ return when (__input.jsonObject["${tagKey}"]) {
559
+ is JsonPrimitive -> when (__input.jsonObject["${tagKey}"]!!.jsonPrimitive.contentOrNull) {
560
+ ${subTypes.map((type) => `"${type.discriminatorValue}" -> ${type.prefixedTypeName}.fromJsonElement(__input, instancePath)`).join("\n ")}
529
561
  else -> new()
530
562
  }
531
563
 
@@ -533,9 +565,176 @@ function kotlinDiscriminatorFromSchema(schema, context) {
533
565
  }
534
566
  }
535
567
  }
568
+ }${subContent.length ? `
569
+
570
+ ${subContent.join("\n\n")}` : ""}`;
571
+ context.existingTypeIds.push(className);
572
+ return {
573
+ ...result,
574
+ content
575
+ };
536
576
  }
577
+ function kotlinWrappedUnionFromSchema(schema, context) {
578
+ const className = getClassName(schema, context);
579
+ const prefixedClassName = `${context.typePrefix}${className}`;
580
+ const nullable = isNullable(schema, context);
581
+ const defaultValue = nullable ? "null" : `${prefixedClassName}.new()`;
582
+ const result = {
583
+ typeName: className,
584
+ prefixedTypeName: prefixedClassName,
585
+ isNullable: nullable,
586
+ defaultValue,
587
+ fromJson(input, key) {
588
+ return `when (${input}) {
589
+ is JsonObject -> ${prefixedClassName}.fromJsonElement(
590
+ ${input}!!,
591
+ "$instancePath/${key}",
592
+ )
537
593
 
538
- ${subContent.join("\n\n")}`;
594
+ else -> ${defaultValue}
595
+ }`;
596
+ },
597
+ toJson(input, target) {
598
+ if (schema.isNullable) {
599
+ return `${target} += ${input}?.toJson()`;
600
+ }
601
+ return `${target} += ${input}.toJson()`;
602
+ },
603
+ toQueryString() {
604
+ return `__logError("[WARNING] nested unions cannot be serialized to query params. Skipping field at ${context.instancePath}.")`;
605
+ },
606
+ content: ""
607
+ };
608
+ if (context.existingTypeIds.includes(className)) {
609
+ return result;
610
+ }
611
+ const keys = Object.keys(schema.union);
612
+ if (keys.length === 0) {
613
+ throw new Error(
614
+ `Error at ${context.schemaPath}: Union schemas must have at least one variant`
615
+ );
616
+ }
617
+ const tagKey = schema.tagKey;
618
+ const tagProp = tagKey ? kotlinIdentifier(tagKey) : void 0;
619
+ const valueKey = schema.valueKey ?? "value";
620
+ const valueProp = kotlinIdentifier(valueKey);
621
+ const variants = [];
622
+ const variantContent = [];
623
+ const subContent = [];
624
+ for (const key of keys) {
625
+ const subSchema = schema.union[key];
626
+ const variantClassName = `${context.typePrefix}${kotlinClassName(`${className}_${key}`)}`;
627
+ const valueType = kotlinTypeFromSchema(subSchema, {
628
+ typePrefix: context.typePrefix,
629
+ clientName: context.clientName,
630
+ clientVersion: context.clientVersion,
631
+ instancePath: `/${className}/${key}/${valueKey}`,
632
+ schemaPath: `${context.schemaPath}/union/${key}`,
633
+ existingTypeIds: context.existingTypeIds
634
+ });
635
+ if (valueType.content) {
636
+ subContent.push(valueType.content);
637
+ }
638
+ variants.push({ key, prefixedClassName: variantClassName });
639
+ const jsonValueKey = tagKey ? valueKey : key;
640
+ const valueTypeName = `${valueType.prefixedTypeName}${valueType.isNullable ? "?" : ""}`;
641
+ const tagField = tagProp ? `
642
+ override val ${tagProp} get() = "${key}"
643
+ ` : "";
644
+ const toJsonParts = tagProp ? [
645
+ `output += "\\"${tagKey}\\":\\"${key}\\""`,
646
+ `output += ",\\"${jsonValueKey}\\":"`
647
+ ] : [`output += "\\"${jsonValueKey}\\":"`];
648
+ toJsonParts.push(valueType.toJson(valueProp, "output"));
649
+ variantContent.push(`data class ${variantClassName}(
650
+ val ${valueProp}: ${valueTypeName},
651
+ ) : ${prefixedClassName} {${tagField}
652
+ override fun toJson(): String {
653
+ var output = "{"
654
+ ${indentTail(toJsonParts.join("\n"), 8)}
655
+ output += "}"
656
+ return output
657
+ }
658
+
659
+ override fun toUrlQueryParams(): String {
660
+ __logError("[WARNING] unions cannot be serialized to query params. Skipping ${variantClassName}.")
661
+ return ""
662
+ }
663
+
664
+ companion object Factory : ${context.clientName}ModelFactory<${variantClassName}> {
665
+ @JvmStatic
666
+ override fun new(): ${variantClassName} {
667
+ return ${variantClassName}(
668
+ ${valueProp} = ${valueType.defaultValue},
669
+ )
670
+ }
671
+
672
+ @JvmStatic
673
+ override fun fromJson(input: String): ${variantClassName} {
674
+ return fromJsonElement(JsonInstance.parseToJsonElement(input))
675
+ }
676
+
677
+ @JvmStatic
678
+ override fun fromJsonElement(__input: JsonElement, instancePath: String): ${variantClassName} {
679
+ if (__input !is JsonObject) {
680
+ __logError("[WARNING] ${variantClassName}.fromJsonElement() expected kotlinx.serialization.json.JsonObject at $instancePath. Got \${__input.javaClass}. Initializing empty ${variantClassName}.")
681
+ return new()
682
+ }
683
+ val ${valueProp}: ${valueTypeName} = ${indentTail(valueType.fromJson(`__input.jsonObject["${jsonValueKey}"]`, jsonValueKey), 12)}
684
+ return ${variantClassName}(
685
+ ${valueProp},
686
+ )
687
+ }
688
+ }
689
+ }`);
690
+ }
691
+ const fallbackKey = codegenUtils.getUnionFallbackKey(schema.union);
692
+ const fallbackVariant = variants.find(
693
+ (variant) => variant.key === fallbackKey
694
+ );
695
+ let fromJsonBody;
696
+ if (tagKey && tagProp) {
697
+ fromJsonBody = ` return when (__input.jsonObject["${tagKey}"]) {
698
+ is JsonPrimitive -> when (__input.jsonObject["${tagKey}"]!!.jsonPrimitive.contentOrNull) {
699
+ ${variants.map((variant) => `"${variant.key}" -> ${variant.prefixedClassName}.fromJsonElement(__input, instancePath)`).join("\n ")}
700
+ else -> new()
701
+ }
702
+
703
+ else -> new()
704
+ }`;
705
+ } else {
706
+ fromJsonBody = ` return when {
707
+ ${variants.map((variant) => `"${variant.key}" in __input -> ${variant.prefixedClassName}.fromJsonElement(__input, instancePath)`).join("\n ")}
708
+ else -> new()
709
+ }`;
710
+ }
711
+ const codeComment = getCodeComment(schema.metadata, "", "class");
712
+ const content = `${codeComment}sealed interface ${prefixedClassName} : ${context.clientName}Model {${tagProp ? `
713
+ val ${tagProp}: String
714
+ ` : ""}
715
+ companion object Factory : ${context.clientName}ModelFactory<${prefixedClassName}> {
716
+ @JvmStatic
717
+ override fun new(): ${prefixedClassName} {
718
+ return ${fallbackVariant.prefixedClassName}.new()
719
+ }
720
+
721
+ @JvmStatic
722
+ override fun fromJson(input: String): ${prefixedClassName} {
723
+ return fromJsonElement(JsonInstance.parseToJsonElement(input))
724
+ }
725
+
726
+ @JvmStatic
727
+ override fun fromJsonElement(__input: JsonElement, instancePath: String): ${prefixedClassName} {
728
+ if (__input !is JsonObject) {
729
+ __logError("[WARNING] ${prefixedClassName}.fromJsonElement() expected kotlinx.serialization.json.JsonObject at $instancePath. Got \${__input.javaClass}. Initializing empty ${prefixedClassName}.")
730
+ return new()
731
+ }
732
+ ${fromJsonBody}
733
+ }
734
+ }
735
+ }
736
+
737
+ ${[...variantContent, ...subContent].join("\n\n")}`;
539
738
  context.existingTypeIds.push(className);
540
739
  return {
541
740
  ...result,
@@ -543,6 +742,16 @@ ${subContent.join("\n\n")}`;
543
742
  };
544
743
  }
545
744
 
745
+ function kotlinDiscriminatorFromSchema(schema, context) {
746
+ return kotlinInternallyTaggedSealedInterface(
747
+ schema,
748
+ schema.discriminator,
749
+ schema.mapping,
750
+ "mapping",
751
+ context
752
+ );
753
+ }
754
+
546
755
  function kotlinEnumFromSchema(schema, context) {
547
756
  const nullable = isNullable(schema, context);
548
757
  const className = getClassName(schema, context);
@@ -563,11 +772,12 @@ function kotlinEnumFromSchema(schema, context) {
563
772
  if (!context.existingTypeIds.includes(className)) {
564
773
  content = `enum class ${prefixedClassName} {
565
774
  ${enumItems.map((item) => item.name).join(",\n ")};
775
+
566
776
  val serialValue: String
567
777
  get() = when (this) {
568
778
  ${enumItems.map((item) => `${item.name} -> "${item.value}"`).join("\n ")}
569
779
  }
570
-
780
+
571
781
  companion object Factory : ${context.clientName}ModelFactory<${prefixedClassName}> {
572
782
  @JvmStatic
573
783
  override fun new(): ${prefixedClassName} {
@@ -603,38 +813,30 @@ function kotlinEnumFromSchema(schema, context) {
603
813
  isNullable: nullable,
604
814
  defaultValue,
605
815
  fromJson(input, key) {
606
- if (nullable) {
607
- return `when (${input}) {
608
- is JsonNull -> null
609
- is JsonPrimitive -> ${prefixedClassName}.fromJsonElement(${input}!!, "$instancePath/${key ?? ""}")
610
- else -> null
611
- }`;
612
- }
613
816
  return `when (${input}) {
614
- is JsonNull -> ${defaultValue}
615
- is JsonPrimitive -> ${prefixedClassName}.fromJsonElement(${input}!!, "$instancePath/${key}")
616
- else -> ${defaultValue}
617
- }`;
817
+ is JsonNull -> ${defaultValue}
818
+ is JsonPrimitive -> ${prefixedClassName}.fromJsonElement(${input}!!, "$instancePath/${key ?? ""}")
819
+ else -> ${defaultValue}
820
+ }`;
618
821
  },
619
822
  toJson(input, target) {
620
823
  if (schema.isNullable) {
621
824
  return `${target} += when (${input}) {
622
- is ${prefixedClassName} -> "\\"\${${input}.serialValue}\\""
623
- else -> "null"
624
- }`;
825
+ is ${prefixedClassName} -> "\\"\${${input}.serialValue}\\""
826
+ else -> "null"
827
+ }`;
625
828
  }
626
829
  return `${target} += "\\"\${${input}.serialValue}\\""`;
627
830
  },
628
831
  toQueryString(input, target, key) {
629
- if (context.isOptional) {
630
- return `if (${input} != null) {
631
- ${target}.add("${key}=\${${input}.serialValue}")
632
- }`;
633
- }
634
- if (schema.isNullable) {
635
- return `${target}.add("${key}=\${${input}?.serialValue}")`;
636
- }
637
- return `${target}.add("${key}=\${${input}.serialValue}")`;
832
+ return kotlinEncodedQueryString(
833
+ schema,
834
+ context,
835
+ input,
836
+ target,
837
+ key,
838
+ (value) => `${value}.serialValue`
839
+ );
638
840
  },
639
841
  content
640
842
  };
@@ -659,42 +861,46 @@ function kotlinMapFromSchema(schema, context) {
659
861
  defaultValue,
660
862
  fromJson(input, key) {
661
863
  return `when (${input}) {
662
- is JsonObject -> {
663
- val __value: ${typeName} = mutableMapOf()
664
- for (__entry in ${input}!!.jsonObject.entries) {
665
- __value[__entry.key] = ${subType.fromJson("__entry.value", key)}
666
- }
667
- __value
668
- }
864
+ is JsonObject -> {
865
+ val __value: ${typeName} = mutableMapOf()
866
+ for (__entry in ${input}!!.jsonObject.entries) {
867
+ __value[__entry.key] = ${indentTail(subType.fromJson("__entry.value", key), 12)}
868
+ }
869
+ __value
870
+ }
669
871
 
670
- else -> ${defaultValue}
671
- }`;
872
+ else -> ${defaultValue}
873
+ }`;
672
874
  },
673
875
  toJson(input, target) {
876
+ const valueToJson = indentTail(
877
+ subType.toJson("__entry.value", target),
878
+ 4
879
+ );
674
880
  if (schema.isNullable) {
675
881
  return `if (${input} == null) {
676
- ${target} += "null"
677
- } else {
678
- ${target} += "{"
679
- for ((__index, __entry) in ${input}.entries.withIndex()) {
680
- if (__index != 0) {
681
- ${target} += ","
682
- }
683
- ${target} += "\${buildString { printQuoted(__entry.key) }}:"
684
- ${subType.toJson("__entry.value", target)}
685
- }
686
- ${target} += "}"
687
- }`;
882
+ ${target} += "null"
883
+ } else {
884
+ ${target} += "{"
885
+ for ((__index, __entry) in ${input}.entries.withIndex()) {
886
+ if (__index != 0) {
887
+ ${target} += ","
888
+ }
889
+ ${target} += "\${buildString { printQuoted(__entry.key) }}:"
890
+ ${indentTail(valueToJson, 4)}
891
+ }
892
+ ${target} += "}"
893
+ }`;
688
894
  }
689
895
  return `${target} += "{"
690
- for ((__index, __entry) in ${input}.entries.withIndex()) {
691
- if (__index != 0) {
692
- ${target} += ","
693
- }
694
- ${target} += "\${buildString { printQuoted(__entry.key) }}:"
695
- ${subType.toJson("__entry.value", target)}
696
- }
697
- ${target} += "}"`;
896
+ for ((__index, __entry) in ${input}.entries.withIndex()) {
897
+ if (__index != 0) {
898
+ ${target} += ","
899
+ }
900
+ ${target} += "\${buildString { printQuoted(__entry.key) }}:"
901
+ ${valueToJson}
902
+ }
903
+ ${target} += "}"`;
698
904
  },
699
905
  toQueryString() {
700
906
  return `__logError("[WARNING] nested objects cannot be serialized to query params. Skipping field at ${context.instancePath}.")`;
@@ -704,12 +910,13 @@ function kotlinMapFromSchema(schema, context) {
704
910
  }
705
911
 
706
912
  function defaultToQueryString(context, input, target, key) {
913
+ const queryKey = encodeURIComponent(key);
707
914
  if (context.isOptional) {
708
915
  return `if (${input} != null) {
709
- ${target}.add("${key}=$${input}")
710
- }`;
916
+ ${target}.add("${queryKey}=$${input}")
917
+ }`;
711
918
  }
712
- return `${target}.add("${key}=$${input}")`;
919
+ return `${target}.add("${queryKey}=$${input}")`;
713
920
  }
714
921
  function defaultToJsonString(context, input, target) {
715
922
  return `${target} += ${input}`;
@@ -725,26 +932,33 @@ function kotlinStringFromSchema(schema, context) {
725
932
  fromJson(input) {
726
933
  if (nullable) {
727
934
  return `when (${input}) {
728
- is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull
729
- else -> null
730
- }`;
935
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull
936
+ else -> null
937
+ }`;
731
938
  }
732
939
  return `when (${input}) {
733
- is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull ?: ${defaultValue}
734
- else -> ${defaultValue}
735
- }`;
940
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull ?: ${defaultValue}
941
+ else -> ${defaultValue}
942
+ }`;
736
943
  },
737
944
  toJson(input, target) {
738
945
  if (schema.isNullable) {
739
946
  return `${target} += when (${input}) {
740
- is String -> buildString { printQuoted(${input}) }
741
- else -> "null"
742
- }`;
947
+ is String -> buildString { printQuoted(${input}) }
948
+ else -> "null"
949
+ }`;
743
950
  }
744
951
  return `${target} += buildString { printQuoted(${input}) }`;
745
952
  },
746
953
  toQueryString(input, target, key) {
747
- return defaultToQueryString(context, input, target, key);
954
+ return kotlinEncodedQueryString(
955
+ schema,
956
+ context,
957
+ input,
958
+ target,
959
+ key,
960
+ (value) => value
961
+ );
748
962
  },
749
963
  content: ""
750
964
  };
@@ -760,14 +974,14 @@ function kotlinBooleanFromSchema(schema, context) {
760
974
  fromJson(input) {
761
975
  if (nullable) {
762
976
  return `when (${input}) {
763
- is JsonPrimitive -> ${input}!!.jsonPrimitive.booleanOrNull
764
- else -> null
765
- }`;
977
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.booleanOrNull
978
+ else -> null
979
+ }`;
766
980
  }
767
981
  return `when (${input}) {
768
- is JsonPrimitive -> ${input}!!.jsonPrimitive.booleanOrNull ?: ${defaultValue}
769
- else -> ${defaultValue}
770
- }`;
982
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.booleanOrNull ?: ${defaultValue}
983
+ else -> ${defaultValue}
984
+ }`;
771
985
  },
772
986
  toJson(input, target) {
773
987
  return defaultToJsonString(context, input, target);
@@ -780,7 +994,7 @@ function kotlinBooleanFromSchema(schema, context) {
780
994
  }
781
995
  function kotlinTimestampFromSchema(schema, context) {
782
996
  const nullable = isNullable(schema, context);
783
- const defaultValue = nullable ? "null" : "Instant.now()";
997
+ const defaultValue = nullable ? "null" : "Instant.EPOCH";
784
998
  return {
785
999
  typeName: "Instant",
786
1000
  prefixedTypeName: "Instant",
@@ -788,48 +1002,37 @@ function kotlinTimestampFromSchema(schema, context) {
788
1002
  defaultValue,
789
1003
  fromJson(input) {
790
1004
  return `when (${input}) {
791
- is JsonPrimitive ->
792
- if (${input}!!.jsonPrimitive.isString)
793
- Instant.parse(${input}!!.jsonPrimitive.content)
794
- else
795
- ${defaultValue}
796
- else -> ${defaultValue}
797
- }`;
1005
+ is JsonPrimitive ->
1006
+ if (${input}!!.jsonPrimitive.isString)
1007
+ try {
1008
+ Instant.parse(${input}!!.jsonPrimitive.content)
1009
+ } catch (e: java.time.format.DateTimeParseException) {
1010
+ ${defaultValue}
1011
+ }
1012
+ else
1013
+ ${defaultValue}
1014
+
1015
+ else -> ${defaultValue}
1016
+ }`;
798
1017
  },
799
1018
  toJson(input, target) {
800
1019
  if (schema.isNullable) {
801
1020
  return `${target} += when (${input}) {
802
- is Instant -> "\\"\${timestampFormatter.format(${input})}\\""
803
- else -> "null"
804
- }`;
1021
+ is Instant -> "\\"\${timestampFormatter.format(${input})}\\""
1022
+ else -> "null"
1023
+ }`;
805
1024
  }
806
1025
  return `${target} += "\\"\${timestampFormatter.format(${input})}\\""`;
807
1026
  },
808
1027
  toQueryString(input, target, key) {
809
- if (context.isOptional) {
810
- return `if (${input} != null) {
811
- ${target}.add(
812
- "${key}=\${
813
- timestampFormatter.format(${input})
814
- }"
815
- )
816
- }`;
817
- }
818
- if (schema.isNullable) {
819
- return `${target}.add(
820
- "${key}=\${
821
- when (${input}) {
822
- is Instant -> timestampFormatter.format(${input})
823
- else -> "null"
824
- }
825
- }"
826
- )`;
827
- }
828
- return `${target}.add(
829
- "${key}=\${
830
- timestampFormatter.format(${input})
831
- }"
832
- )`;
1028
+ return kotlinEncodedQueryString(
1029
+ schema,
1030
+ context,
1031
+ input,
1032
+ target,
1033
+ key,
1034
+ (value) => `timestampFormatter.format(${value})`
1035
+ );
833
1036
  },
834
1037
  content: ""
835
1038
  };
@@ -845,14 +1048,14 @@ function kotlinFloat32FromSchema(schema, context) {
845
1048
  fromJson(input) {
846
1049
  if (nullable) {
847
1050
  return `when (${input}) {
848
- is JsonPrimitive -> ${input}!!.jsonPrimitive.floatOrNull
849
- else -> null
850
- }`;
1051
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.floatOrNull
1052
+ else -> null
1053
+ }`;
851
1054
  }
852
1055
  return `when (${input}) {
853
- is JsonPrimitive -> ${input}!!.jsonPrimitive.floatOrNull ?: ${defaultValue}
854
- else -> ${defaultValue}
855
- }`;
1056
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.floatOrNull ?: ${defaultValue}
1057
+ else -> ${defaultValue}
1058
+ }`;
856
1059
  },
857
1060
  toJson(input, target) {
858
1061
  return defaultToJsonString(context, input, target);
@@ -874,14 +1077,14 @@ function kotlinFloat64FromSchema(schema, context) {
874
1077
  fromJson(input) {
875
1078
  if (nullable) {
876
1079
  return `when (${input}) {
877
- is JsonPrimitive -> ${input}!!.jsonPrimitive.doubleOrNull
878
- else -> null
879
- }`;
1080
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.doubleOrNull
1081
+ else -> null
1082
+ }`;
880
1083
  }
881
1084
  return `when (${input}) {
882
- is JsonPrimitive -> ${input}!!.jsonPrimitive.doubleOrNull ?: 0.0
883
- else -> 0.0
884
- }`;
1085
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.doubleOrNull ?: 0.0
1086
+ else -> 0.0
1087
+ }`;
885
1088
  },
886
1089
  toJson(input, target) {
887
1090
  return defaultToJsonString(context, input, target);
@@ -903,14 +1106,14 @@ function kotlinInt8FromSchema(schema, context) {
903
1106
  fromJson(input) {
904
1107
  if (nullable) {
905
1108
  return `when (${input}) {
906
- is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toByteOrNull()
907
- else -> null
908
- }`;
1109
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toByteOrNull()
1110
+ else -> null
1111
+ }`;
909
1112
  }
910
1113
  return `when (${input}) {
911
- is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toByteOrNull() ?: 0
912
- else -> 0
913
- }`;
1114
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toByteOrNull() ?: 0
1115
+ else -> 0
1116
+ }`;
914
1117
  },
915
1118
  toJson(input, target) {
916
1119
  return defaultToJsonString(context, input, target);
@@ -932,14 +1135,14 @@ function kotlinInt16FromSchema(schema, context) {
932
1135
  fromJson(input) {
933
1136
  if (nullable) {
934
1137
  return `when (${input}) {
935
- is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toShortOrNull()
936
- else -> null
937
- }`;
1138
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toShortOrNull()
1139
+ else -> null
1140
+ }`;
938
1141
  }
939
1142
  return `when (${input}) {
940
- is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toShortOrNull() ?: 0
941
- else -> 0
942
- }`;
1143
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toShortOrNull() ?: 0
1144
+ else -> 0
1145
+ }`;
943
1146
  },
944
1147
  toJson(input, target) {
945
1148
  return defaultToJsonString(context, input, target);
@@ -961,14 +1164,14 @@ function kotlinInt32FromSchema(schema, context) {
961
1164
  fromJson(input) {
962
1165
  if (nullable) {
963
1166
  return `when (${input}) {
964
- is JsonPrimitive -> ${input}!!.jsonPrimitive.intOrNull
965
- else -> null
966
- }`;
1167
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.intOrNull
1168
+ else -> null
1169
+ }`;
967
1170
  }
968
1171
  return `when (${input}) {
969
- is JsonPrimitive -> ${input}!!.jsonPrimitive.intOrNull ?: 0
970
- else -> 0
971
- }`;
1172
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.intOrNull ?: 0
1173
+ else -> 0
1174
+ }`;
972
1175
  },
973
1176
  toJson(input, target) {
974
1177
  return defaultToJsonString(context, input, target);
@@ -990,21 +1193,21 @@ function kotlinInt64FromSchema(schema, context) {
990
1193
  fromJson(input) {
991
1194
  if (nullable) {
992
1195
  return `when (${input}) {
993
- is JsonPrimitive -> ${input}!!.jsonPrimitive.longOrNull
994
- else -> null
995
- }`;
1196
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.longOrNull
1197
+ else -> null
1198
+ }`;
996
1199
  }
997
1200
  return `when (${input}) {
998
- is JsonPrimitive -> ${input}!!.jsonPrimitive.longOrNull ?: 0L
999
- else -> 0L
1000
- }`;
1201
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.longOrNull ?: 0L
1202
+ else -> 0L
1203
+ }`;
1001
1204
  },
1002
1205
  toJson(input, target) {
1003
1206
  if (schema.isNullable) {
1004
1207
  return `${target} += when (${input}) {
1005
- is Long -> "\\"\${${input}}\\""
1006
- else -> "null"
1007
- }`;
1208
+ is Long -> "\\"\${${input}}\\""
1209
+ else -> "null"
1210
+ }`;
1008
1211
  }
1009
1212
  return `${target} += "\\"\${${input}}\\""`;
1010
1213
  },
@@ -1025,14 +1228,14 @@ function kotlinUint8FromSchema(schema, context) {
1025
1228
  fromJson(input) {
1026
1229
  if (nullable) {
1027
1230
  return `when (${input}) {
1028
- is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toUByteOrNull()
1029
- else -> null
1030
- }`;
1231
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toUByteOrNull()
1232
+ else -> null
1233
+ }`;
1031
1234
  }
1032
1235
  return `when (${input}) {
1033
- is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toUByteOrNull() ?: 0u
1034
- else -> 0u
1035
- }`;
1236
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toUByteOrNull() ?: 0u
1237
+ else -> 0u
1238
+ }`;
1036
1239
  },
1037
1240
  toJson(input, target) {
1038
1241
  return defaultToJsonString(context, input, target);
@@ -1054,14 +1257,14 @@ function kotlinUint16FromSchema(schema, context) {
1054
1257
  fromJson(input) {
1055
1258
  if (nullable) {
1056
1259
  return `when (${input}) {
1057
- is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toUShortOrNull()
1058
- else -> null
1059
- }`;
1260
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toUShortOrNull()
1261
+ else -> null
1262
+ }`;
1060
1263
  }
1061
1264
  return `when (${input}) {
1062
- is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toUShortOrNull() ?: 0u
1063
- else -> 0u
1064
- }`;
1265
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toUShortOrNull() ?: 0u
1266
+ else -> 0u
1267
+ }`;
1065
1268
  },
1066
1269
  toJson(input, target) {
1067
1270
  return defaultToJsonString(context, input, target);
@@ -1083,14 +1286,14 @@ function kotlinUint32FromSchema(schema, context) {
1083
1286
  fromJson(input) {
1084
1287
  if (nullable) {
1085
1288
  return `when (${input}) {
1086
- is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toUIntOrNull()
1087
- else -> null
1088
- }`;
1289
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toUIntOrNull()
1290
+ else -> null
1291
+ }`;
1089
1292
  }
1090
1293
  return `when (${input}) {
1091
- is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toUIntOrNull() ?: 0u
1092
- else -> 0u
1093
- }`;
1294
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toUIntOrNull() ?: 0u
1295
+ else -> 0u
1296
+ }`;
1094
1297
  },
1095
1298
  toJson(input, target) {
1096
1299
  return defaultToJsonString(context, input, target);
@@ -1112,21 +1315,21 @@ function kotlinUint64FromSchema(schema, context) {
1112
1315
  fromJson(input) {
1113
1316
  if (nullable) {
1114
1317
  return `when (${input}) {
1115
- is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toULongOrNull()
1116
- else -> null
1117
- }`;
1318
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toULongOrNull()
1319
+ else -> null
1320
+ }`;
1118
1321
  }
1119
1322
  return `when (${input}) {
1120
- is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toULongOrNull() ?: 0UL
1121
- else -> 0UL
1122
- }`;
1323
+ is JsonPrimitive -> ${input}!!.jsonPrimitive.contentOrNull?.toULongOrNull() ?: 0UL
1324
+ else -> 0UL
1325
+ }`;
1123
1326
  },
1124
1327
  toJson(input, target) {
1125
1328
  if (schema.isNullable) {
1126
1329
  return `${target} += when (${input}) {
1127
- is ULong -> "\\"\${${input}}\\""
1128
- else -> "null"
1129
- }`;
1330
+ is ULong -> "\\"\${${input}}\\""
1331
+ else -> "null"
1332
+ }`;
1130
1333
  }
1131
1334
  return `${target} += "\\"\${${input}}\\""`;
1132
1335
  },
@@ -1164,37 +1367,37 @@ function kotlinHttpRpcFromSchema(schema, context) {
1164
1367
  );
1165
1368
  if (schema.isEventStream) {
1166
1369
  return `${codeComment}suspend fun ${name}(
1167
- ${params ? `params: ${params},` : ""}
1168
- lastEventId: String? = null,
1169
- bufferCapacity: Int = 1024 * 1024,
1170
- onOpen: ((response: HttpResponse) -> Unit) = {},
1171
- onClose: (() -> Unit) = {},
1172
- onRequestError: ((error: Exception) -> Unit) = {},
1173
- onResponseError: ((error: ${context.clientName}Error) -> Unit) = {},
1174
- onData: ((${response ? `data: ${response}` : ""}) -> Unit) = {},
1175
- maxBackoffTime: Long? = null,
1176
- ): Unit {
1177
- __handleSseRequest(
1178
- httpClient = httpClient,
1179
- url = "$baseUrl${schema.path}",
1180
- method = HttpMethod.${codegenUtils.pascalCase(schema.method, { normalize: true })},
1181
- params = ${params ? "params" : "null"},
1182
- headers = headers,
1183
- backoffTime = 0,
1184
- maxBackoffTime = maxBackoffTime ?: 30000L,
1185
- lastEventId = lastEventId,
1186
- bufferCapacity = bufferCapacity,
1187
- onOpen = onOpen,
1188
- onClose = onClose,
1189
- onError = onError,
1190
- onRequestError = onRequestError,
1191
- onResponseError = onResponseError,
1192
- onData = { str ->
1193
- ${response ? `val data = ${response}.fromJson(str)` : ""}
1194
- onData(${response ? "data" : ""})
1195
- }
1196
- )
1197
- }`;
1370
+ ${params ? `params: ${params},
1371
+ ` : ""}lastEventId: String? = null,
1372
+ bufferCapacity: Int = 1024 * 1024,
1373
+ onOpen: ((response: HttpResponse) -> Unit) = {},
1374
+ onClose: (() -> Unit) = {},
1375
+ onRequestError: ((error: Exception) -> Unit) = {},
1376
+ onResponseError: ((error: ${context.clientName}Error) -> Unit) = {},
1377
+ onData: ((${response ? `data: ${response}` : ""}) -> Unit) = {},
1378
+ maxBackoffTime: Long? = null,
1379
+ ): Unit {
1380
+ __handleSseRequest(
1381
+ httpClient = httpClient,
1382
+ url = "$baseUrl${schema.path}",
1383
+ method = HttpMethod.${codegenUtils.pascalCase(schema.method, { normalize: true })},
1384
+ params = ${params ? "params" : "null"},
1385
+ headers = headers,
1386
+ backoffTime = 0,
1387
+ maxBackoffTime = maxBackoffTime ?: 30000L,
1388
+ lastEventId = lastEventId,
1389
+ bufferCapacity = bufferCapacity,
1390
+ onOpen = onOpen,
1391
+ onClose = onClose,
1392
+ onError = onError,
1393
+ onRequestError = onRequestError,
1394
+ onResponseError = onResponseError,
1395
+ onData = { str ->
1396
+ ${response ? `val data = ${response}.fromJson(str)
1397
+ ` : ""}onData(${response ? "data" : ""})
1398
+ }
1399
+ )
1400
+ }`;
1198
1401
  }
1199
1402
  const headingCheck = `if (response.headers["Content-Type"] != "application/json") {
1200
1403
  throw ${context.clientName}Error(
@@ -1203,26 +1406,26 @@ function kotlinHttpRpcFromSchema(schema, context) {
1203
1406
  data = JsonPrimitive(response.bodyAsText()),
1204
1407
  stack = null,
1205
1408
  )
1206
- }`;
1409
+ }
1410
+ `;
1207
1411
  return `${codeComment}suspend fun ${name}(${params ? `params: ${params}` : ""}): ${response ?? "Unit"} {
1208
- try {
1209
- val response = __prepareRequest(
1210
- client = httpClient,
1211
- url = "$baseUrl${schema.path}",
1212
- method = HttpMethod.${codegenUtils.pascalCase(schema.method, { normalize: true })},
1213
- params = ${params ? "params" : null},
1214
- headers = headers?.invoke(),
1215
- ).execute()
1216
- ${response ? headingCheck : ""}
1217
- if (response.status.value in 200..299) {
1218
- return ${response ? `${response}.fromJson(response.bodyAsText())` : ""}
1219
- }
1220
- throw ${context.clientName}Error.fromJson(response.bodyAsText())
1221
- } catch (e: Exception) {
1222
- onError(e)
1223
- throw e
1412
+ try {
1413
+ val response = __prepareRequest(
1414
+ client = httpClient,
1415
+ url = "$baseUrl${schema.path}",
1416
+ method = HttpMethod.${codegenUtils.pascalCase(schema.method, { normalize: true })},
1417
+ params = ${params ? "params" : null},
1418
+ headers = headers?.invoke(),
1419
+ ).execute()
1420
+ ${response ? headingCheck : ""}if (response.status.value in 200..299) {
1421
+ return${response ? ` ${response}.fromJson(response.bodyAsText())` : ""}
1224
1422
  }
1225
- }`;
1423
+ throw ${context.clientName}Error.fromJson(response.bodyAsText())
1424
+ } catch (e: Exception) {
1425
+ onError(e)
1426
+ throw e
1427
+ }
1428
+ }`;
1226
1429
  }
1227
1430
  function kotlinWsRpcFromSchema(_schema, _context) {
1228
1431
  return "";
@@ -1239,12 +1442,9 @@ function kotlinServiceFromSchema(schema, context) {
1239
1442
  ...context,
1240
1443
  instancePath: `${context.instancePath}.${key}`
1241
1444
  });
1242
- procedureParts.push(`val ${kotlinKey}: ${subService.name} = ${subService.name}(
1243
- httpClient = httpClient,
1244
- baseUrl = baseUrl,
1245
- headers = headers,
1246
- onError = onError,
1247
- )`);
1445
+ procedureParts.push(
1446
+ kotlinSubServiceField(kotlinKey, subService.name)
1447
+ );
1248
1448
  if (subService.content) {
1249
1449
  subServiceParts.push(subService.content);
1250
1450
  }
@@ -1269,12 +1469,20 @@ function kotlinServiceFromSchema(schema, context) {
1269
1469
  private val headers: __${context.clientName}HeadersFn,
1270
1470
  private val onError: ((err: Exception) -> Unit) = {},
1271
1471
  ) {
1272
- ${procedureParts.join("\n\n ")}
1273
- }
1472
+ ${indentTail(procedureParts.join("\n\n"), 4)}
1473
+ }${subServiceParts.length ? `
1274
1474
 
1275
- ${subServiceParts.join("\n\n")}`
1475
+ ${subServiceParts.join("\n\n")}` : ""}`
1276
1476
  };
1277
1477
  }
1478
+ function kotlinSubServiceField(key, serviceName) {
1479
+ return `val ${key}: ${serviceName} = ${serviceName}(
1480
+ httpClient = httpClient,
1481
+ baseUrl = baseUrl,
1482
+ headers = headers,
1483
+ onError = onError,
1484
+ )`;
1485
+ }
1278
1486
  function getProcedureName(context) {
1279
1487
  const name = context.instancePath.split(".").pop() ?? "";
1280
1488
  return kotlinIdentifier(name);
@@ -1296,12 +1504,13 @@ function kotlinRefFromSchema(schema, context) {
1296
1504
  defaultValue,
1297
1505
  fromJson(input, key) {
1298
1506
  return `when (${input}) {
1299
- is JsonObject -> ${prefixedTypeName}.fromJsonElement(
1300
- ${input}!!,
1301
- "$instancePath/${key}",
1302
- )
1303
- else -> ${defaultValue}
1304
- }`;
1507
+ is JsonObject -> ${prefixedTypeName}.fromJsonElement(
1508
+ ${input}!!,
1509
+ "$instancePath/${key}",
1510
+ )
1511
+
1512
+ else -> ${defaultValue}
1513
+ }`;
1305
1514
  },
1306
1515
  toJson(input, target) {
1307
1516
  if (schema.isNullable) {
@@ -1363,12 +1572,9 @@ function kotlinClientFromAppDefinition(def, options) {
1363
1572
  ...context,
1364
1573
  instancePath: `${key}`
1365
1574
  });
1366
- procedureParts.push(`val ${kotlinKey}: ${subService.name} = ${subService.name}(
1367
- httpClient = httpClient,
1368
- baseUrl = baseUrl,
1369
- headers = headers,
1370
- onError = onError,
1371
- )`);
1575
+ procedureParts.push(
1576
+ kotlinSubServiceField(kotlinKey, subService.name)
1577
+ );
1372
1578
  if (subService.content) {
1373
1579
  subServiceParts.push(subService.content);
1374
1580
  }
@@ -1401,7 +1607,7 @@ class ${clientName}(
1401
1607
  private val headers: __${clientName}HeadersFn,
1402
1608
  private val onError: ((err: Exception) -> Unit) = {},
1403
1609
  ) {
1404
- ${procedureParts.join("\n\n ")}
1610
+ ${indentTail(procedureParts.join("\n\n"), 4)}
1405
1611
  }
1406
1612
 
1407
1613
  ${subServiceParts.join("\n\n")}
@@ -1461,6 +1667,9 @@ function kotlinTypeFromSchema(schema, context) {
1461
1667
  if (codegenUtils.isSchemaFormDiscriminator(schema)) {
1462
1668
  return kotlinDiscriminatorFromSchema(schema, context);
1463
1669
  }
1670
+ if (codegenUtils.isSchemaFormUnion(schema)) {
1671
+ return kotlinUnionFromSchema(schema, context);
1672
+ }
1464
1673
  if (codegenUtils.isSchemaFormRef(schema)) {
1465
1674
  return kotlinRefFromSchema(schema, context);
1466
1675
  }
@@ -1639,6 +1848,13 @@ private fun __logError(string: String) {
1639
1848
  System.err.println(string)
1640
1849
  }
1641
1850
 
1851
+ /**
1852
+ * URL encodes a query param value. Null values are serialized as "null".
1853
+ */
1854
+ private fun __encodeQueryValue(value: String?): String {
1855
+ return value?.encodeURLParameter(spaceToPlus = true) ?: "null"
1856
+ }
1857
+
1642
1858
  private suspend fun __prepareRequest(
1643
1859
  client: HttpClient,
1644
1860
  url: String,
@@ -1806,7 +2022,7 @@ private suspend fun __handleSseRequest(
1806
2022
  if (httpResponse.status.value !in 200..299) {
1807
2023
  try {
1808
2024
  if (httpResponse.headers["Content-Type"] == "application/json") {
1809
- val err = ${clientName}Error.fromJson(httpResponse.bodyAsText())
2025
+ val err = ${clientName}Error.fromJson(httpResponse.bodyAsText())
1810
2026
  onError(err)
1811
2027
  onResponseError(err)
1812
2028
  } else {
@@ -1875,11 +2091,23 @@ private suspend fun __handleSseRequest(
1875
2091
  )
1876
2092
  }
1877
2093
  newBackoffTime = 0
2094
+ val heartbeatIntervalMs = httpResponse.headers["heartbeat-interval"]?.toLongOrNull() ?: 0L
1878
2095
  val channel: ByteReadChannel = httpResponse.body()
1879
2096
  var pendingData = ""
1880
2097
  while (!channel.isClosedForRead) {
1881
2098
  val buffer = ByteBuffer.allocateDirect(bufferCapacity)
1882
- val read = channel.readAvailable(buffer)
2099
+ val read = if (heartbeatIntervalMs > 0L) {
2100
+ withTimeoutOrNull(heartbeatIntervalMs * 2L) {
2101
+ channel.readAvailable(buffer)
2102
+ }
2103
+ } else {
2104
+ channel.readAvailable(buffer)
2105
+ }
2106
+ if (read == null) {
2107
+ // no data or heartbeat was received in time so assume the connection is dead and reconnect
2108
+ httpResponse.cancel()
2109
+ break
2110
+ }
1883
2111
  if (read == -1) break
1884
2112
  buffer.flip()
1885
2113
  val input = Charsets.UTF_8.decode(buffer).toString()
@@ -1987,6 +2215,7 @@ import io.ktor.utils.io.*
1987
2215
  import kotlinx.coroutines.cancel
1988
2216
  import kotlinx.coroutines.currentCoroutineContext
1989
2217
  import kotlinx.coroutines.withContext
2218
+ import kotlinx.coroutines.withTimeoutOrNull
1990
2219
  import kotlinx.serialization.encodeToString
1991
2220
  import kotlinx.serialization.json.*
1992
2221
  import java.nio.ByteBuffer