@kizunajs/kotlin 2.0.0-beta.3 → 2.0.0-beta.31

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.
@@ -56,6 +56,7 @@ var TypeRegistry = class {
56
56
  explicitIds = /* @__PURE__ */ new Set();
57
57
  sealedVariantPayloads = /* @__PURE__ */ new Set();
58
58
  sealedVariantPaths = /* @__PURE__ */ new Map();
59
+ brands = /* @__PURE__ */ new Map();
59
60
  usesJsonElement = false;
60
61
  constructor(camelCaseProperties = false, unknownEnumCase = false) {
61
62
  this.camelCaseProperties = camelCaseProperties;
@@ -99,6 +100,15 @@ var TypeRegistry = class {
99
100
  sealedVariantPath(name) {
100
101
  return this.sealedVariantPaths.get(name);
101
102
  }
103
+ addBrand(brand) {
104
+ const existing = this.brands.get(brand.name);
105
+ if (existing !== void 0 && existing.rawType !== brand.rawType) throw new Error(`@kizunajs/kotlin: brand ${stringify(brand.name)} wraps both ${existing.rawType} and ${brand.rawType}. Give each its own name.`);
106
+ if (this.types.has(brand.name)) throw new Error(`@kizunajs/kotlin: brand ${stringify(brand.name)} has the same name as a model. Give each its own name.`);
107
+ this.brands.set(brand.name, brand);
108
+ }
109
+ allBrands() {
110
+ return Array.from(this.brands.values());
111
+ }
102
112
  warnJsonElement(hint, reason) {
103
113
  this.usesJsonElement = true;
104
114
  this.warningSet.add(`${hint}: ${reason}`);
@@ -117,8 +127,7 @@ const propertyName = (key, camelCase) => {
117
127
  if (!camel) return "field";
118
128
  return /^[0-9]/.test(camel) ? `_${camel}` : camel;
119
129
  };
120
- const objectFields = (schema, registry, hint) => {
121
- const shape = (0, kizunajs_generator.readObjectShape)(schema) ?? {};
130
+ const objectFields = (schema, registry, hint, shape = (0, kizunajs_generator.readObjectShape)(schema) ?? {}) => {
122
131
  const fields = [];
123
132
  const seen = /* @__PURE__ */ new Map();
124
133
  for (const [key, value] of Object.entries(shape)) {
@@ -133,6 +142,7 @@ const objectFields = (schema, registry, hint) => {
133
142
  wireName: key,
134
143
  type: result.expression,
135
144
  optional: result.optional,
145
+ requiredNullable: result.requiredNullable,
136
146
  description: (0, kizunajs_generator.readMetaDescription)(value),
137
147
  isFile: result.isFile,
138
148
  deprecated: deprecation !== void 0,
@@ -142,12 +152,40 @@ const objectFields = (schema, registry, hint) => {
142
152
  return fields;
143
153
  };
144
154
  const stringify = (value) => JSON.stringify(value);
155
+ const BRANDABLE_TYPES = new Set([
156
+ "String",
157
+ "Int",
158
+ "Long",
159
+ "Double",
160
+ "Boolean",
161
+ "Instant"
162
+ ]);
145
163
  const mapType = (schema, registry, hint) => {
164
+ const result = mapUnbrandedType(schema, registry, hint);
165
+ const brand = (0, kizunajs_generator.readMetaBrand)(schema);
166
+ if (brand === void 0 || !BRANDABLE_TYPES.has(result.expression)) return result;
167
+ const name = (0, kizunajs_generator.sanitizeIdentifier)(brand);
168
+ registry.addBrand({
169
+ name,
170
+ rawType: result.expression
171
+ });
172
+ return {
173
+ expression: name,
174
+ optional: false
175
+ };
176
+ };
177
+ const mapUnbrandedType = (schema, registry, hint) => {
146
178
  if ((0, kizunajs_generator.isFileSchema)(schema)) return {
147
179
  expression: "MultipartFile",
148
180
  optional: false,
149
181
  isFile: true
150
182
  };
183
+ if ((0, kizunajs_generator.isBinarySchema)(schema)) return {
184
+ expression: "ByteArray",
185
+ optional: false
186
+ };
187
+ const model = (0, kizunajs_generator.readModelSchema)(schema);
188
+ if (model !== void 0 && model !== schema) return mapUnbrandedType(model, registry, hint);
151
189
  const id = (0, kizunajs_generator.readMetaId)(schema);
152
190
  const def = (0, kizunajs_generator.readDef)(schema);
153
191
  const discriminated = (0, kizunajs_generator.readDiscriminatedUnion)(schema);
@@ -229,6 +267,7 @@ const mapType = (schema, registry, hint) => {
229
267
  return {
230
268
  expression: innerResult.expression.endsWith("?") ? innerResult.expression : `${innerResult.expression}?`,
231
269
  optional: true,
270
+ requiredNullable: nullable && !optional,
232
271
  isFile: innerResult.isFile
233
272
  };
234
273
  }
@@ -277,8 +316,9 @@ const mapType = (schema, registry, hint) => {
277
316
  optional: false
278
317
  };
279
318
  }
319
+ const elementType = mapType(element, registry, `${hint}Item`).expression.replace(/\?$/, "");
280
320
  return {
281
- expression: `List<${mapType(element, registry, `${hint}Item`).expression.replace(/\?$/, "")}>`,
321
+ expression: `List<${(0, kizunajs_generator.unwrapOptionalWrappers)(element).nullable ? `${elementType}?` : elementType}>`,
282
322
  optional: false
283
323
  };
284
324
  }
@@ -412,6 +452,7 @@ const sanitizeCaseName = (literal) => {
412
452
  const collectObjectFields = (schema, registry, hint) => {
413
453
  return objectFields(schema, registry, hint);
414
454
  };
455
+ const hasDefault = (field) => field.optional && field.requiredNullable !== true;
415
456
  const objectFieldCount = (schema) => {
416
457
  return Object.keys((0, kizunajs_generator.readObjectShape)(schema) ?? {}).length;
417
458
  };
@@ -512,18 +553,23 @@ const buildRouteMethod = (routeKey, route, registry, deprecated, deprecationMess
512
553
  successResponses.push({
513
554
  status,
514
555
  type: stream.messageType ?? "Event",
515
- responseHeaders: headersSchema ? collectObjectFields(headersSchema, registry, `${baseHint}ResponseHeaders`) : []
556
+ responseHeaders: headersSchema ? collectObjectFields(headersSchema, registry, `${baseHint}ResponseHeaders`) : [],
557
+ isText: false
516
558
  });
517
559
  continue;
518
560
  }
519
- const typeExpression = mapType((0, kizunajs_generator.resolveResponseBody)(responseValue), registry, responseHint).expression;
561
+ const bodySchema = (0, kizunajs_generator.resolveResponseBody)(responseValue);
562
+ const responseContentType = (0, kizunajs_generator.resolveResponseContentType)(responseValue);
563
+ const isText = !(0, kizunajs_generator.isBinarySchema)(bodySchema) && responseContentType !== void 0 && !(0, kizunajs_generator.isJsonMediaType)(responseContentType);
564
+ const typeExpression = mapType(bodySchema, registry, responseHint).expression;
520
565
  if ((0, kizunajs_generator.isSuccessStatus)(status)) {
521
566
  const headersSchema = (0, kizunajs_generator.resolveResponseHeaders)(responseValue);
522
567
  const perStatusHeaderFields = headersSchema ? collectObjectFields(headersSchema, registry, `${baseHint}ResponseHeaders`) : [];
523
568
  successResponses.push({
524
569
  status,
525
570
  type: typeExpression,
526
- responseHeaders: perStatusHeaderFields
571
+ responseHeaders: perStatusHeaderFields,
572
+ isText
527
573
  });
528
574
  } else errorCases.push({
529
575
  caseName: (0, kizunajs_generator.statusToCamelCase)(status),
@@ -576,7 +622,7 @@ const buildRouteMethod = (routeKey, route, registry, deprecated, deprecationMess
576
622
  stream
577
623
  };
578
624
  };
579
- const kotlinGenerator = (0, kizunajs_generator.createGenerator)((options, _api) => {
625
+ const kotlinRoutesWalk = (options) => {
580
626
  const flatMethods = [];
581
627
  const groupMap = /* @__PURE__ */ new Map();
582
628
  return {
@@ -608,7 +654,7 @@ const kotlinGenerator = (0, kizunajs_generator.createGenerator)((options, _api)
608
654
  };
609
655
  }
610
656
  };
611
- });
657
+ };
612
658
  const KOTLIN_KEYWORDS = new Set([
613
659
  "as",
614
660
  "break",
@@ -642,6 +688,10 @@ const KOTLIN_KEYWORDS = new Set([
642
688
  const escapeKeyword = (name) => {
643
689
  return KOTLIN_KEYWORDS.has(name) ? `\`${name}\`` : name;
644
690
  };
691
+ const defaultArgument = (field) => {
692
+ if (!hasDefault(field)) return "";
693
+ return " = null";
694
+ };
645
695
  const optionalize = (type, optional) => {
646
696
  if (!optional) return type;
647
697
  return type.endsWith("?") ? type : `${type}?`;
@@ -653,8 +703,16 @@ const KOTLIN_PRIMITIVE_TYPES = new Set([
653
703
  "Long",
654
704
  "Boolean",
655
705
  "Instant",
656
- "Unit"
706
+ "Unit",
707
+ "ByteArray"
657
708
  ]);
709
+ /**
710
+ * How a response body is read. Raw bytes are the body already, and text is its decoded bytes.
711
+ */
712
+ const decodeBody = (resolved, isText = false) => {
713
+ if (resolved === "ByteArray") return "data";
714
+ return isText ? "data.decodeToString()" : `json.decodeFromString<${resolved}>(data.decodeToString())`;
715
+ };
658
716
  const resolveType = (typeName, currentOperation, context, scope = "client") => {
659
717
  const { operationTypeMap, namespaceName, clientName, fileLevelTypeNames } = context;
660
718
  const optional = typeName.endsWith("?");
@@ -797,7 +855,7 @@ const emitDataClass = (writer, type, ownedTypeMap, ownedTypeLookup, registryName
797
855
  if (!hasFile) writer.line("@Serializable");
798
856
  const params = adjustedFields.map((field) => {
799
857
  const typeExpression = optionalize(field.type, field.optional);
800
- const defaultPart = field.optional ? " = null" : "";
858
+ const defaultPart = defaultArgument(field);
801
859
  const serialNameAnnotation = needsSerialName && (field.name !== field.wireName || KOTLIN_KEYWORDS.has(field.name)) ? `@SerialName(${stringLiteral(field.wireName)}) ` : "";
802
860
  return `${field.deprecated ? `${deprecatedAnnotation(field.deprecationMessage)} ` : ""}${serialNameAnnotation}val ${escapeKeyword(field.name)}: ${typeExpression}${defaultPart}`;
803
861
  });
@@ -890,7 +948,7 @@ const emitSealedClass = (writer, type, registry, ownedTypeMap, ownedTypeLookup)
890
948
  const params = fields.map((field) => {
891
949
  const variantPath = registry.sealedVariantPath(variant.payloadType) ?? variant.payloadType;
892
950
  const typeExpression = optionalize(relativeOwnedPath(field.type, ownedTypeMap, variantPath, registry) ?? ownedTypePath(field.type, ownedTypeMap, registry), field.optional);
893
- const defaultPart = field.optional ? " = null" : "";
951
+ const defaultPart = defaultArgument(field);
894
952
  return `val ${escapeKeyword(field.name)}: ${typeExpression}${defaultPart}`;
895
953
  });
896
954
  if (params.length === 1) writer.line(`data class ${variant.caseName}(${params[0]}) : ${type.name}`);
@@ -927,6 +985,16 @@ const emitType = (writer, type, ownedTypeMap = /* @__PURE__ */ new Map(), ownedT
927
985
  else if (type.kind === "enum-class") emitEnumClass(writer, type.name, type.cases, type.unknownCase, type.description);
928
986
  else if (registry) emitSealedClass(writer, type, registry, ownedTypeMap, ownedTypeLookup);
929
987
  };
988
+ /**
989
+ * A brand as a value class that serializes and prints as the bare value.
990
+ */
991
+ const emitBrand = (writer, brand) => {
992
+ writer.line("@Serializable");
993
+ writer.line("@JvmInline");
994
+ writer.block(`value class ${brand.name}(val value: ${brand.rawType})`, () => {
995
+ writer.line(`override fun toString(): String = ${brand.rawType === "String" ? "value" : "value.toString()"}`);
996
+ });
997
+ };
930
998
  const emitTypes = (writer, types, ownedTypeMap = /* @__PURE__ */ new Map(), ownedTypeLookup = /* @__PURE__ */ new Map(), registry) => {
931
999
  for (const type of types) emitType(writer, type, ownedTypeMap, ownedTypeLookup, void 0, registry);
932
1000
  };
@@ -1002,7 +1070,7 @@ const emitOperationResultTypes = (writer, method, context) => {
1002
1070
  writer.line(") {");
1003
1071
  writer.indent(() => {
1004
1072
  writer.line("/** How far along the call is. */");
1005
- writer.line("enum class State { Running, Done, Failed }");
1073
+ writer.line("enum class State { Running, NeedsApproval, Done, Failed }");
1006
1074
  });
1007
1075
  writer.line("}");
1008
1076
  writer.blank();
@@ -1012,7 +1080,12 @@ const emitOperationResultTypes = (writer, method, context) => {
1012
1080
  writer.block("for (event in events)", () => {
1013
1081
  writer.line("when (event) {");
1014
1082
  writer.indent(() => {
1015
- writer.line("is Event.ToolCall -> calls[event.data.id] = (calls[event.data.id] ?: ToolCallRecord(event.data.id, event.data.name)).copy(call = event.data)");
1083
+ writer.line("is Event.ToolCall -> {");
1084
+ writer.indent(() => {
1085
+ writer.line("val tracked = (calls[event.data.id] ?: ToolCallRecord(event.data.id, event.data.name)).copy(call = event.data)");
1086
+ writer.line("calls[event.data.id] = if (event.data.needsApproval == true && tracked.state == ToolCallRecord.State.Running) tracked.copy(state = ToolCallRecord.State.NeedsApproval) else tracked");
1087
+ });
1088
+ writer.line("}");
1016
1089
  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)");
1017
1090
  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)");
1018
1091
  writer.line("else -> Unit");
@@ -1074,7 +1147,7 @@ const groupTypeRef = (operationName, className, context) => `${context.clientNam
1074
1147
  const groupMemberAccessor = (groupLabel, field) => `${groupLabel}.${escapeKeyword(field.name)}`;
1075
1148
  const groupClassField = (field) => {
1076
1149
  const typeExpression = optionalize(field.type, field.optional);
1077
- const defaultPart = field.optional ? " = null" : "";
1150
+ const defaultPart = defaultArgument(field);
1078
1151
  return `val ${escapeKeyword(field.name)}: ${typeExpression}${defaultPart}`;
1079
1152
  };
1080
1153
  const emitGroupClass = (writer, className, fields, method, context) => {
@@ -1133,13 +1206,13 @@ const methodChannels = (method) => {
1133
1206
  if (method.query.length > 0) channels.push({
1134
1207
  varName: "query",
1135
1208
  className: "Query",
1136
- required: method.query.some((field) => !field.optional),
1209
+ required: method.query.some((field) => !hasDefault(field)),
1137
1210
  fields: method.query
1138
1211
  });
1139
1212
  if (method.headers.length > 0) channels.push({
1140
1213
  varName: "headers",
1141
1214
  className: "Headers",
1142
- required: method.headers.some((field) => !field.optional),
1215
+ required: method.headers.some((field) => !hasDefault(field)),
1143
1216
  fields: method.headers
1144
1217
  });
1145
1218
  if (hasBodyGroup(method)) {
@@ -1188,7 +1261,7 @@ const emitArgsScaffolding = (writer, method, context) => {
1188
1261
  };
1189
1262
  const factorySignature = (channel) => channel.fields.map((field) => {
1190
1263
  const typeExpression = optionalize(field.type, field.optional);
1191
- const defaultPart = field.optional ? " = null" : "";
1264
+ const defaultPart = defaultArgument(field);
1192
1265
  return `${escapeKeyword(field.name)}: ${typeExpression}${defaultPart}`;
1193
1266
  }).join(", ");
1194
1267
  const factoryConstruction = (channel) => {
@@ -1245,10 +1318,16 @@ const emitBodyEncoding = (writer, method, context) => {
1245
1318
  if (body.kind === "multipart") {
1246
1319
  writer.line("val multipartBuilder = MultipartBody.Builder().setType(MultipartBody.FORM)");
1247
1320
  for (const field of body.multipartFields) {
1248
- const accessor = groupMemberAccessor("body", field);
1249
- const isFlattenedFile = body.flattened.find((flatField) => flatField.name === field.name)?.isFile === true;
1250
- if (field.isFile || isFlattenedFile) writer.line(`multipartBuilder.addFormDataPart(${stringLiteral(field.wireName)}, ${accessor}.filename, ${accessor}.data.toRequestBody(${accessor}.mimeType.toMediaType()))`);
1251
- else writer.line(`multipartBuilder.addFormDataPart(${stringLiteral(field.wireName)}, ${accessor}.toString())`);
1321
+ const flattenedField = body.flattened.find((flatField) => flatField.name === field.name);
1322
+ const isFile = field.isFile || flattenedField?.isFile === true;
1323
+ const append = (accessor) => {
1324
+ if (isFile) writer.line(`multipartBuilder.addFormDataPart(${stringLiteral(field.wireName)}, ${accessor}.filename, ${accessor}.data.toRequestBody(${accessor}.mimeType.toMediaType()))`);
1325
+ else writer.line(`multipartBuilder.addFormDataPart(${stringLiteral(field.wireName)}, ${accessor}.toString())`);
1326
+ };
1327
+ if (flattenedField?.optional === true) writer.block(`if (${groupMemberAccessor("body", field)} != null)`, () => {
1328
+ append(groupMemberAccessor("body", field));
1329
+ });
1330
+ else append(groupMemberAccessor("body", field));
1252
1331
  }
1253
1332
  writer.line("requestBody = multipartBuilder.build()");
1254
1333
  return;
@@ -1324,7 +1403,7 @@ const emitMethodBody = (writer, method, context) => {
1324
1403
  else setHeader(accessor);
1325
1404
  }
1326
1405
  writer.line("requestInterceptor?.invoke(requestBuilder)");
1327
- writer.line("val httpResponse = Kizuna.execute(client, requestBuilder.build())");
1406
+ writer.line("val httpResponse = Kizuna.send(client, requestBuilder.build(), retry)");
1328
1407
  if (method.stream) {
1329
1408
  emitStreamMethodTail(writer, method, context);
1330
1409
  return;
@@ -1344,7 +1423,7 @@ const emitMethodBody = (writer, method, context) => {
1344
1423
  writer.indent(() => {
1345
1424
  const resolved = resolveType(successResponse.type, method.operationName, context);
1346
1425
  writer.block("try", () => {
1347
- writer.line(`val payload = json.decodeFromString<${resolved}>(data.decodeToString())`);
1426
+ writer.line(`val payload = ${decodeBody(resolved, successResponse.isText)}`);
1348
1427
  const bodyExpr = isMultiSuccess ? `${operationRef}.Success.Status${successResponse.status}(payload)` : "payload";
1349
1428
  if (hasHeaders) {
1350
1429
  for (const field of successResponse.responseHeaders) writer.line(`val ${escapeKeyword(field.name)} = httpResponse.header(${stringLiteral(field.wireName)})`);
@@ -1381,7 +1460,7 @@ const emitErrorBranches = (writer, method, context) => {
1381
1460
  const resolved = resolveType(errorCase.type, method.operationName, context);
1382
1461
  writer.line("val payload = try {");
1383
1462
  writer.indent(() => {
1384
- writer.line(`json.decodeFromString<${resolved}>(data.decodeToString())`);
1463
+ writer.line(decodeBody(resolved));
1385
1464
  });
1386
1465
  writer.line(`} catch (error: Exception) { throw ${failureRef}.Decoding(error, statusCode, data) }`);
1387
1466
  writer.line(`throw ${failureRef}.${caseName}(body = payload)`);
@@ -1394,7 +1473,7 @@ const emitErrorBranches = (writer, method, context) => {
1394
1473
  const resolved = resolveType(errorCase.type, method.operationName, context);
1395
1474
  writer.line(`val ${errorCase.caseName} = try {`);
1396
1475
  writer.indent(() => {
1397
- writer.line(`json.decodeFromString<${resolved}>(data.decodeToString())`);
1476
+ writer.line(decodeBody(resolved));
1398
1477
  });
1399
1478
  writer.line("} catch (_: Exception) { null }");
1400
1479
  writer.line(`if (${errorCase.caseName} != null) throw ${failureRef}.${caseName}(body = ${errorCase.caseName})`);
@@ -1407,6 +1486,35 @@ const emitErrorBranches = (writer, method, context) => {
1407
1486
  }
1408
1487
  writer.line(`else -> throw ${failureRef}.Unexpected(statusCode = statusCode, data = data)`);
1409
1488
  };
1489
+ const IDEMPOTENT_METHODS = new Set([
1490
+ "GET",
1491
+ "HEAD",
1492
+ "OPTIONS",
1493
+ "PUT",
1494
+ "DELETE"
1495
+ ]);
1496
+ /**
1497
+ * Writes the reconnection an event stream reopens through and returns the argument handing it to `Kizuna.events`, or
1498
+ * nothing for a method a client may not resend.
1499
+ */
1500
+ const emitReopen = (writer, method, operationRef, status) => {
1501
+ if (!IDEMPOTENT_METHODS.has(method.method)) return "";
1502
+ closure(writer, "val reconnection = reconnect?.let { policy ->", () => {
1503
+ closure(writer, "Kizuna.Reconnection(policy) { lastEventId ->", () => {
1504
+ writer.line("val again = requestBuilder.build().newBuilder()");
1505
+ writer.line("if (lastEventId.isNotEmpty()) again.header(\"Last-Event-ID\", lastEventId)");
1506
+ writer.line("requestInterceptor?.invoke(again)");
1507
+ writer.line("val reopened = Kizuna.send(client, again.build(), retry)");
1508
+ writer.line("val eventStream = reopened.header(\"Content-Type\")?.lowercase()?.startsWith(\"text/event-stream\") == true");
1509
+ writer.block("when", () => {
1510
+ writer.line("reopened.code == 204 -> { reopened.close(); null }");
1511
+ writer.line(`reopened.code == ${status} && eventStream -> reopened`);
1512
+ writer.line(`else -> { reopened.close(); throw ${operationRef}.Failure.Unexpected(statusCode = reopened.code, data = ByteArray(0)) }`);
1513
+ });
1514
+ });
1515
+ });
1516
+ return ", reconnection";
1517
+ };
1410
1518
  const emitStreamMethodTail = (writer, method, context) => {
1411
1519
  const operationRef = `${context.clientName}.${method.operationName}`;
1412
1520
  const stream = method.stream;
@@ -1419,7 +1527,7 @@ const emitStreamMethodTail = (writer, method, context) => {
1419
1527
  else if (stream.events) {
1420
1528
  const events = stream.events;
1421
1529
  const elementType = streamElementType(method, context, "client");
1422
- closure(writer, `val body = Kizuna.events<${elementType}>(httpResponse) { event ->`, () => {
1530
+ closure(writer, `val body = Kizuna.events<${elementType}>(httpResponse${emitReopen(writer, method, operationRef, stream.status)}) { event ->`, () => {
1423
1531
  writer.block("when (event.event)", () => {
1424
1532
  for (const event of events) {
1425
1533
  const payloadType = resolveType(event.type, method.operationName, context);
@@ -1430,7 +1538,8 @@ const emitStreamMethodTail = (writer, method, context) => {
1430
1538
  });
1431
1539
  } else {
1432
1540
  const elementType = streamElementType(method, context, "client");
1433
- writer.line(`val body = Kizuna.events<${elementType}>(httpResponse) { event -> json.decodeFromString<${elementType}>(event.data) }`);
1541
+ const reconnection = emitReopen(writer, method, operationRef, stream.status);
1542
+ writer.line(`val body = Kizuna.events<${elementType}>(httpResponse${reconnection}) { event -> json.decodeFromString<${elementType}>(event.data) }`);
1434
1543
  }
1435
1544
  if (hasHeaders) {
1436
1545
  for (const field of successResponse.responseHeaders) writer.line(`val ${escapeKeyword(field.name)} = httpResponse.header(${stringLiteral(field.wireName)})`);
@@ -1476,7 +1585,7 @@ const emitSubClientMethod = (writer, method, context) => {
1476
1585
  };
1477
1586
  const emitSubClientClass = (writer, group, clientName, context) => {
1478
1587
  writer.blank();
1479
- writer.block(`class ${group.className}(private val client: OkHttpClient, private val baseUrl: String, private val json: Json, private val requestContextHeaders: Map<String, String>, private val requestInterceptor: (suspend (Request.Builder) -> Unit)?, private val responseInterceptor: (suspend (Request, Response) -> Unit)?)`, () => {
1588
+ writer.block(`class ${group.className}(private val client: OkHttpClient, private val baseUrl: String, private val json: Json, private val requestContextHeaders: Map<String, String>, private val requestInterceptor: (suspend (Request.Builder) -> Unit)?, private val responseInterceptor: (suspend (Request, Response) -> Unit)?, private val retry: ${clientName}.RetryPolicy?, private val reconnect: ${clientName}.ReconnectPolicy?)`, () => {
1480
1589
  for (const method of group.methods) {
1481
1590
  writer.blank();
1482
1591
  emitSubClientMethod(writer, method, context);
@@ -1488,10 +1597,12 @@ const closure = (writer, opener, body) => {
1488
1597
  writer.indent(body);
1489
1598
  writer.line("}");
1490
1599
  };
1491
- const emitKizunaStreaming = (writer) => {
1600
+ const emitKizunaStreaming = (writer, clientName) => {
1492
1601
  writer.blank();
1493
1602
  writer.line("data class ServerSentEvent(val event: String?, val data: String, val id: String?, val retry: Int?)");
1494
1603
  writer.blank();
1604
+ writer.line(`class Reconnection(val policy: ${clientName}.ReconnectPolicy, val reopen: suspend (String) -> Response?)`);
1605
+ writer.blank();
1495
1606
  writer.block("private suspend fun readLine(source: okio.BufferedSource): String?", () => {
1496
1607
  writer.line("return kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { source.readUtf8Line() }");
1497
1608
  });
@@ -1518,44 +1629,83 @@ const emitKizunaStreaming = (writer) => {
1518
1629
  });
1519
1630
  });
1520
1631
  writer.blank();
1521
- writer.block("fun serverSentEvents(response: Response): Flow<ServerSentEvent> = flow", () => {
1522
- closure(writer, "response.use { open ->", () => {
1523
- writer.line("val source = open.body?.source() ?: return@use");
1524
- writer.line("var eventType = \"\"");
1525
- writer.line("val dataLines = mutableListOf<String>()");
1526
- writer.line("var lastEventId = \"\"");
1527
- writer.line("var retry: Int? = null");
1528
- writer.block("while (true)", () => {
1529
- writer.line("val line = readLine(source) ?: break");
1530
- writer.block("if (line.isEmpty())", () => {
1531
- writer.block("if (dataLines.isNotEmpty())", () => {
1532
- writer.line("emit(ServerSentEvent(eventType.ifEmpty { null }, dataLines.joinToString(\"\\n\"), lastEventId.ifEmpty { null }, retry))");
1533
- writer.line("dataLines.clear()");
1534
- writer.line("retry = null");
1632
+ writer.line("private val LINE_ENDINGS = okio.ByteString.of('\\r'.code.toByte(), '\\n'.code.toByte())");
1633
+ writer.blank();
1634
+ writer.block("private suspend fun readEventLine(source: okio.BufferedSource): String?", () => {
1635
+ closure(writer, "return kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {", () => {
1636
+ writer.line("val end = source.indexOfElement(LINE_ENDINGS)");
1637
+ writer.block("if (end == -1L)", () => {
1638
+ writer.line("if (source.exhausted()) null else source.readUtf8()");
1639
+ });
1640
+ writer.block("else", () => {
1641
+ writer.line("val line = source.readUtf8(end)");
1642
+ writer.line("val carriageReturn = source.readByte() == '\\r'.code.toByte()");
1643
+ writer.line("if (carriageReturn && source.request(1) && source.buffer[0] == '\\n'.code.toByte()) source.skip(1)");
1644
+ writer.line("line");
1645
+ });
1646
+ });
1647
+ });
1648
+ writer.blank();
1649
+ writer.block("fun serverSentEvents(response: Response, reconnect: Reconnection?): Flow<ServerSentEvent> = flow", () => {
1650
+ writer.line("var lastEventId = \"\"");
1651
+ writer.line("var reconnectionTime = reconnect?.policy?.reconnectionTime ?: 3.seconds");
1652
+ writer.line("var current: Response? = response");
1653
+ writer.line("var attempts = 0");
1654
+ writer.line("var failure: Throwable? = null");
1655
+ writer.block("while (true)", () => {
1656
+ closure(writer, "current?.use { open ->", () => {
1657
+ writer.line("val source = open.body?.source() ?: return@use");
1658
+ writer.line("var eventType = \"\"");
1659
+ writer.line("val dataLines = mutableListOf<String>()");
1660
+ writer.line("var pendingId = lastEventId");
1661
+ writer.line("var retry: Int? = null");
1662
+ writer.line("var firstLine = true");
1663
+ writer.block("while (true)", () => {
1664
+ writer.line("val received = try { readEventLine(source) } catch (error: java.io.IOException) { failure = error; null } ?: break");
1665
+ writer.line("val line = if (firstLine) received.removePrefix(\"\\uFEFF\") else received");
1666
+ writer.line("firstLine = false");
1667
+ writer.block("if (line.isEmpty())", () => {
1668
+ writer.line("lastEventId = pendingId");
1669
+ writer.block("if (dataLines.isNotEmpty())", () => {
1670
+ writer.line("emit(ServerSentEvent(eventType.ifEmpty { null }, dataLines.joinToString(\"\\n\"), lastEventId.ifEmpty { null }, retry))");
1671
+ writer.line("attempts = 0");
1672
+ writer.line("failure = null");
1673
+ writer.line("dataLines.clear()");
1674
+ writer.line("retry = null");
1675
+ });
1676
+ writer.line("eventType = \"\"");
1677
+ writer.line("continue");
1678
+ });
1679
+ writer.line("if (line.startsWith(\":\")) continue");
1680
+ writer.line("val separator = line.indexOf(':')");
1681
+ writer.line("val field = if (separator == -1) line else line.substring(0, separator)");
1682
+ writer.line("val value = (if (separator == -1) \"\" else line.substring(separator + 1)).removePrefix(\" \")");
1683
+ writer.block("when (field)", () => {
1684
+ writer.line("\"event\" -> eventType = value");
1685
+ writer.line("\"data\" -> dataLines.add(value)");
1686
+ writer.line("\"id\" -> if (!value.contains('\\u0000')) pendingId = value");
1687
+ writer.line("\"retry\" -> if (value.isNotEmpty() && value.all { character -> character in '0'..'9' }) value.toIntOrNull()?.let { milliseconds -> retry = milliseconds; reconnectionTime = minOf(milliseconds.milliseconds, 3_600_000.milliseconds) }");
1535
1688
  });
1536
- writer.line("eventType = \"\"");
1537
- writer.line("continue");
1538
- });
1539
- writer.line("if (line.startsWith(\":\")) continue");
1540
- writer.line("val separator = line.indexOf(':')");
1541
- writer.line("val field = if (separator == -1) line else line.substring(0, separator)");
1542
- writer.line("val value = (if (separator == -1) \"\" else line.substring(separator + 1)).removePrefix(\" \")");
1543
- writer.block("when (field)", () => {
1544
- writer.line("\"event\" -> eventType = value");
1545
- writer.line("\"data\" -> dataLines.add(value)");
1546
- writer.line("\"id\" -> if (!value.contains('\\u0000')) lastEventId = value");
1547
- writer.line("\"retry\" -> if (value.isNotEmpty() && value.all { it.isDigit() }) retry = value.toIntOrNull()");
1548
1689
  });
1549
1690
  });
1691
+ writer.block("if (reconnect == null || attempts >= reconnect.policy.maximumAttempts)", () => {
1692
+ writer.line("failure?.let { throw it }");
1693
+ writer.line("return@flow");
1694
+ });
1695
+ writer.line("attempts += 1");
1696
+ writer.line("val ceiling = minOf(reconnect.policy.maximumDelay, reconnectionTime * Math.pow(2.0, (attempts - 1).toDouble()))");
1697
+ writer.line("val extra = (ceiling - reconnectionTime).coerceAtLeast(kotlin.time.Duration.ZERO)");
1698
+ writer.line("kotlinx.coroutines.delay(reconnectionTime + extra * Math.random())");
1699
+ writer.line("current = try { reconnect.reopen(lastEventId) ?: return@flow } catch (error: java.io.IOException) { failure = error; null }");
1550
1700
  });
1551
1701
  });
1552
1702
  writer.blank();
1553
- writer.line("fun <Event : Any> events(response: Response, decode: (ServerSentEvent) -> Event?): Flow<Event> = serverSentEvents(response).mapNotNull(decode)");
1703
+ writer.line("fun <Event : Any> events(response: Response, reconnect: Reconnection? = null, decode: (ServerSentEvent) -> Event?): Flow<Event> = serverSentEvents(response, reconnect).mapNotNull(decode)");
1554
1704
  };
1555
1705
  const emitKizunaObject = (writer, options) => {
1556
1706
  writer.blank();
1557
1707
  writer.block("private object Kizuna", () => {
1558
- if (options.streaming) emitKizunaStreaming(writer);
1708
+ if (options.streaming) emitKizunaStreaming(writer, options.clientName);
1559
1709
  writer.block("fun resolveUrl(baseUrl: String, path: String): HttpUrl.Builder", () => {
1560
1710
  writer.line("val base = baseUrl.toHttpUrl()");
1561
1711
  writer.line("val trimmedPath = path.trimStart('/')");
@@ -1581,6 +1731,47 @@ const emitKizunaObject = (writer, options) => {
1581
1731
  writer.line("}");
1582
1732
  });
1583
1733
  writer.blank();
1734
+ writer.block(`suspend fun send(client: OkHttpClient, request: Request, retry: ${options.clientName}.RetryPolicy?): Response`, () => {
1735
+ writer.line("val idempotent = request.method in setOf(\"GET\", \"HEAD\", \"OPTIONS\", \"PUT\", \"DELETE\")");
1736
+ writer.line("val policy = retry?.takeIf { idempotent && request.body?.isOneShot() != true }");
1737
+ writer.line("var attempt = 1");
1738
+ writer.block("while (true)", () => {
1739
+ writer.line("val response = try {");
1740
+ writer.line(" execute(client, request)");
1741
+ writer.line("} catch (error: java.io.IOException) {");
1742
+ writer.line(" val delay = policy?.let { retryDelay(it, attempt, null) } ?: throw error");
1743
+ writer.line(" kotlinx.coroutines.delay(delay)");
1744
+ writer.line(" attempt += 1");
1745
+ writer.line(" continue");
1746
+ writer.line("}");
1747
+ writer.line("val delay = policy?.let { retryDelay(it, attempt, response) } ?: return response");
1748
+ writer.line("response.close()");
1749
+ writer.line("kotlinx.coroutines.delay(delay)");
1750
+ writer.line("attempt += 1");
1751
+ });
1752
+ });
1753
+ writer.blank();
1754
+ writer.block(`fun retryDelay(policy: ${options.clientName}.RetryPolicy, attempt: Int, response: Response?): Long?`, () => {
1755
+ writer.line("if (attempt >= policy.maximumAttempts) return null");
1756
+ writer.line("val ceiling = minOf(policy.maximumDelay.inWholeMilliseconds, policy.initialDelay.inWholeMilliseconds shl (attempt - 1))");
1757
+ writer.line("val backoff = (Math.random() * ceiling).toLong()");
1758
+ writer.line("if (response == null) return backoff");
1759
+ writer.line("if (response.code != 429 && response.code != 503) return null");
1760
+ writer.line("val asked = retryAfter(response.header(\"Retry-After\")) ?: return backoff");
1761
+ writer.line("return if (asked <= policy.maximumDelay.inWholeMilliseconds) asked else null");
1762
+ });
1763
+ writer.blank();
1764
+ writer.block("fun retryAfter(header: String?): Long?", () => {
1765
+ writer.line("val value = header?.trim() ?: return null");
1766
+ writer.line("value.toLongOrNull()?.let { return if (it >= 0) it * 1000 else null }");
1767
+ writer.line("val date = try {");
1768
+ writer.line(" java.time.ZonedDateTime.parse(value, java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME)");
1769
+ writer.line("} catch (_: java.time.format.DateTimeParseException) {");
1770
+ writer.line(" return null");
1771
+ writer.line("}");
1772
+ writer.line("return maxOf(0L, date.toInstant().toEpochMilli() - System.currentTimeMillis())");
1773
+ });
1774
+ writer.blank();
1584
1775
  writer.block("suspend fun execute(client: OkHttpClient, request: Request): Response", () => {
1585
1776
  writer.line("return kotlinx.coroutines.suspendCancellableCoroutine { continuation ->");
1586
1777
  writer.indent(() => {
@@ -1608,20 +1799,48 @@ const emitClient = (writer, config, partition, context, typesByOperation, regist
1608
1799
  const allMethods = [...flatMethods, ...groups.flatMap((group) => group.methods)];
1609
1800
  const usesMultipart = allMethods.some((method) => method.body?.kind === "multipart");
1610
1801
  const contextFields = context.requestContextFields;
1611
- const contextRequired = contextFields.some((field) => !field.optional);
1802
+ const contextRequired = contextFields.some((field) => !hasDefault(field));
1612
1803
  const contextParam = contextFields.length > 0 ? `requestContext: RequestContext${contextRequired ? "" : " = RequestContext()"}, ` : "";
1613
1804
  writer.blank();
1614
- writer.block(`class ${clientName}(private val baseUrl: String, ${contextParam}private val client: OkHttpClient = OkHttpClient(), private val json: Json = Json { ignoreUnknownKeys = true }, private val requestInterceptor: (suspend (Request.Builder) -> Unit)? = null, private val responseInterceptor: (suspend (Request, Response) -> Unit)? = null)`, () => {
1805
+ writer.block(`class ${clientName}(private val baseUrl: String, ${contextParam}private val client: OkHttpClient = OkHttpClient(), private val json: Json = Json { ignoreUnknownKeys = true }, private val requestInterceptor: (suspend (Request.Builder) -> Unit)? = null, private val responseInterceptor: (suspend (Request, Response) -> Unit)? = null, private val retry: RetryPolicy? = null, private val reconnect: ReconnectPolicy? = null)`, () => {
1615
1806
  if (contextFields.length > 0) {
1616
1807
  writer.blank();
1617
1808
  writer.line("/** Values sent as headers on every request, from the api's request context. */");
1618
- emitConstructorClass(writer, "data class RequestContext", contextFields.map((field) => `val ${escapeKeyword(field.name)}: ${field.type}${field.optional ? " = null" : ""}`));
1809
+ emitConstructorClass(writer, "data class RequestContext", contextFields.map((field) => `val ${escapeKeyword(field.name)}: ${field.type}${defaultArgument(field)}`));
1619
1810
  writer.blank();
1620
1811
  writer.block("private val requestContextHeaders: Map<String, String> = buildMap", () => {
1621
1812
  for (const field of contextFields) if (field.optional) writer.line(`if (requestContext.${escapeKeyword(field.name)} != null) put(${stringLiteral(field.wireName)}, requestContext.${escapeKeyword(field.name)}!!)`);
1622
1813
  else writer.line(`put(${stringLiteral(field.wireName)}, requestContext.${escapeKeyword(field.name)})`);
1623
1814
  });
1624
1815
  }
1816
+ writer.blank();
1817
+ writer.line("/**");
1818
+ writer.line(" * Retries a GET, HEAD, OPTIONS, PUT or DELETE that failed on the network or was answered 429 or 503,");
1819
+ writer.line(" * waiting what Retry-After asks or backing off.");
1820
+ writer.line(" *");
1821
+ writer.line(" * @property maximumAttempts Attempts in all, the first included.");
1822
+ writer.line(" * @property initialDelay What the first backoff waits at most.");
1823
+ writer.line(" * @property maximumDelay What any wait may take.");
1824
+ writer.line(" */");
1825
+ emitConstructorClass(writer, "data class RetryPolicy", [
1826
+ "val maximumAttempts: Int = 3",
1827
+ "val initialDelay: kotlin.time.Duration = 500.milliseconds",
1828
+ "val maximumDelay: kotlin.time.Duration = 30.seconds"
1829
+ ]);
1830
+ writer.blank();
1831
+ writer.line("/**");
1832
+ writer.line(" * Reconnects an event stream on a GET, HEAD, OPTIONS, PUT or DELETE when its connection drops,");
1833
+ writer.line(" * sending the id of the last event as Last-Event-ID.");
1834
+ writer.line(" *");
1835
+ writer.line(" * @property maximumAttempts Reconnections in a row before the stream fails. An event received resets the count.");
1836
+ writer.line(" * @property reconnectionTime What to wait before reconnecting, until the server sends a retry field.");
1837
+ writer.line(" * @property maximumDelay What the wait may grow to after reconnections in a row that fail.");
1838
+ writer.line(" */");
1839
+ emitConstructorClass(writer, "data class ReconnectPolicy", [
1840
+ "val maximumAttempts: Int = 5",
1841
+ "val reconnectionTime: kotlin.time.Duration = 3.seconds",
1842
+ "val maximumDelay: kotlin.time.Duration = 30.seconds"
1843
+ ]);
1625
1844
  if (usesMultipart) {
1626
1845
  writer.blank();
1627
1846
  emitConstructorClass(writer, "data class MultipartFile", [
@@ -1677,7 +1896,7 @@ const emitClient = (writer, config, partition, context, typesByOperation, regist
1677
1896
  }
1678
1897
  if (groups.length > 0) for (const group of groups) {
1679
1898
  writer.blank();
1680
- writer.line(`val ${escapeKeyword(group.propertyName)} = ${group.className}(client, baseUrl, json, ${contextFields.length > 0 ? "requestContextHeaders" : "emptyMap()"}, requestInterceptor, responseInterceptor)`);
1899
+ writer.line(`val ${escapeKeyword(group.propertyName)} = ${group.className}(client, baseUrl, json, ${contextFields.length > 0 ? "requestContextHeaders" : "emptyMap()"}, requestInterceptor, responseInterceptor, retry, reconnect)`);
1681
1900
  }
1682
1901
  for (const method of flatMethods) {
1683
1902
  writer.blank();
@@ -1685,21 +1904,8 @@ const emitClient = (writer, config, partition, context, typesByOperation, regist
1685
1904
  }
1686
1905
  });
1687
1906
  };
1688
- /**
1689
- * Generate a Kotlin API client from a Kizuna api.
1690
- *
1691
- * @param api - What `defineConfig` assembled.
1692
- * @param config - Override the generated names:
1693
- * - `namespaceName`: the object wrapping shared types.
1694
- * - `packageName`: optional package declaration for the generated file.
1695
- */
1696
- const generateKotlinClient = (api, config) => {
1697
- const { namespaceName, packageName, camelCaseProperties = false, unknownEnumCase = false } = config;
1698
- const registry = new TypeRegistry(camelCaseProperties, unknownEnumCase);
1699
- const partition = kotlinGenerator(api, {
1700
- namespaceName,
1701
- registry
1702
- });
1907
+ const renderKotlinClient = (api, partition, registry, config) => {
1908
+ const { namespaceName, packageName, camelCaseProperties = false } = config;
1703
1909
  const allMethods = [...partition.flatMethods, ...partition.groups.flatMap((group) => group.methods)];
1704
1910
  const operationTypeMap = buildOperationTypeMap(allMethods, registry);
1705
1911
  const clientName = `${namespaceName}Client`;
@@ -1735,6 +1941,8 @@ const generateKotlinClient = (api, config) => {
1735
1941
  writer.line("import okhttp3.*");
1736
1942
  writer.line("import okhttp3.MediaType.Companion.toMediaType");
1737
1943
  writer.line("import okhttp3.RequestBody.Companion.toRequestBody");
1944
+ writer.line("import kotlin.time.Duration.Companion.milliseconds");
1945
+ writer.line("import kotlin.time.Duration.Companion.seconds");
1738
1946
  writer.line("import okhttp3.HttpUrl.Companion.toHttpUrl");
1739
1947
  writer.blank();
1740
1948
  if (registry.all().some((type) => type.kind === "enum-class")) {
@@ -1784,13 +1992,43 @@ const generateKotlinClient = (api, config) => {
1784
1992
  };
1785
1993
  writer.block(`object ${namespaceName}`, () => {
1786
1994
  emitTypes(writer, topLevelSharedTypes, ownedTypeMap, ownedTypeLookup, registry);
1995
+ for (const brand of registry.allBrands()) {
1996
+ writer.blank();
1997
+ emitBrand(writer, brand);
1998
+ }
1787
1999
  });
1788
2000
  emitClient(writer, { clientName }, partition, context, typesByOperation, registry);
1789
2001
  for (const group of partition.groups) emitSubClientClass(writer, group, clientName, context);
1790
- emitKizunaObject(writer, { streaming: usesStreaming });
2002
+ emitKizunaObject(writer, {
2003
+ streaming: usesStreaming,
2004
+ clientName
2005
+ });
1791
2006
  for (const warning of registry.warnings()) process.stderr.write(`[kizuna/kotlin] JsonElement fallback at ${warning}\n`);
1792
2007
  return writer.toString();
1793
2008
  };
2009
+ /**
2010
+ * The Kotlin client's walk: the routes into a partition, then the file.
2011
+ */
2012
+ const kotlinClientWalk = (api, config) => {
2013
+ const registry = new TypeRegistry(config.camelCaseProperties ?? false, config.unknownEnumCase ?? false);
2014
+ const routes = kotlinRoutesWalk({
2015
+ namespaceName: config.namespaceName,
2016
+ registry
2017
+ });
2018
+ return {
2019
+ processRoute: routes.processRoute,
2020
+ finalize: () => renderKotlinClient(api, routes.finalize(), registry, config)
2021
+ };
2022
+ };
2023
+ /**
2024
+ * Generate a Kotlin API client from a Kizuna api.
2025
+ *
2026
+ * @param api - What `defineConfig` assembled.
2027
+ * @param config - Override the generated names:
2028
+ * - `namespaceName`: the object wrapping shared types.
2029
+ * - `packageName`: optional package declaration for the generated file.
2030
+ */
2031
+ const generateKotlinClient = (api, config) => (0, kizunajs_generator.walkApi)(api, kotlinClientWalk(api, config), { skipHidden: true });
1794
2032
  //#endregion
1795
2033
  Object.defineProperty(exports, "generateKotlinClient", {
1796
2034
  enumerable: true,
@@ -1798,3 +2036,9 @@ Object.defineProperty(exports, "generateKotlinClient", {
1798
2036
  return generateKotlinClient;
1799
2037
  }
1800
2038
  });
2039
+ Object.defineProperty(exports, "kotlinClientWalk", {
2040
+ enumerable: true,
2041
+ get: function() {
2042
+ return kotlinClientWalk;
2043
+ }
2044
+ });