@kizunajs/kotlin 2.0.0-beta.35 → 2.0.0-beta.37

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/cli.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- const require_generator = require("./generator-DdoAAOSj.cjs");
2
+ const require_generator = require("./generator-DyQN5KLn.cjs");
3
3
  let node_fs = require("node:fs");
4
4
  let node_path = require("node:path");
5
5
  let node_util = require("node:util");
package/dist/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { t as generateKotlinClient } from "./generator-DRWVjcfl.mjs";
2
+ import { t as generateKotlinClient } from "./generator-Dm08BYru.mjs";
3
3
  import { mkdirSync, writeFileSync } from "node:fs";
4
4
  import { dirname, resolve } from "node:path";
5
5
  import { parseArgs } from "node:util";
@@ -1,4 +1,4 @@
1
- import { isBinarySchema, isDiscriminatedUnionSchema, isFileSchema, isHintPrefix, isIntegerSchema, isJsonMediaType, isJsonQueryField, isNamedStream, isObjectSchema, isStreamResponse, isSuccessStatus, localTypeName, mergeHeaderFields, parsePath, readDef, readDefType, readDeprecation, readDiscriminatedUnion, readDiscriminatorStringLiteral, readMetaBrand, readMetaDescription, readMetaId, readModelSchema, readObjectShape, resolveResponseBody, resolveResponseContentType, resolveResponseHeaders, routeStreams, sanitizeFieldName, sanitizeIdentifier, shortTypeName, soleStreamResponse, statusToCamelCase, streamMode, toCamelCase, toPascalCase, uniqueNames, unwrapOptionalWrappers, validatesRequest, walkApi } from "kizunajs/generator";
1
+ import { isBinarySchema, isDiscriminatedUnionSchema, isFileSchema, isHintPrefix, isIntegerSchema, isJsonMediaType, isJsonQueryField, isNamedStream, isObjectSchema, isStreamResponse, isSuccessStatus, localTypeName, mergeHeaderFields, parsePath, readDef, readDefType, readDeprecation, readDiscriminatedUnion, readDiscriminatorStringLiteral, readMetaBrand, readMetaDescription, readMetaExtensible, readMetaId, readModelSchema, readObjectShape, resolveResponseBody, resolveResponseContentType, resolveResponseHeaders, routeStreams, sanitizeFieldName, sanitizeIdentifier, shortTypeName, soleStreamResponse, statusToCamelCase, streamMode, toCamelCase, toPascalCase, uniqueNames, unwrapOptionalWrappers, validatesRequest, walkApi } from "kizunajs/generator";
2
2
  //#region src/emit.ts
3
3
  var KotlinWriter = class {
4
4
  lines = [];
@@ -198,6 +198,7 @@ const mapUnbrandedType = (schema, registry, hint) => {
198
198
  name: enumName,
199
199
  discriminator: discriminated.discriminator,
200
200
  variants: [],
201
+ unknownCase: registry.unknownEnumCase || readMetaExtensible(schema),
201
202
  description: readMetaDescription(schema)
202
203
  });
203
204
  const variants = [];
@@ -231,6 +232,7 @@ const mapUnbrandedType = (schema, registry, hint) => {
231
232
  name: enumName,
232
233
  discriminator: discriminated.discriminator,
233
234
  variants,
235
+ unknownCase: registry.unknownEnumCase || readMetaExtensible(schema),
234
236
  description: readMetaDescription(schema)
235
237
  });
236
238
  }
@@ -354,7 +356,7 @@ const mapUnbrandedType = (schema, registry, hint) => {
354
356
  name: enumName,
355
357
  cases,
356
358
  description: readMetaDescription(schema),
357
- unknownCase: registry.unknownEnumCase
359
+ unknownCase: registry.unknownEnumCase || readMetaExtensible(schema)
358
360
  });
359
361
  return {
360
362
  expression: enumName,
@@ -538,11 +540,16 @@ const buildRouteMethod = (routeKey, route, registry, deprecated, deprecationMess
538
540
  if (mode === "events" && isNamedStream(responseValue.stream)) stream = {
539
541
  status,
540
542
  mode,
541
- events: Object.entries(responseValue.stream).map(([name, schema]) => ({
542
- name,
543
- caseName: toPascalCase(name),
544
- type: mapType(schema, registry, `${baseHint}${toPascalCase(name)}`).expression
545
- }))
543
+ events: Object.entries(responseValue.stream).map(([name, schema]) => {
544
+ const type = mapType(schema, registry, `${baseHint}${toPascalCase(name)}`).expression;
545
+ const found = registry.get(type);
546
+ return {
547
+ name,
548
+ caseName: toPascalCase(name),
549
+ type,
550
+ unknownCase: found?.kind === "sealed-class" && found.unknownCase
551
+ };
552
+ })
546
553
  };
547
554
  else if (mode === "events") stream = {
548
555
  status,
@@ -981,11 +988,14 @@ const ownedTypePath = (typeName, ownedTypeMap, registry) => {
981
988
  return `${ownedTypePath(owningClass, ownedTypeMap, registry)}.${shortTypeName(typeName, owningClass)}`;
982
989
  };
983
990
  const emitSealedClass = (writer, type, registry, ownedTypeMap, ownedTypeLookup) => {
984
- writer.line(`@OptIn(ExperimentalSerializationApi::class)`);
985
- writer.line(`@JsonClassDiscriminator(${stringLiteral(type.discriminator)})`);
986
- writer.line("@Serializable");
991
+ if (type.unknownCase) writer.line(`@Serializable(with = ${type.name}.Serializer::class)`);
992
+ else {
993
+ writer.line(`@OptIn(ExperimentalSerializationApi::class)`);
994
+ writer.line(`@JsonClassDiscriminator(${stringLiteral(type.discriminator)})`);
995
+ writer.line("@Serializable");
996
+ }
987
997
  const nestedVariants = type.variants.filter((variant) => variant.nested);
988
- if (nestedVariants.length === 0) {
998
+ if (nestedVariants.length === 0 && !type.unknownCase) {
989
999
  writer.line(`sealed interface ${type.name}`);
990
1000
  return;
991
1001
  }
@@ -1002,9 +1012,10 @@ const emitSealedClass = (writer, type, registry, ownedTypeMap, ownedTypeLookup)
1002
1012
  })()
1003
1013
  }));
1004
1014
  const sharedFields = wrapped.length > 0 && wrapped.every(({ payload, inlined }) => payload !== void 0 && !inlined) ? wrapped[0].payload.fields.filter((field) => wrapped.every(({ payload }) => payload.fields.some((other) => other.name === field.name && other.type === field.type && other.optional === field.optional))) : [];
1015
+ const sharedOptional = (field) => field.optional || type.unknownCase && field.wireName !== type.discriminator;
1005
1016
  writer.block(`sealed interface ${type.name}`, () => {
1006
1017
  for (const field of sharedFields) {
1007
- const typeExpression = optionalize(ownedTypePath(field.type, ownedTypeMap, registry), field.optional);
1018
+ const typeExpression = optionalize(ownedTypePath(field.type, ownedTypeMap, registry), sharedOptional(field));
1008
1019
  writer.line(`val ${escapeKeyword(field.name)}: ${typeExpression}`);
1009
1020
  }
1010
1021
  if (sharedFields.length > 0) writer.blank();
@@ -1051,6 +1062,58 @@ const emitSealedClass = (writer, type, registry, ownedTypeMap, ownedTypeLookup)
1051
1062
  });
1052
1063
  else writer.line(`data class ${variant.caseName}(val value: ${ownedTypePath(variant.payloadType, ownedTypeMap, registry)}) : ${type.name}`);
1053
1064
  }
1065
+ if (type.unknownCase) emitUnknownVariant(writer, type, sharedFields, registry, ownedTypeMap);
1066
+ });
1067
+ };
1068
+ /**
1069
+ * A union's `Unknown` member and the serializer that falls back to it: it reads the discriminator, decodes the
1070
+ * matching variant from the rest of the object, and writes the discriminator back on encode.
1071
+ */
1072
+ const emitUnknownVariant = (writer, type, sharedFields, registry, ownedTypeMap) => {
1073
+ const taken = new Set(type.variants.map((variant) => variant.caseName));
1074
+ let unknown = "Unknown";
1075
+ while (taken.has(unknown)) unknown = `${unknown}Variant`;
1076
+ const discriminator = stringLiteral(type.discriminator);
1077
+ const cases = type.variants.map((variant) => {
1078
+ const payload = registry.all().find((candidate) => candidate.name === variant.payloadType);
1079
+ const inline = payload !== void 0 && payload.kind === "data-class" && payload.fields.length > 0;
1080
+ const wrapped = variant.nested && !inline;
1081
+ return {
1082
+ literal: stringLiteral(variant.literal),
1083
+ className: variant.nested ? variant.caseName : ownedTypePath(variant.payloadType, ownedTypeMap, registry),
1084
+ payloadPath: ownedTypePath(variant.payloadType, ownedTypeMap, registry),
1085
+ wrapped
1086
+ };
1087
+ });
1088
+ writer.blank();
1089
+ writer.docComment("A variant this client was generated before. It holds the discriminator, and cannot be sent back.");
1090
+ const overrides = sharedFields.map((field) => field.wireName === type.discriminator ? `override val ${escapeKeyword(field.name)}: String get() = wireValue` : `override val ${escapeKeyword(field.name)}: ${optionalize(ownedTypePath(field.type, ownedTypeMap, registry), true)} get() = null`);
1091
+ if (overrides.length === 0) writer.line(`data class ${unknown}(val wireValue: String) : ${type.name}`);
1092
+ else writer.block(`data class ${unknown}(val wireValue: String) : ${type.name}`, () => {
1093
+ for (const line of overrides) writer.line(line);
1094
+ });
1095
+ writer.blank();
1096
+ writer.block(`object Serializer : KSerializer<${type.name}>`, () => {
1097
+ writer.line(`override val descriptor: SerialDescriptor = buildClassSerialDescriptor(${stringLiteral(type.name)})`);
1098
+ writer.blank();
1099
+ writer.block(`override fun deserialize(decoder: Decoder): ${type.name}`, () => {
1100
+ writer.line("val input = decoder as JsonDecoder");
1101
+ writer.line("val element = input.decodeJsonElement().jsonObject");
1102
+ writer.line(`val body = JsonObject(element - ${discriminator})`);
1103
+ writer.block(`return when (val kind = element[${discriminator}]?.jsonPrimitive?.contentOrNull)`, () => {
1104
+ for (const each of cases) writer.line(each.wrapped ? `${each.literal} -> ${each.className}(input.json.decodeFromJsonElement(${each.payloadPath}.serializer(), body))` : `${each.literal} -> input.json.decodeFromJsonElement(${each.className}.serializer(), body)`);
1105
+ writer.line(`else -> ${unknown}(kind ?: "")`);
1106
+ });
1107
+ });
1108
+ writer.blank();
1109
+ writer.block(`override fun serialize(encoder: Encoder, value: ${type.name})`, () => {
1110
+ writer.line("val output = encoder as JsonEncoder");
1111
+ writer.block("val (kind, body) = when (value)", () => {
1112
+ for (const each of cases) writer.line(each.wrapped ? `is ${each.className} -> ${each.literal} to output.json.encodeToJsonElement(${each.payloadPath}.serializer(), value.value)` : `is ${each.className} -> ${each.literal} to output.json.encodeToJsonElement(${each.className}.serializer(), value)`);
1113
+ writer.line(`is ${unknown} -> throw SerializationException("This client does not know the variant \${value.wireValue}, so it cannot send it.")`);
1114
+ });
1115
+ writer.line(`output.encodeJsonElement(JsonObject(mapOf(${discriminator} to JsonPrimitive(kind)) + body.jsonObject))`);
1116
+ });
1054
1117
  });
1055
1118
  };
1056
1119
  const emitType = (writer, type, ownedTypeMap = /* @__PURE__ */ new Map(), ownedTypeLookup = /* @__PURE__ */ new Map(), registryName, registry, withBuilders = false) => {
@@ -1127,7 +1190,9 @@ const emitOperationResultTypes = (writer, method, context) => {
1127
1190
  const streamEvents = method.stream?.events;
1128
1191
  if (streamEvents) {
1129
1192
  const eventNames = new Set(streamEvents.map((event) => event.name));
1130
- if (eventNames.has("tool_call") && eventNames.has("tool_result")) {
1193
+ const tracksTools = eventNames.has("tool_call") && eventNames.has("tool_result");
1194
+ const readId = (eventName) => `val id = event.data.id${streamEvents.find((event) => event.name === eventName)?.unknownCase ? " ?: continue" : ""}`;
1195
+ if (tracksTools) {
1131
1196
  writer.blank();
1132
1197
  writer.line("/** One tool call, with its result once it answered. */");
1133
1198
  writer.line("data class ToolCallRecord(");
@@ -1157,11 +1222,17 @@ const emitOperationResultTypes = (writer, method, context) => {
1157
1222
  writer.indent(() => {
1158
1223
  writer.line("is Event.ToolCall -> {");
1159
1224
  writer.indent(() => {
1160
- writer.line("val tracked = (calls[event.data.id] ?: ToolCallRecord(event.data.id, event.data.name)).copy(call = event.data)");
1161
- writer.line("calls[event.data.id] = if (event.data.needsApproval == true && tracked.state == ToolCallRecord.State.Running) tracked.copy(state = ToolCallRecord.State.NeedsApproval) else tracked");
1225
+ writer.line(readId("tool_call"));
1226
+ writer.line("val tracked = (calls[id] ?: ToolCallRecord(id, event.data.name)).copy(call = event.data)");
1227
+ writer.line("calls[id] = if (event.data.needsApproval == true && tracked.state == ToolCallRecord.State.Running) tracked.copy(state = ToolCallRecord.State.NeedsApproval) else tracked");
1228
+ });
1229
+ writer.line("}");
1230
+ writer.line("is Event.ToolResult -> {");
1231
+ writer.indent(() => {
1232
+ writer.line(readId("tool_result"));
1233
+ writer.line("calls[id] = (calls[id] ?: ToolCallRecord(id, event.data.name)).copy(state = ToolCallRecord.State.Done, result = event.data)");
1162
1234
  });
1163
1235
  writer.line("}");
1164
- writer.line("is Event.ToolResult -> calls[event.data.id] = (calls[event.data.id] ?: ToolCallRecord(event.data.id, event.data.name)).copy(state = ToolCallRecord.State.Done, result = event.data)");
1165
1236
  if (eventNames.has("tool_error")) writer.line("is Event.ToolError -> calls[event.data.id] = (calls[event.data.id] ?: ToolCallRecord(event.data.id, event.data.name.wireValue)).copy(state = ToolCallRecord.State.Failed, message = event.data.message)");
1166
1237
  writer.line("else -> Unit");
1167
1238
  });
@@ -2038,7 +2109,7 @@ const renderKotlinClient = (api, partition, registry, config) => {
2038
2109
  }
2039
2110
  writer.line("import kotlinx.serialization.*");
2040
2111
  writer.line("import kotlinx.serialization.json.*");
2041
- if (registry.all().some((type) => type.kind === "enum-class" && type.unknownCase)) {
2112
+ if (registry.all().some((type) => (type.kind === "enum-class" || type.kind === "sealed-class") && type.unknownCase)) {
2042
2113
  writer.line("import kotlinx.serialization.descriptors.*");
2043
2114
  writer.line("import kotlinx.serialization.encoding.*");
2044
2115
  }
@@ -198,6 +198,7 @@ const mapUnbrandedType = (schema, registry, hint) => {
198
198
  name: enumName,
199
199
  discriminator: discriminated.discriminator,
200
200
  variants: [],
201
+ unknownCase: registry.unknownEnumCase || (0, kizunajs_generator.readMetaExtensible)(schema),
201
202
  description: (0, kizunajs_generator.readMetaDescription)(schema)
202
203
  });
203
204
  const variants = [];
@@ -231,6 +232,7 @@ const mapUnbrandedType = (schema, registry, hint) => {
231
232
  name: enumName,
232
233
  discriminator: discriminated.discriminator,
233
234
  variants,
235
+ unknownCase: registry.unknownEnumCase || (0, kizunajs_generator.readMetaExtensible)(schema),
234
236
  description: (0, kizunajs_generator.readMetaDescription)(schema)
235
237
  });
236
238
  }
@@ -354,7 +356,7 @@ const mapUnbrandedType = (schema, registry, hint) => {
354
356
  name: enumName,
355
357
  cases,
356
358
  description: (0, kizunajs_generator.readMetaDescription)(schema),
357
- unknownCase: registry.unknownEnumCase
359
+ unknownCase: registry.unknownEnumCase || (0, kizunajs_generator.readMetaExtensible)(schema)
358
360
  });
359
361
  return {
360
362
  expression: enumName,
@@ -538,11 +540,16 @@ const buildRouteMethod = (routeKey, route, registry, deprecated, deprecationMess
538
540
  if (mode === "events" && (0, kizunajs_generator.isNamedStream)(responseValue.stream)) stream = {
539
541
  status,
540
542
  mode,
541
- events: Object.entries(responseValue.stream).map(([name, schema]) => ({
542
- name,
543
- caseName: (0, kizunajs_generator.toPascalCase)(name),
544
- type: mapType(schema, registry, `${baseHint}${(0, kizunajs_generator.toPascalCase)(name)}`).expression
545
- }))
543
+ events: Object.entries(responseValue.stream).map(([name, schema]) => {
544
+ const type = mapType(schema, registry, `${baseHint}${(0, kizunajs_generator.toPascalCase)(name)}`).expression;
545
+ const found = registry.get(type);
546
+ return {
547
+ name,
548
+ caseName: (0, kizunajs_generator.toPascalCase)(name),
549
+ type,
550
+ unknownCase: found?.kind === "sealed-class" && found.unknownCase
551
+ };
552
+ })
546
553
  };
547
554
  else if (mode === "events") stream = {
548
555
  status,
@@ -981,11 +988,14 @@ const ownedTypePath = (typeName, ownedTypeMap, registry) => {
981
988
  return `${ownedTypePath(owningClass, ownedTypeMap, registry)}.${(0, kizunajs_generator.shortTypeName)(typeName, owningClass)}`;
982
989
  };
983
990
  const emitSealedClass = (writer, type, registry, ownedTypeMap, ownedTypeLookup) => {
984
- writer.line(`@OptIn(ExperimentalSerializationApi::class)`);
985
- writer.line(`@JsonClassDiscriminator(${stringLiteral(type.discriminator)})`);
986
- writer.line("@Serializable");
991
+ if (type.unknownCase) writer.line(`@Serializable(with = ${type.name}.Serializer::class)`);
992
+ else {
993
+ writer.line(`@OptIn(ExperimentalSerializationApi::class)`);
994
+ writer.line(`@JsonClassDiscriminator(${stringLiteral(type.discriminator)})`);
995
+ writer.line("@Serializable");
996
+ }
987
997
  const nestedVariants = type.variants.filter((variant) => variant.nested);
988
- if (nestedVariants.length === 0) {
998
+ if (nestedVariants.length === 0 && !type.unknownCase) {
989
999
  writer.line(`sealed interface ${type.name}`);
990
1000
  return;
991
1001
  }
@@ -1002,9 +1012,10 @@ const emitSealedClass = (writer, type, registry, ownedTypeMap, ownedTypeLookup)
1002
1012
  })()
1003
1013
  }));
1004
1014
  const sharedFields = wrapped.length > 0 && wrapped.every(({ payload, inlined }) => payload !== void 0 && !inlined) ? wrapped[0].payload.fields.filter((field) => wrapped.every(({ payload }) => payload.fields.some((other) => other.name === field.name && other.type === field.type && other.optional === field.optional))) : [];
1015
+ const sharedOptional = (field) => field.optional || type.unknownCase && field.wireName !== type.discriminator;
1005
1016
  writer.block(`sealed interface ${type.name}`, () => {
1006
1017
  for (const field of sharedFields) {
1007
- const typeExpression = optionalize(ownedTypePath(field.type, ownedTypeMap, registry), field.optional);
1018
+ const typeExpression = optionalize(ownedTypePath(field.type, ownedTypeMap, registry), sharedOptional(field));
1008
1019
  writer.line(`val ${escapeKeyword(field.name)}: ${typeExpression}`);
1009
1020
  }
1010
1021
  if (sharedFields.length > 0) writer.blank();
@@ -1051,6 +1062,58 @@ const emitSealedClass = (writer, type, registry, ownedTypeMap, ownedTypeLookup)
1051
1062
  });
1052
1063
  else writer.line(`data class ${variant.caseName}(val value: ${ownedTypePath(variant.payloadType, ownedTypeMap, registry)}) : ${type.name}`);
1053
1064
  }
1065
+ if (type.unknownCase) emitUnknownVariant(writer, type, sharedFields, registry, ownedTypeMap);
1066
+ });
1067
+ };
1068
+ /**
1069
+ * A union's `Unknown` member and the serializer that falls back to it: it reads the discriminator, decodes the
1070
+ * matching variant from the rest of the object, and writes the discriminator back on encode.
1071
+ */
1072
+ const emitUnknownVariant = (writer, type, sharedFields, registry, ownedTypeMap) => {
1073
+ const taken = new Set(type.variants.map((variant) => variant.caseName));
1074
+ let unknown = "Unknown";
1075
+ while (taken.has(unknown)) unknown = `${unknown}Variant`;
1076
+ const discriminator = stringLiteral(type.discriminator);
1077
+ const cases = type.variants.map((variant) => {
1078
+ const payload = registry.all().find((candidate) => candidate.name === variant.payloadType);
1079
+ const inline = payload !== void 0 && payload.kind === "data-class" && payload.fields.length > 0;
1080
+ const wrapped = variant.nested && !inline;
1081
+ return {
1082
+ literal: stringLiteral(variant.literal),
1083
+ className: variant.nested ? variant.caseName : ownedTypePath(variant.payloadType, ownedTypeMap, registry),
1084
+ payloadPath: ownedTypePath(variant.payloadType, ownedTypeMap, registry),
1085
+ wrapped
1086
+ };
1087
+ });
1088
+ writer.blank();
1089
+ writer.docComment("A variant this client was generated before. It holds the discriminator, and cannot be sent back.");
1090
+ const overrides = sharedFields.map((field) => field.wireName === type.discriminator ? `override val ${escapeKeyword(field.name)}: String get() = wireValue` : `override val ${escapeKeyword(field.name)}: ${optionalize(ownedTypePath(field.type, ownedTypeMap, registry), true)} get() = null`);
1091
+ if (overrides.length === 0) writer.line(`data class ${unknown}(val wireValue: String) : ${type.name}`);
1092
+ else writer.block(`data class ${unknown}(val wireValue: String) : ${type.name}`, () => {
1093
+ for (const line of overrides) writer.line(line);
1094
+ });
1095
+ writer.blank();
1096
+ writer.block(`object Serializer : KSerializer<${type.name}>`, () => {
1097
+ writer.line(`override val descriptor: SerialDescriptor = buildClassSerialDescriptor(${stringLiteral(type.name)})`);
1098
+ writer.blank();
1099
+ writer.block(`override fun deserialize(decoder: Decoder): ${type.name}`, () => {
1100
+ writer.line("val input = decoder as JsonDecoder");
1101
+ writer.line("val element = input.decodeJsonElement().jsonObject");
1102
+ writer.line(`val body = JsonObject(element - ${discriminator})`);
1103
+ writer.block(`return when (val kind = element[${discriminator}]?.jsonPrimitive?.contentOrNull)`, () => {
1104
+ for (const each of cases) writer.line(each.wrapped ? `${each.literal} -> ${each.className}(input.json.decodeFromJsonElement(${each.payloadPath}.serializer(), body))` : `${each.literal} -> input.json.decodeFromJsonElement(${each.className}.serializer(), body)`);
1105
+ writer.line(`else -> ${unknown}(kind ?: "")`);
1106
+ });
1107
+ });
1108
+ writer.blank();
1109
+ writer.block(`override fun serialize(encoder: Encoder, value: ${type.name})`, () => {
1110
+ writer.line("val output = encoder as JsonEncoder");
1111
+ writer.block("val (kind, body) = when (value)", () => {
1112
+ for (const each of cases) writer.line(each.wrapped ? `is ${each.className} -> ${each.literal} to output.json.encodeToJsonElement(${each.payloadPath}.serializer(), value.value)` : `is ${each.className} -> ${each.literal} to output.json.encodeToJsonElement(${each.className}.serializer(), value)`);
1113
+ writer.line(`is ${unknown} -> throw SerializationException("This client does not know the variant \${value.wireValue}, so it cannot send it.")`);
1114
+ });
1115
+ writer.line(`output.encodeJsonElement(JsonObject(mapOf(${discriminator} to JsonPrimitive(kind)) + body.jsonObject))`);
1116
+ });
1054
1117
  });
1055
1118
  };
1056
1119
  const emitType = (writer, type, ownedTypeMap = /* @__PURE__ */ new Map(), ownedTypeLookup = /* @__PURE__ */ new Map(), registryName, registry, withBuilders = false) => {
@@ -1127,7 +1190,9 @@ const emitOperationResultTypes = (writer, method, context) => {
1127
1190
  const streamEvents = method.stream?.events;
1128
1191
  if (streamEvents) {
1129
1192
  const eventNames = new Set(streamEvents.map((event) => event.name));
1130
- if (eventNames.has("tool_call") && eventNames.has("tool_result")) {
1193
+ const tracksTools = eventNames.has("tool_call") && eventNames.has("tool_result");
1194
+ const readId = (eventName) => `val id = event.data.id${streamEvents.find((event) => event.name === eventName)?.unknownCase ? " ?: continue" : ""}`;
1195
+ if (tracksTools) {
1131
1196
  writer.blank();
1132
1197
  writer.line("/** One tool call, with its result once it answered. */");
1133
1198
  writer.line("data class ToolCallRecord(");
@@ -1157,11 +1222,17 @@ const emitOperationResultTypes = (writer, method, context) => {
1157
1222
  writer.indent(() => {
1158
1223
  writer.line("is Event.ToolCall -> {");
1159
1224
  writer.indent(() => {
1160
- writer.line("val tracked = (calls[event.data.id] ?: ToolCallRecord(event.data.id, event.data.name)).copy(call = event.data)");
1161
- writer.line("calls[event.data.id] = if (event.data.needsApproval == true && tracked.state == ToolCallRecord.State.Running) tracked.copy(state = ToolCallRecord.State.NeedsApproval) else tracked");
1225
+ writer.line(readId("tool_call"));
1226
+ writer.line("val tracked = (calls[id] ?: ToolCallRecord(id, event.data.name)).copy(call = event.data)");
1227
+ writer.line("calls[id] = if (event.data.needsApproval == true && tracked.state == ToolCallRecord.State.Running) tracked.copy(state = ToolCallRecord.State.NeedsApproval) else tracked");
1228
+ });
1229
+ writer.line("}");
1230
+ writer.line("is Event.ToolResult -> {");
1231
+ writer.indent(() => {
1232
+ writer.line(readId("tool_result"));
1233
+ writer.line("calls[id] = (calls[id] ?: ToolCallRecord(id, event.data.name)).copy(state = ToolCallRecord.State.Done, result = event.data)");
1162
1234
  });
1163
1235
  writer.line("}");
1164
- writer.line("is Event.ToolResult -> calls[event.data.id] = (calls[event.data.id] ?: ToolCallRecord(event.data.id, event.data.name)).copy(state = ToolCallRecord.State.Done, result = event.data)");
1165
1236
  if (eventNames.has("tool_error")) writer.line("is Event.ToolError -> calls[event.data.id] = (calls[event.data.id] ?: ToolCallRecord(event.data.id, event.data.name.wireValue)).copy(state = ToolCallRecord.State.Failed, message = event.data.message)");
1166
1237
  writer.line("else -> Unit");
1167
1238
  });
@@ -2038,7 +2109,7 @@ const renderKotlinClient = (api, partition, registry, config) => {
2038
2109
  }
2039
2110
  writer.line("import kotlinx.serialization.*");
2040
2111
  writer.line("import kotlinx.serialization.json.*");
2041
- if (registry.all().some((type) => type.kind === "enum-class" && type.unknownCase)) {
2112
+ if (registry.all().some((type) => (type.kind === "enum-class" || type.kind === "sealed-class") && type.unknownCase)) {
2042
2113
  writer.line("import kotlinx.serialization.descriptors.*");
2043
2114
  writer.line("import kotlinx.serialization.encoding.*");
2044
2115
  }
package/dist/index.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_generator = require("./generator-DdoAAOSj.cjs");
2
+ const require_generator = require("./generator-DyQN5KLn.cjs");
3
3
  let kizunajs_generator = require("kizunajs/generator");
4
4
  let zod = require("zod");
5
5
  //#region src/client-target.ts
package/dist/index.d.cts CHANGED
@@ -21,10 +21,10 @@ interface KotlinConfig {
21
21
  */
22
22
  camelCaseProperties?: boolean;
23
23
  /**
24
- * Emit each `z.enum` as a `sealed interface` with an `Unknown(wireValue)`
25
- * member, so unrecognised wire values decode instead of throwing. The raw
26
- * string round-trips on encode and in query params. Discriminated unions are
27
- * unaffected and still throw on an unknown discriminator.
24
+ * Give each `z.enum` and discriminated union an `Unknown(wireValue)` member,
25
+ * so a value this client doesn't know decodes instead of throwing.
26
+ *
27
+ * An unknown union value can't be sent.
28
28
  *
29
29
  * @default false
30
30
  */
package/dist/index.d.mts CHANGED
@@ -21,10 +21,10 @@ interface KotlinConfig {
21
21
  */
22
22
  camelCaseProperties?: boolean;
23
23
  /**
24
- * Emit each `z.enum` as a `sealed interface` with an `Unknown(wireValue)`
25
- * member, so unrecognised wire values decode instead of throwing. The raw
26
- * string round-trips on encode and in query params. Discriminated unions are
27
- * unaffected and still throw on an unknown discriminator.
24
+ * Give each `z.enum` and discriminated union an `Unknown(wireValue)` member,
25
+ * so a value this client doesn't know decodes instead of throwing.
26
+ *
27
+ * An unknown union value can't be sent.
28
28
  *
29
29
  * @default false
30
30
  */
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { n as kotlinClientWalk, t as generateKotlinClient } from "./generator-DRWVjcfl.mjs";
1
+ import { n as kotlinClientWalk, t as generateKotlinClient } from "./generator-Dm08BYru.mjs";
2
2
  import { defineClient } from "kizunajs/generator";
3
3
  import { z } from "zod";
4
4
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kizunajs/kotlin",
3
- "version": "2.0.0-beta.35",
3
+ "version": "2.0.0-beta.37",
4
4
  "description": "Kotlin client generation for Kizuna.js APIs",
5
5
  "keywords": [
6
6
  "kizunajs",
@@ -60,15 +60,15 @@
60
60
  "access": "public"
61
61
  },
62
62
  "dependencies": {
63
- "@kizunajs/cli": "2.0.0-beta.35"
63
+ "@kizunajs/cli": "2.0.0-beta.37"
64
64
  },
65
65
  "peerDependencies": {
66
- "kizunajs": "2.0.0-beta.35",
66
+ "kizunajs": "2.0.0-beta.37",
67
67
  "zod": "^4.0.0"
68
68
  },
69
69
  "devDependencies": {
70
70
  "@types/node": "^24.19.2",
71
- "kizunajs": "2.0.0-beta.35",
71
+ "kizunajs": "2.0.0-beta.37",
72
72
  "tsdown": "^0.21.10",
73
73
  "typescript": "^6.0.3",
74
74
  "zod": "^4.6.7"