@kizunajs/swift 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.
- package/README.md +17 -1
- package/dist/cli.cjs +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/{generator-BpGEeivv.cjs → generator-BOrQ_XSd.cjs} +397 -92
- package/dist/{generator-DfFjWZhf.mjs → generator-CWrbZWB-.mjs} +393 -94
- package/dist/index.cjs +35 -8
- package/dist/index.d.cts +20 -30
- package/dist/index.d.mts +20 -30
- package/dist/index.mjs +34 -9
- package/package.json +8 -8
|
@@ -45,6 +45,7 @@ var TypeRegistry = class {
|
|
|
45
45
|
warningSet = /* @__PURE__ */ new Set();
|
|
46
46
|
explicitIds = /* @__PURE__ */ new Set();
|
|
47
47
|
unionVariantOwners = /* @__PURE__ */ new Map();
|
|
48
|
+
brands = /* @__PURE__ */ new Map();
|
|
48
49
|
usesAnyCodable = false;
|
|
49
50
|
constructor(camelCaseProperties = false, unknownEnumCase = false) {
|
|
50
51
|
this.camelCaseProperties = camelCaseProperties;
|
|
@@ -82,6 +83,15 @@ var TypeRegistry = class {
|
|
|
82
83
|
unionVariantOwner(payloadName) {
|
|
83
84
|
return this.unionVariantOwners.get(payloadName);
|
|
84
85
|
}
|
|
86
|
+
addBrand(brand) {
|
|
87
|
+
const existing = this.brands.get(brand.name);
|
|
88
|
+
if (existing !== void 0 && existing.rawType !== brand.rawType) throw new Error(`@kizunajs/swift: brand ${stringify(brand.name)} wraps both ${existing.rawType} and ${brand.rawType}. Give each its own name.`);
|
|
89
|
+
if (this.types.has(brand.name)) throw new Error(`@kizunajs/swift: brand ${stringify(brand.name)} has the same name as a model. Give each its own name.`);
|
|
90
|
+
this.brands.set(brand.name, brand);
|
|
91
|
+
}
|
|
92
|
+
allBrands() {
|
|
93
|
+
return Array.from(this.brands.values());
|
|
94
|
+
}
|
|
85
95
|
warnAnyCodable(hint, reason) {
|
|
86
96
|
this.usesAnyCodable = true;
|
|
87
97
|
this.warningSet.add(`${hint}: ${reason}`);
|
|
@@ -100,8 +110,7 @@ const propertyName = (key, camelCase) => {
|
|
|
100
110
|
if (!camel) return "field";
|
|
101
111
|
return /^[0-9]/.test(camel) ? `_${camel}` : camel;
|
|
102
112
|
};
|
|
103
|
-
const objectFields = (schema, registry, hint) => {
|
|
104
|
-
const shape = (0, kizunajs_generator.readObjectShape)(schema) ?? {};
|
|
113
|
+
const objectFields = (schema, registry, hint, shape = (0, kizunajs_generator.readObjectShape)(schema) ?? {}) => {
|
|
105
114
|
const fields = [];
|
|
106
115
|
const seen = /* @__PURE__ */ new Map();
|
|
107
116
|
for (const [key, value] of Object.entries(shape)) {
|
|
@@ -116,6 +125,7 @@ const objectFields = (schema, registry, hint) => {
|
|
|
116
125
|
wireName: key,
|
|
117
126
|
type: result.expression,
|
|
118
127
|
optional: result.optional,
|
|
128
|
+
requiredNullable: result.requiredNullable,
|
|
119
129
|
description: (0, kizunajs_generator.readMetaDescription)(value),
|
|
120
130
|
isFile: result.isFile,
|
|
121
131
|
deprecated: deprecation !== void 0,
|
|
@@ -125,7 +135,29 @@ const objectFields = (schema, registry, hint) => {
|
|
|
125
135
|
return fields;
|
|
126
136
|
};
|
|
127
137
|
const stringify = (value) => JSON.stringify(value);
|
|
138
|
+
const BRANDABLE_TYPES = new Set([
|
|
139
|
+
"String",
|
|
140
|
+
"Int",
|
|
141
|
+
"Int64",
|
|
142
|
+
"Double",
|
|
143
|
+
"Bool",
|
|
144
|
+
"Date"
|
|
145
|
+
]);
|
|
128
146
|
const mapType = (schema, registry, hint) => {
|
|
147
|
+
const result = mapUnbrandedType(schema, registry, hint);
|
|
148
|
+
const brand = (0, kizunajs_generator.readMetaBrand)(schema);
|
|
149
|
+
if (brand === void 0 || !BRANDABLE_TYPES.has(result.expression)) return result;
|
|
150
|
+
const name = (0, kizunajs_generator.sanitizeIdentifier)(brand);
|
|
151
|
+
registry.addBrand({
|
|
152
|
+
name,
|
|
153
|
+
rawType: result.expression
|
|
154
|
+
});
|
|
155
|
+
return {
|
|
156
|
+
expression: name,
|
|
157
|
+
optional: false
|
|
158
|
+
};
|
|
159
|
+
};
|
|
160
|
+
const mapUnbrandedType = (schema, registry, hint) => {
|
|
129
161
|
if ((0, kizunajs_generator.isFileSchema)(schema)) return {
|
|
130
162
|
expression: "MultipartFile",
|
|
131
163
|
optional: false,
|
|
@@ -135,6 +167,8 @@ const mapType = (schema, registry, hint) => {
|
|
|
135
167
|
expression: "Foundation.Data",
|
|
136
168
|
optional: false
|
|
137
169
|
};
|
|
170
|
+
const model = (0, kizunajs_generator.readModelSchema)(schema);
|
|
171
|
+
if (model !== void 0 && model !== schema) return mapUnbrandedType(model, registry, hint);
|
|
138
172
|
const id = (0, kizunajs_generator.readMetaId)(schema);
|
|
139
173
|
const def = (0, kizunajs_generator.readDef)(schema);
|
|
140
174
|
const discriminated = (0, kizunajs_generator.readDiscriminatedUnion)(schema);
|
|
@@ -205,6 +239,7 @@ const mapType = (schema, registry, hint) => {
|
|
|
205
239
|
return {
|
|
206
240
|
expression: innerResult.expression.endsWith("?") ? innerResult.expression : `${innerResult.expression}?`,
|
|
207
241
|
optional: true,
|
|
242
|
+
requiredNullable: nullable && !optional,
|
|
208
243
|
isFile: innerResult.isFile
|
|
209
244
|
};
|
|
210
245
|
}
|
|
@@ -253,8 +288,9 @@ const mapType = (schema, registry, hint) => {
|
|
|
253
288
|
optional: false
|
|
254
289
|
};
|
|
255
290
|
}
|
|
291
|
+
const elementType = mapType(element, registry, `${hint}Item`).expression.replace(/\?$/, "");
|
|
256
292
|
return {
|
|
257
|
-
expression: `[${
|
|
293
|
+
expression: `[${(0, kizunajs_generator.unwrapOptionalWrappers)(element).nullable ? `${elementType}?` : elementType}]`,
|
|
258
294
|
optional: false
|
|
259
295
|
};
|
|
260
296
|
}
|
|
@@ -388,6 +424,7 @@ const sanitizeCaseName = (literal) => {
|
|
|
388
424
|
const collectObjectFields = (schema, registry, hint) => {
|
|
389
425
|
return objectFields(schema, registry, hint);
|
|
390
426
|
};
|
|
427
|
+
const hasDefault = (field) => field.optional && field.requiredNullable !== true;
|
|
391
428
|
const objectFieldCount = (schema) => {
|
|
392
429
|
return Object.keys((0, kizunajs_generator.readObjectShape)(schema) ?? {}).length;
|
|
393
430
|
};
|
|
@@ -556,7 +593,7 @@ const buildRouteMethod = (routeKey, route, registry, deprecated, deprecationMess
|
|
|
556
593
|
stream
|
|
557
594
|
};
|
|
558
595
|
};
|
|
559
|
-
const
|
|
596
|
+
const swiftRoutesWalk = (options) => {
|
|
560
597
|
const flatMethods = [];
|
|
561
598
|
const groupMap = /* @__PURE__ */ new Map();
|
|
562
599
|
return {
|
|
@@ -588,7 +625,7 @@ const swiftGenerator = (0, kizunajs_generator.createGenerator)((options, _api) =
|
|
|
588
625
|
};
|
|
589
626
|
}
|
|
590
627
|
};
|
|
591
|
-
}
|
|
628
|
+
};
|
|
592
629
|
const SWIFT_KEYWORDS = new Set([
|
|
593
630
|
"associatedtype",
|
|
594
631
|
"class",
|
|
@@ -664,6 +701,10 @@ const sanitizeEnumCaseName = (value) => {
|
|
|
664
701
|
if (!camel) return "_";
|
|
665
702
|
return /^[0-9]/.test(camel) ? `_${camel}` : camel;
|
|
666
703
|
};
|
|
704
|
+
const defaultArgument = (field) => {
|
|
705
|
+
if (!hasDefault(field)) return "";
|
|
706
|
+
return " = nil";
|
|
707
|
+
};
|
|
667
708
|
const optionalize = (type, optional) => {
|
|
668
709
|
if (!optional) return type;
|
|
669
710
|
return type.endsWith("?") ? type : `${type}?`;
|
|
@@ -678,7 +719,7 @@ const emitNamedFactory = (writer, factoryName, fields, buildExpression) => {
|
|
|
678
719
|
}
|
|
679
720
|
const params = fields.map((field) => {
|
|
680
721
|
const typeExpression = optionalize(field.type, field.optional);
|
|
681
|
-
const defaultPart = field
|
|
722
|
+
const defaultPart = defaultArgument(field);
|
|
682
723
|
return `${escapeKeyword(field.name)}: ${typeExpression}${defaultPart}`;
|
|
683
724
|
});
|
|
684
725
|
const args = fields.map((field) => `${field.name}: ${escapeKeyword(field.name)}`).join(", ");
|
|
@@ -701,7 +742,7 @@ const emitMemberwiseInit = (writer, fields, assignmentTarget = (field) => escape
|
|
|
701
742
|
}
|
|
702
743
|
const params = fields.map((field) => {
|
|
703
744
|
const typeExpression = optionalize(field.type, field.optional);
|
|
704
|
-
const defaultPart = field
|
|
745
|
+
const defaultPart = defaultArgument(field);
|
|
705
746
|
return `${escapeKeyword(field.name)}: ${typeExpression}${defaultPart}`;
|
|
706
747
|
});
|
|
707
748
|
if (params.length === 1) {
|
|
@@ -835,7 +876,9 @@ const emitStruct = (writer, type, context, ownedTypeMap, ownedTypeLookup, regist
|
|
|
835
876
|
...field,
|
|
836
877
|
type: resolveOwnedType(field.type)
|
|
837
878
|
}));
|
|
838
|
-
const
|
|
879
|
+
const needsEncode = !hasFile && type.fields.some((field) => field.requiredNullable === true);
|
|
880
|
+
const needsCodingKeys = needsEncode || !hasFile && type.fields.some((field) => field.name !== field.wireName || SWIFT_KEYWORDS.has(field.name) || field.deprecated === true);
|
|
881
|
+
const storageName = (field) => field.deprecated ? deprecatedStorageName(field, type.fields) : escapeKeyword(field.name);
|
|
839
882
|
writer.block(`public struct ${type.name}: ${conformances}`, () => {
|
|
840
883
|
emitOwnedTypes(writer, lookupName, context, ownedTypeMap, ownedTypeLookup);
|
|
841
884
|
for (const field of type.fields) {
|
|
@@ -858,8 +901,43 @@ const emitStruct = (writer, type, context, ownedTypeMap, ownedTypeLookup, regist
|
|
|
858
901
|
else writer.line(`case ${escapeKeyword(field.name)} = ${stringLiteral(field.wireName)}`);
|
|
859
902
|
});
|
|
860
903
|
}
|
|
904
|
+
if (needsEncode) {
|
|
905
|
+
writer.blank();
|
|
906
|
+
writer.block("public func encode(to encoder: Encoder) throws", () => {
|
|
907
|
+
writer.line("var container = encoder.container(keyedBy: CodingKeys.self)");
|
|
908
|
+
for (const field of type.fields) {
|
|
909
|
+
const encodeCall = field.optional && field.requiredNullable !== true ? "encodeIfPresent" : "encode";
|
|
910
|
+
writer.line(`try container.${encodeCall}(${storageName(field)}, forKey: .${storageName(field)})`);
|
|
911
|
+
}
|
|
912
|
+
});
|
|
913
|
+
}
|
|
914
|
+
writer.blank();
|
|
915
|
+
emitMemberwiseInit(writer, adjustedFields, storageName);
|
|
916
|
+
});
|
|
917
|
+
};
|
|
918
|
+
/**
|
|
919
|
+
* A brand as a struct around its value, encoded as the bare value.
|
|
920
|
+
*/
|
|
921
|
+
const emitBrand = (writer, brand) => {
|
|
922
|
+
writer.block(`public struct ${brand.name}: RawRepresentable, Codable, Hashable, Sendable`, () => {
|
|
923
|
+
writer.line(`public let rawValue: ${brand.rawType}`);
|
|
924
|
+
writer.blank();
|
|
925
|
+
writer.block(`public init(rawValue: ${brand.rawType})`, () => {
|
|
926
|
+
writer.line("self.rawValue = rawValue");
|
|
927
|
+
});
|
|
928
|
+
writer.blank();
|
|
929
|
+
writer.block(`public init(_ rawValue: ${brand.rawType})`, () => {
|
|
930
|
+
writer.line("self.rawValue = rawValue");
|
|
931
|
+
});
|
|
932
|
+
writer.blank();
|
|
933
|
+
writer.block("public init(from decoder: Decoder) throws", () => {
|
|
934
|
+
writer.line(`rawValue = try decoder.singleValueContainer().decode(${brand.rawType}.self)`);
|
|
935
|
+
});
|
|
861
936
|
writer.blank();
|
|
862
|
-
|
|
937
|
+
writer.block("public func encode(to encoder: Encoder) throws", () => {
|
|
938
|
+
writer.line("var container = encoder.singleValueContainer()");
|
|
939
|
+
writer.line("try container.encode(rawValue)");
|
|
940
|
+
});
|
|
863
941
|
});
|
|
864
942
|
};
|
|
865
943
|
const emitDiscriminatedEnum = (writer, type, context, registryName, ownedTypeMap, ownedTypeLookup) => {
|
|
@@ -872,7 +950,7 @@ const emitDiscriminatedEnum = (writer, type, context, registryName, ownedTypeMap
|
|
|
872
950
|
if (!payloadStruct) continue;
|
|
873
951
|
const isDiscriminator = (field) => field.wireName === type.discriminator || field.name === type.discriminator;
|
|
874
952
|
const factoryParams = payloadStruct.fields.filter((field) => !isDiscriminator(field)).map((field) => {
|
|
875
|
-
const defaultPart = field
|
|
953
|
+
const defaultPart = defaultArgument(field);
|
|
876
954
|
const fieldType = (ownedTypeMap && relativeOwnedPath(field.type, ownedTypeMap, lookupName)) ?? resolveType(field.type, void 0, context);
|
|
877
955
|
return `${escapeKeyword(field.name)}: ${optionalize(fieldType, field.optional)}${defaultPart}`;
|
|
878
956
|
}).join(", ");
|
|
@@ -955,13 +1033,33 @@ const SWIFT_PRIMITIVE_TYPES = new Set([
|
|
|
955
1033
|
"Void",
|
|
956
1034
|
"Foundation.Data"
|
|
957
1035
|
]);
|
|
1036
|
+
/**
|
|
1037
|
+
* Where a dictionary's key ends and its value begins, or -1 for an array.
|
|
1038
|
+
*/
|
|
1039
|
+
const dictionarySeparator = (inner) => {
|
|
1040
|
+
let depth = 0;
|
|
1041
|
+
for (let index = 0; index < inner.length; index += 1) {
|
|
1042
|
+
const character = inner[index];
|
|
1043
|
+
if (character === "[") depth += 1;
|
|
1044
|
+
else if (character === "]") depth -= 1;
|
|
1045
|
+
else if (character === ":" && depth === 0) return index;
|
|
1046
|
+
}
|
|
1047
|
+
return -1;
|
|
1048
|
+
};
|
|
958
1049
|
const resolveType = (typeName, currentOperation, context, scope = "actor") => {
|
|
959
1050
|
const { operationTypeMap, namespaceName, clientName, fileLevelTypeNames } = context;
|
|
960
1051
|
const optional = typeName.endsWith("?");
|
|
961
1052
|
const base = optional ? typeName.slice(0, -1) : typeName;
|
|
962
1053
|
if (SWIFT_PRIMITIVE_TYPES.has(base)) return typeName;
|
|
963
1054
|
if (base.startsWith("[") && base.endsWith("]")) {
|
|
964
|
-
const
|
|
1055
|
+
const inner = base.slice(1, -1);
|
|
1056
|
+
const separator = dictionarySeparator(inner);
|
|
1057
|
+
if (separator !== -1) {
|
|
1058
|
+
const key = resolveType(inner.slice(0, separator).trim(), currentOperation, context, scope);
|
|
1059
|
+
const value = resolveType(inner.slice(separator + 1).trim(), currentOperation, context, scope);
|
|
1060
|
+
return optional ? `[${key}: ${value}]?` : `[${key}: ${value}]`;
|
|
1061
|
+
}
|
|
1062
|
+
const resolved = resolveType(inner, currentOperation, context, scope);
|
|
965
1063
|
return optional ? `[${resolved}]?` : `[${resolved}]`;
|
|
966
1064
|
}
|
|
967
1065
|
if (base === "MultipartFile" || base === "ValidationError" || base === "ValidationIssue") {
|
|
@@ -1038,6 +1136,8 @@ const emitToolTracking = (writer, method) => {
|
|
|
1038
1136
|
writer.line("/// How far along the call is.");
|
|
1039
1137
|
writer.block("public enum State: Sendable, Equatable", () => {
|
|
1040
1138
|
writer.line("case running");
|
|
1139
|
+
writer.line("/// The call waits for the person to approve it.");
|
|
1140
|
+
writer.line("case needsApproval");
|
|
1041
1141
|
writer.line("case done");
|
|
1042
1142
|
writer.line("case failed");
|
|
1043
1143
|
});
|
|
@@ -1070,6 +1170,9 @@ const emitToolTracking = (writer, method) => {
|
|
|
1070
1170
|
writer.line("case .tool_call(let payload):");
|
|
1071
1171
|
writer.line(" var tracked = at(payload.id, payload.name)");
|
|
1072
1172
|
writer.line(" tracked.call = payload");
|
|
1173
|
+
writer.line(" if payload.needsApproval == true, tracked.state == .running {");
|
|
1174
|
+
writer.line(" tracked.state = .needsApproval");
|
|
1175
|
+
writer.line(" }");
|
|
1073
1176
|
writer.line(" calls[payload.id] = tracked");
|
|
1074
1177
|
}
|
|
1075
1178
|
if (names.has("tool_result")) {
|
|
@@ -1231,7 +1334,7 @@ const closure = (writer, opener, body) => {
|
|
|
1231
1334
|
writer.indent(body);
|
|
1232
1335
|
writer.line("}");
|
|
1233
1336
|
};
|
|
1234
|
-
const emitKizunaStreaming = (writer) => {
|
|
1337
|
+
const emitKizunaStreaming = (writer, clientName) => {
|
|
1235
1338
|
writer.blank();
|
|
1236
1339
|
writer.block("struct ServerSentEvent: Sendable", () => {
|
|
1237
1340
|
writer.line("let event: String?");
|
|
@@ -1240,21 +1343,44 @@ const emitKizunaStreaming = (writer) => {
|
|
|
1240
1343
|
writer.line("let retry: Int?");
|
|
1241
1344
|
});
|
|
1242
1345
|
writer.blank();
|
|
1243
|
-
writer.block("
|
|
1346
|
+
writer.block("struct Reconnection: Sendable", () => {
|
|
1347
|
+
writer.line(`let policy: ${clientName}.ReconnectPolicy`);
|
|
1348
|
+
writer.line("let reopen: @Sendable (String) async throws -> URLSession.AsyncBytes?");
|
|
1349
|
+
});
|
|
1350
|
+
writer.blank();
|
|
1351
|
+
writer.block(`static func open<Failure: KizunaFailure>(_ request: inout URLRequest, session: URLSession, retry: ${clientName}.RetryPolicy?, requestMiddleware: (@Sendable (inout URLRequest) async throws -> Void)?, responseMiddleware: (@Sendable (URLRequest, Foundation.Data, URLResponse) async -> Void)?, failure: Failure.Type) async throws(Failure) -> (URLSession.AsyncBytes, Int, HTTPURLResponse)`, () => {
|
|
1244
1352
|
writer.line("if let requestMiddleware {");
|
|
1245
1353
|
writer.line(" do { try await requestMiddleware(&request) }");
|
|
1246
1354
|
writer.line(" catch is CancellationError { throw Failure.cancelled }");
|
|
1247
1355
|
writer.line(" catch let error as URLError where error.code == .cancelled { throw Failure.cancelled }");
|
|
1248
1356
|
writer.line(" catch { throw Failure.requestFailed(error) }");
|
|
1249
1357
|
writer.line("}");
|
|
1250
|
-
writer.line("let
|
|
1251
|
-
writer.line("
|
|
1252
|
-
writer.
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1358
|
+
writer.line("let policy = retryPolicy(for: request, retry)");
|
|
1359
|
+
writer.line("var attempt = 1");
|
|
1360
|
+
writer.block("while true", () => {
|
|
1361
|
+
writer.line("let bytes: URLSession.AsyncBytes");
|
|
1362
|
+
writer.line("let response: URLResponse");
|
|
1363
|
+
writer.line("do { (bytes, response) = try await session.bytes(for: request) }");
|
|
1364
|
+
writer.line("catch is CancellationError { throw Failure.cancelled }");
|
|
1365
|
+
writer.line("catch let error as URLError where error.code == .cancelled { throw Failure.cancelled }");
|
|
1366
|
+
writer.line("catch {");
|
|
1367
|
+
writer.line(" if let policy, let delay = retryDelay(policy, attempt: attempt, response: nil) {");
|
|
1368
|
+
writer.line(" try await pause(delay, failure: Failure.self)");
|
|
1369
|
+
writer.line(" attempt += 1");
|
|
1370
|
+
writer.line(" continue");
|
|
1371
|
+
writer.line(" }");
|
|
1372
|
+
writer.line(" throw Failure.requestFailed(error)");
|
|
1373
|
+
writer.line("}");
|
|
1374
|
+
writer.line("if let responseMiddleware { await responseMiddleware(request, Foundation.Data(), response) }");
|
|
1375
|
+
writer.line("guard let httpResponse = response as? HTTPURLResponse else { throw Failure.invalidResponse }");
|
|
1376
|
+
writer.line("if let policy, let delay = retryDelay(policy, attempt: attempt, response: httpResponse) {");
|
|
1377
|
+
writer.line(" bytes.task.cancel()");
|
|
1378
|
+
writer.line(" try await pause(delay, failure: Failure.self)");
|
|
1379
|
+
writer.line(" attempt += 1");
|
|
1380
|
+
writer.line(" continue");
|
|
1381
|
+
writer.line("}");
|
|
1382
|
+
writer.line("return (bytes, httpResponse.statusCode, httpResponse)");
|
|
1383
|
+
});
|
|
1258
1384
|
});
|
|
1259
1385
|
writer.blank();
|
|
1260
1386
|
writer.block("static func collect<Failure: KizunaFailure>(_ bytes: URLSession.AsyncBytes, failure: Failure.Type) async throws(Failure) -> Foundation.Data", () => {
|
|
@@ -1314,56 +1440,97 @@ const emitKizunaStreaming = (writer) => {
|
|
|
1314
1440
|
});
|
|
1315
1441
|
});
|
|
1316
1442
|
writer.blank();
|
|
1317
|
-
writer.block("static func serverSentEvents(_
|
|
1443
|
+
writer.block("static func serverSentEvents(_ first: URLSession.AsyncBytes, reconnect: Reconnection?) -> AsyncThrowingStream<ServerSentEvent, Swift.Error>", () => {
|
|
1318
1444
|
closure(writer, "AsyncThrowingStream { continuation in", () => {
|
|
1319
1445
|
writer.block("let task = Task", () => {
|
|
1320
|
-
writer.line("var eventType = \"\"");
|
|
1321
|
-
writer.line("var dataLines: [String] = []");
|
|
1322
1446
|
writer.line("var lastEventId = \"\"");
|
|
1323
|
-
writer.line("var
|
|
1324
|
-
writer.
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
writer.line("
|
|
1330
|
-
writer.line("
|
|
1331
|
-
writer.line("
|
|
1332
|
-
writer.line("
|
|
1333
|
-
writer.line("
|
|
1334
|
-
writer.
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1447
|
+
writer.line("var reconnectionTime = reconnect?.policy.reconnectionTime ?? 3");
|
|
1448
|
+
writer.line("var bytes: URLSession.AsyncBytes? = first");
|
|
1449
|
+
writer.line("var attempts = 0");
|
|
1450
|
+
writer.line("var failure: Swift.Error? = nil");
|
|
1451
|
+
writer.block("while true", () => {
|
|
1452
|
+
writer.block("if let current = bytes", () => {
|
|
1453
|
+
writer.line("var eventType = \"\"");
|
|
1454
|
+
writer.line("var dataLines: [String] = []");
|
|
1455
|
+
writer.line("var pendingId = lastEventId");
|
|
1456
|
+
writer.line("var retry: Int? = nil");
|
|
1457
|
+
writer.line("var firstLine = true");
|
|
1458
|
+
writer.block("do", () => {
|
|
1459
|
+
writer.block("for try await received in lines(current)", () => {
|
|
1460
|
+
writer.line("let line = firstLine && received.hasPrefix(\"\\u{FEFF}\") ? String(received.dropFirst()) : received");
|
|
1461
|
+
writer.line("firstLine = false");
|
|
1462
|
+
writer.line("if line.isEmpty {");
|
|
1463
|
+
writer.line(" lastEventId = pendingId");
|
|
1464
|
+
writer.line(" if !dataLines.isEmpty {");
|
|
1465
|
+
writer.line(" continuation.yield(ServerSentEvent(event: eventType.isEmpty ? nil : eventType, data: dataLines.joined(separator: \"\\n\"), id: lastEventId.isEmpty ? nil : lastEventId, retry: retry))");
|
|
1466
|
+
writer.line(" attempts = 0");
|
|
1467
|
+
writer.line(" failure = nil");
|
|
1468
|
+
writer.line(" dataLines = []");
|
|
1469
|
+
writer.line(" retry = nil");
|
|
1470
|
+
writer.line(" }");
|
|
1471
|
+
writer.line(" eventType = \"\"");
|
|
1472
|
+
writer.line(" continue");
|
|
1473
|
+
writer.line("}");
|
|
1474
|
+
writer.line("if line.hasPrefix(\":\") { continue }");
|
|
1475
|
+
writer.line("let field: Substring");
|
|
1476
|
+
writer.line("var value: Substring");
|
|
1477
|
+
writer.line("if let separator = line.firstIndex(of: \":\") {");
|
|
1478
|
+
writer.line(" field = line[..<separator]");
|
|
1479
|
+
writer.line(" value = line[line.index(after: separator)...]");
|
|
1480
|
+
writer.line(" if value.hasPrefix(\" \") { value = value.dropFirst() }");
|
|
1481
|
+
writer.line("} else {");
|
|
1482
|
+
writer.line(" field = Substring(line)");
|
|
1483
|
+
writer.line(" value = \"\"");
|
|
1484
|
+
writer.line("}");
|
|
1485
|
+
writer.line("switch field {");
|
|
1486
|
+
writer.line("case \"event\": eventType = String(value)");
|
|
1487
|
+
writer.line("case \"data\": dataLines.append(String(value))");
|
|
1488
|
+
writer.line("case \"id\": if !value.contains(\"\\0\") { pendingId = String(value) }");
|
|
1489
|
+
writer.line("case \"retry\": if !value.isEmpty, value.allSatisfy({ $0.isASCII && $0.isNumber }), let milliseconds = Int(value) { retry = milliseconds; reconnectionTime = min(TimeInterval(milliseconds) / 1000, 3600) }");
|
|
1490
|
+
writer.line("default: break");
|
|
1491
|
+
writer.line("}");
|
|
1492
|
+
});
|
|
1493
|
+
});
|
|
1494
|
+
writer.line("catch { failure = error }");
|
|
1495
|
+
});
|
|
1496
|
+
writer.line("guard let reconnect, !Task.isCancelled, attempts < reconnect.policy.maximumAttempts else {");
|
|
1497
|
+
writer.line(" continuation.finish(throwing: failure)");
|
|
1498
|
+
writer.line(" return");
|
|
1499
|
+
writer.line("}");
|
|
1500
|
+
writer.line("attempts += 1");
|
|
1501
|
+
writer.line("let ceiling = min(reconnect.policy.maximumDelay, reconnectionTime * pow(2, Double(attempts - 1)))");
|
|
1502
|
+
writer.line("let delay = max(0, reconnectionTime) + Double.random(in: 0...max(0, ceiling - reconnectionTime))");
|
|
1503
|
+
writer.line("do { try await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000)) }");
|
|
1504
|
+
writer.line("catch {");
|
|
1505
|
+
writer.line(" continuation.finish(throwing: failure)");
|
|
1506
|
+
writer.line(" return");
|
|
1507
|
+
writer.line("}");
|
|
1508
|
+
writer.block("do", () => {
|
|
1509
|
+
writer.line("guard let reopened = try await reconnect.reopen(lastEventId) else {");
|
|
1510
|
+
writer.line(" continuation.finish()");
|
|
1511
|
+
writer.line(" return");
|
|
1352
1512
|
writer.line("}");
|
|
1513
|
+
writer.line("bytes = reopened");
|
|
1514
|
+
});
|
|
1515
|
+
writer.block("catch let error as URLError", () => {
|
|
1516
|
+
writer.line("failure = error");
|
|
1517
|
+
writer.line("bytes = nil");
|
|
1518
|
+
});
|
|
1519
|
+
writer.block("catch", () => {
|
|
1520
|
+
writer.line("continuation.finish(throwing: error)");
|
|
1521
|
+
writer.line("return");
|
|
1353
1522
|
});
|
|
1354
|
-
writer.line("continuation.finish()");
|
|
1355
1523
|
});
|
|
1356
|
-
writer.line("catch { continuation.finish(throwing: error) }");
|
|
1357
1524
|
});
|
|
1358
1525
|
writer.line("continuation.onTermination = { _ in task.cancel() }");
|
|
1359
1526
|
});
|
|
1360
1527
|
});
|
|
1361
1528
|
writer.blank();
|
|
1362
|
-
writer.block("static func events<Event: Sendable>(_ bytes: URLSession.AsyncBytes, using decoder: JSONDecoder, _ decode: @escaping @Sendable (ServerSentEvent, JSONDecoder) throws -> Event?) -> AsyncThrowingStream<Event, Swift.Error>", () => {
|
|
1529
|
+
writer.block("static func events<Event: Sendable>(_ bytes: URLSession.AsyncBytes, using decoder: JSONDecoder, reconnect: Reconnection? = nil, _ decode: @escaping @Sendable (ServerSentEvent, JSONDecoder) throws -> Event?) -> AsyncThrowingStream<Event, Swift.Error>", () => {
|
|
1363
1530
|
closure(writer, "AsyncThrowingStream { continuation in", () => {
|
|
1364
1531
|
writer.block("let task = Task", () => {
|
|
1365
1532
|
writer.block("do", () => {
|
|
1366
|
-
writer.block("for try await event in serverSentEvents(bytes)", () => {
|
|
1533
|
+
writer.block("for try await event in serverSentEvents(bytes, reconnect: reconnect)", () => {
|
|
1367
1534
|
writer.line("if let decoded = try decode(event, decoder) { continuation.yield(decoded) }");
|
|
1368
1535
|
});
|
|
1369
1536
|
writer.line("continuation.finish()");
|
|
@@ -1458,22 +1625,68 @@ const emitKizunaNamespace = (writer, options) => {
|
|
|
1458
1625
|
writer.line("catch { throw Failure.requestFailed(error) }");
|
|
1459
1626
|
});
|
|
1460
1627
|
writer.blank();
|
|
1461
|
-
writer.block(
|
|
1628
|
+
writer.block(`static func send<Failure: KizunaFailure>(_ request: inout URLRequest, session: URLSession, retry: ${options.clientName}.RetryPolicy?, requestMiddleware: (@Sendable (inout URLRequest) async throws -> Void)?, responseMiddleware: (@Sendable (URLRequest, Foundation.Data, URLResponse) async -> Void)?, failure: Failure.Type) async throws(Failure) -> (Foundation.Data, Int, HTTPURLResponse)`, () => {
|
|
1462
1629
|
writer.line("if let requestMiddleware {");
|
|
1463
1630
|
writer.line(" do { try await requestMiddleware(&request) }");
|
|
1464
1631
|
writer.line(" catch is CancellationError { throw Failure.cancelled }");
|
|
1465
1632
|
writer.line(" catch let error as URLError where error.code == .cancelled { throw Failure.cancelled }");
|
|
1466
1633
|
writer.line(" catch { throw Failure.requestFailed(error) }");
|
|
1467
1634
|
writer.line("}");
|
|
1468
|
-
writer.line("let
|
|
1469
|
-
writer.line("
|
|
1470
|
-
writer.
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1635
|
+
writer.line("let policy = retryPolicy(for: request, retry)");
|
|
1636
|
+
writer.line("var attempt = 1");
|
|
1637
|
+
writer.block("while true", () => {
|
|
1638
|
+
writer.line("let data: Foundation.Data");
|
|
1639
|
+
writer.line("let response: URLResponse");
|
|
1640
|
+
writer.line("do { (data, response) = try await session.data(for: request) }");
|
|
1641
|
+
writer.line("catch is CancellationError { throw Failure.cancelled }");
|
|
1642
|
+
writer.line("catch let error as URLError where error.code == .cancelled { throw Failure.cancelled }");
|
|
1643
|
+
writer.line("catch {");
|
|
1644
|
+
writer.line(" if let policy, let delay = retryDelay(policy, attempt: attempt, response: nil) {");
|
|
1645
|
+
writer.line(" try await pause(delay, failure: Failure.self)");
|
|
1646
|
+
writer.line(" attempt += 1");
|
|
1647
|
+
writer.line(" continue");
|
|
1648
|
+
writer.line(" }");
|
|
1649
|
+
writer.line(" throw Failure.requestFailed(error)");
|
|
1650
|
+
writer.line("}");
|
|
1651
|
+
writer.line("if let responseMiddleware { await responseMiddleware(request, data, response) }");
|
|
1652
|
+
writer.line("guard let httpResponse = response as? HTTPURLResponse else { throw Failure.invalidResponse }");
|
|
1653
|
+
writer.line("if let policy, let delay = retryDelay(policy, attempt: attempt, response: httpResponse) {");
|
|
1654
|
+
writer.line(" try await pause(delay, failure: Failure.self)");
|
|
1655
|
+
writer.line(" attempt += 1");
|
|
1656
|
+
writer.line(" continue");
|
|
1657
|
+
writer.line("}");
|
|
1658
|
+
writer.line("return (data, httpResponse.statusCode, httpResponse)");
|
|
1659
|
+
});
|
|
1660
|
+
});
|
|
1661
|
+
writer.blank();
|
|
1662
|
+
writer.block(`static func retryPolicy(for request: URLRequest, _ retry: ${options.clientName}.RetryPolicy?) -> ${options.clientName}.RetryPolicy?`, () => {
|
|
1663
|
+
writer.line("let idempotent = [\"GET\", \"HEAD\", \"OPTIONS\", \"PUT\", \"DELETE\"].contains(request.httpMethod ?? \"GET\")");
|
|
1664
|
+
writer.line("return idempotent && request.httpBodyStream == nil ? retry : nil");
|
|
1665
|
+
});
|
|
1666
|
+
writer.blank();
|
|
1667
|
+
writer.block(`static func retryDelay(_ policy: ${options.clientName}.RetryPolicy, attempt: Int, response: HTTPURLResponse?) -> TimeInterval?`, () => {
|
|
1668
|
+
writer.line("guard attempt < policy.maximumAttempts else { return nil }");
|
|
1669
|
+
writer.line("let backoff = Double.random(in: 0...min(policy.maximumDelay, policy.initialDelay * pow(2, Double(attempt - 1))))");
|
|
1670
|
+
writer.line("guard let response else { return backoff }");
|
|
1671
|
+
writer.line("guard [429, 503].contains(response.statusCode) else { return nil }");
|
|
1672
|
+
writer.line("guard let asked = retryAfter(response.value(forHTTPHeaderField: \"Retry-After\")) else { return backoff }");
|
|
1673
|
+
writer.line("return asked <= policy.maximumDelay ? asked : nil");
|
|
1674
|
+
});
|
|
1675
|
+
writer.blank();
|
|
1676
|
+
writer.block("static func retryAfter(_ header: String?) -> TimeInterval?", () => {
|
|
1677
|
+
writer.line("guard let value = header?.trimmingCharacters(in: .whitespaces) else { return nil }");
|
|
1678
|
+
writer.line("if let seconds = Int(value), seconds >= 0 { return TimeInterval(seconds) }");
|
|
1679
|
+
writer.line("let formatter = DateFormatter()");
|
|
1680
|
+
writer.line("formatter.locale = Locale(identifier: \"en_US_POSIX\")");
|
|
1681
|
+
writer.line("formatter.timeZone = TimeZone(identifier: \"GMT\")");
|
|
1682
|
+
writer.line("formatter.dateFormat = \"EEE, dd MMM yyyy HH:mm:ss zzz\"");
|
|
1683
|
+
writer.line("guard let date = formatter.date(from: value) else { return nil }");
|
|
1684
|
+
writer.line("return max(0, date.timeIntervalSinceNow)");
|
|
1685
|
+
});
|
|
1686
|
+
writer.blank();
|
|
1687
|
+
writer.block("static func pause<Failure: KizunaFailure>(_ seconds: TimeInterval, failure: Failure.Type) async throws(Failure)", () => {
|
|
1688
|
+
writer.line("do { try await Task.sleep(nanoseconds: UInt64(seconds * 1_000_000_000)) }");
|
|
1689
|
+
writer.line("catch { throw Failure.cancelled }");
|
|
1477
1690
|
});
|
|
1478
1691
|
writer.blank();
|
|
1479
1692
|
writer.block("static func decode<Value: Decodable, Failure: KizunaDecodableFailure>(_ type: Value.Type, from data: Foundation.Data, using decoder: JSONDecoder, statusCode: Int, failure: Failure.Type) throws(Failure) -> Value", () => {
|
|
@@ -1489,7 +1702,7 @@ const emitKizunaNamespace = (writer, options) => {
|
|
|
1489
1702
|
writer.line("return Failure.decoding(DecodingError.dataCorrupted(.init(codingPath: [], debugDescription: \"No matching type for status \\(statusCode)\")), statusCode: statusCode, data: data)");
|
|
1490
1703
|
});
|
|
1491
1704
|
}
|
|
1492
|
-
if (options.streaming) emitKizunaStreaming(writer);
|
|
1705
|
+
if (options.streaming) emitKizunaStreaming(writer, options.clientName);
|
|
1493
1706
|
if (options.multipart) {
|
|
1494
1707
|
writer.blank();
|
|
1495
1708
|
writer.block("struct MultipartBuilder", () => {
|
|
@@ -1570,13 +1783,13 @@ const methodGroups = (method, context) => {
|
|
|
1570
1783
|
varName: "query",
|
|
1571
1784
|
type: groupTypeRef(operationName, "Query", context),
|
|
1572
1785
|
factory: "query",
|
|
1573
|
-
required: method.query.some((field) => !field
|
|
1786
|
+
required: method.query.some((field) => !hasDefault(field))
|
|
1574
1787
|
});
|
|
1575
1788
|
if (method.headers.length > 0) groups.push({
|
|
1576
1789
|
varName: "headers",
|
|
1577
1790
|
type: groupTypeRef(operationName, "Headers", context),
|
|
1578
1791
|
factory: "headers",
|
|
1579
|
-
required: method.headers.some((field) => !field
|
|
1792
|
+
required: method.headers.some((field) => !hasDefault(field))
|
|
1580
1793
|
});
|
|
1581
1794
|
return [...groups.filter((group) => group.required), ...groups.filter((group) => !group.required)];
|
|
1582
1795
|
};
|
|
@@ -1632,7 +1845,7 @@ const emitMethodBody = (writer, method, context, receiver = "") => {
|
|
|
1632
1845
|
emitStreamMethodTail(writer, method, context, receiver, responseBinding);
|
|
1633
1846
|
return;
|
|
1634
1847
|
}
|
|
1635
|
-
writer.line(`let (data, statusCode, ${responseBinding}) = try await Kizuna.send(&request, session: ${receiver}session, requestMiddleware: ${receiver}requestMiddleware, responseMiddleware: ${receiver}responseMiddleware, failure: ${failure}.self)`);
|
|
1848
|
+
writer.line(`let (data, statusCode, ${responseBinding}) = try await Kizuna.send(&request, session: ${receiver}session, retry: ${receiver}retry, requestMiddleware: ${receiver}requestMiddleware, responseMiddleware: ${receiver}responseMiddleware, failure: ${failure}.self)`);
|
|
1636
1849
|
writer.line("switch statusCode {");
|
|
1637
1850
|
for (const successResponse of method.successResponses) {
|
|
1638
1851
|
writer.line(`case ${successResponse.status}:`);
|
|
@@ -1700,6 +1913,35 @@ const emitErrorCases = (writer, method, context, receiver, prelude) => {
|
|
|
1700
1913
|
}
|
|
1701
1914
|
}
|
|
1702
1915
|
};
|
|
1916
|
+
const IDEMPOTENT_METHODS = new Set([
|
|
1917
|
+
"GET",
|
|
1918
|
+
"HEAD",
|
|
1919
|
+
"OPTIONS",
|
|
1920
|
+
"PUT",
|
|
1921
|
+
"DELETE"
|
|
1922
|
+
]);
|
|
1923
|
+
/**
|
|
1924
|
+
* Writes the closure that reopens an event stream and returns the argument handing it to `Kizuna.events`, or nothing
|
|
1925
|
+
* for a method a client may not resend.
|
|
1926
|
+
*/
|
|
1927
|
+
const emitReopen = (writer, method, receiver, failure, status) => {
|
|
1928
|
+
if (!IDEMPOTENT_METHODS.has(method.method)) return "";
|
|
1929
|
+
closure(writer, `let reopen: @Sendable (String) async throws -> URLSession.AsyncBytes? = { [request, session = ${receiver}session, retry = ${receiver}retry, requestMiddleware = ${receiver}requestMiddleware, responseMiddleware = ${receiver}responseMiddleware] lastEventId in`, () => {
|
|
1930
|
+
writer.line("var again = request");
|
|
1931
|
+
writer.line("if !lastEventId.isEmpty { again.setValue(lastEventId, forHTTPHeaderField: \"Last-Event-ID\") }");
|
|
1932
|
+
writer.line("let reopened: (URLSession.AsyncBytes, Int, HTTPURLResponse)");
|
|
1933
|
+
writer.line(`do { reopened = try await Kizuna.open(&again, session: session, retry: retry, requestMiddleware: requestMiddleware, responseMiddleware: responseMiddleware, failure: ${failure}.self) }`);
|
|
1934
|
+
writer.line(`catch let failure as ${failure} {`);
|
|
1935
|
+
writer.line(" if case .requestFailed(let underlying) = failure { throw underlying }");
|
|
1936
|
+
writer.line(" throw failure");
|
|
1937
|
+
writer.line("}");
|
|
1938
|
+
writer.line("if reopened.1 == 204 { return nil }");
|
|
1939
|
+
writer.line(`guard reopened.1 == ${status} else { throw ${failure}.unexpectedStatus(reopened.1, Foundation.Data()) }`);
|
|
1940
|
+
writer.line(`guard reopened.2.value(forHTTPHeaderField: "Content-Type")?.lowercased().hasPrefix("text/event-stream") == true else { throw ${failure}.invalidResponse }`);
|
|
1941
|
+
writer.line("return reopened.0");
|
|
1942
|
+
});
|
|
1943
|
+
return `, reconnect: ${receiver}reconnect.map { Kizuna.Reconnection(policy: $0, reopen: reopen) }`;
|
|
1944
|
+
};
|
|
1703
1945
|
const emitStreamMethodTail = (writer, method, context, receiver, responseBinding) => {
|
|
1704
1946
|
const failure = failureRef(method, context);
|
|
1705
1947
|
const stream = method.stream;
|
|
@@ -1707,7 +1949,7 @@ const emitStreamMethodTail = (writer, method, context, receiver, responseBinding
|
|
|
1707
1949
|
const qualifiedResult = `${context.clientName}.${method.operationName}.${method.resultWrapperName}`;
|
|
1708
1950
|
const hasHeaders = method.resultHeaderFields.length > 0;
|
|
1709
1951
|
const collect = `let data = try await Kizuna.collect(bytes, failure: ${failure}.self)`;
|
|
1710
|
-
writer.line(`let (bytes, statusCode, ${responseBinding}) = try await Kizuna.open(&request, session: ${receiver}session, requestMiddleware: ${receiver}requestMiddleware, failure: ${failure}.self)`);
|
|
1952
|
+
writer.line(`let (bytes, statusCode, ${responseBinding}) = try await Kizuna.open(&request, session: ${receiver}session, retry: ${receiver}retry, requestMiddleware: ${receiver}requestMiddleware, responseMiddleware: ${receiver}responseMiddleware, failure: ${failure}.self)`);
|
|
1711
1953
|
writer.line("switch statusCode {");
|
|
1712
1954
|
writer.line(`case ${stream.status}:`);
|
|
1713
1955
|
writer.indent(() => {
|
|
@@ -1715,7 +1957,8 @@ const emitStreamMethodTail = (writer, method, context, receiver, responseBinding
|
|
|
1715
1957
|
else if (stream.mode === "binary") writer.line("let body = Kizuna.chunks(bytes)");
|
|
1716
1958
|
else if (stream.events) {
|
|
1717
1959
|
const events = stream.events;
|
|
1718
|
-
|
|
1960
|
+
const elementType = streamElementType(method, context, "actor");
|
|
1961
|
+
closure(writer, `let body = Kizuna.events(bytes, using: ${receiver}decoder${emitReopen(writer, method, receiver, failure, stream.status)}) { event, decoder -> ${elementType}? in`, () => {
|
|
1719
1962
|
writer.line("switch event.event {");
|
|
1720
1963
|
for (const event of events) {
|
|
1721
1964
|
const payloadType = resolveType(event.type, method.operationName, context);
|
|
@@ -1726,7 +1969,7 @@ const emitStreamMethodTail = (writer, method, context, receiver, responseBinding
|
|
|
1726
1969
|
});
|
|
1727
1970
|
} else {
|
|
1728
1971
|
const elementType = streamElementType(method, context, "actor");
|
|
1729
|
-
closure(writer, `let body = Kizuna.events(bytes, using: ${receiver}decoder) { event, decoder -> ${elementType}? in`, () => {
|
|
1972
|
+
closure(writer, `let body = Kizuna.events(bytes, using: ${receiver}decoder${emitReopen(writer, method, receiver, failure, stream.status)}) { event, decoder -> ${elementType}? in`, () => {
|
|
1730
1973
|
writer.line(`try decoder.decode(${elementType}.self, from: Foundation.Data(event.data.utf8))`);
|
|
1731
1974
|
});
|
|
1732
1975
|
}
|
|
@@ -1792,9 +2035,15 @@ const emitBodyEncoding = (writer, method, context, receiver = "") => {
|
|
|
1792
2035
|
writer.line("var multipart = Kizuna.MultipartBuilder()");
|
|
1793
2036
|
for (const field of body.multipartFields) {
|
|
1794
2037
|
const flattenedField = body.flattened.find((candidate) => candidate.name === field.name);
|
|
1795
|
-
const
|
|
1796
|
-
|
|
1797
|
-
|
|
2038
|
+
const isFile = field.isFile || flattenedField?.isFile === true;
|
|
2039
|
+
const append = (accessor) => {
|
|
2040
|
+
if (isFile) writer.line(`multipart.appendFile(name: ${stringLiteral(field.wireName)}, file: ${accessor})`);
|
|
2041
|
+
else writer.line(`multipart.appendField(name: ${stringLiteral(field.wireName)}, value: String(describing: ${accessor}))`);
|
|
2042
|
+
};
|
|
2043
|
+
if (flattenedField?.optional === true) writer.block(`if let value = body.${escapeKeyword(field.name)}`, () => {
|
|
2044
|
+
append("value");
|
|
2045
|
+
});
|
|
2046
|
+
else append(`body.${escapeKeyword(field.name)}`);
|
|
1798
2047
|
}
|
|
1799
2048
|
writer.line("request.httpBody = multipart.finalize()");
|
|
1800
2049
|
writer.line("request.setValue(multipart.contentType, forHTTPHeaderField: \"Content-Type\")");
|
|
@@ -1813,7 +2062,7 @@ const emitClient = (writer, config, partition, context, typesByOperation) => {
|
|
|
1813
2062
|
const allMethods = [...flatMethods, ...groups.flatMap((group) => group.methods)];
|
|
1814
2063
|
const usesMultipart = allMethods.some((method) => method.body?.kind === "multipart");
|
|
1815
2064
|
const contextFields = context.requestContextFields;
|
|
1816
|
-
const contextRequired = contextFields.some((field) => !field
|
|
2065
|
+
const contextRequired = contextFields.some((field) => !hasDefault(field));
|
|
1817
2066
|
writer.blank();
|
|
1818
2067
|
writer.block(`public final class ${clientName}: Sendable`, () => {
|
|
1819
2068
|
if (contextFields.length > 0) {
|
|
@@ -1822,7 +2071,7 @@ const emitClient = (writer, config, partition, context, typesByOperation) => {
|
|
|
1822
2071
|
writer.block("public struct RequestContext: Sendable, Equatable", () => {
|
|
1823
2072
|
for (const field of contextFields) writer.line(`public var ${escapeKeyword(field.name)}: ${field.type}`);
|
|
1824
2073
|
writer.blank();
|
|
1825
|
-
const initParams = contextFields.map((field) => `${escapeKeyword(field.name)}: ${field.type}${field
|
|
2074
|
+
const initParams = contextFields.map((field) => `${escapeKeyword(field.name)}: ${field.type}${defaultArgument(field)}`).join(", ");
|
|
1826
2075
|
writer.block(`public init(${initParams})`, () => {
|
|
1827
2076
|
for (const field of contextFields) writer.line(`self.${escapeKeyword(field.name)} = ${escapeKeyword(field.name)}`);
|
|
1828
2077
|
});
|
|
@@ -1835,6 +2084,38 @@ const emitClient = (writer, config, partition, context, typesByOperation) => {
|
|
|
1835
2084
|
});
|
|
1836
2085
|
});
|
|
1837
2086
|
}
|
|
2087
|
+
writer.blank();
|
|
2088
|
+
writer.docComment("Retries a GET, HEAD, OPTIONS, PUT or DELETE that failed on the network or was answered 429 or 503, waiting what Retry-After asks or backing off.");
|
|
2089
|
+
writer.block("public struct RetryPolicy: Sendable", () => {
|
|
2090
|
+
writer.docComment("Attempts in all, the first included.");
|
|
2091
|
+
writer.line("public var maximumAttempts: Int");
|
|
2092
|
+
writer.docComment("Seconds the first backoff waits at most.");
|
|
2093
|
+
writer.line("public var initialDelay: TimeInterval");
|
|
2094
|
+
writer.docComment("Seconds any wait may take.");
|
|
2095
|
+
writer.line("public var maximumDelay: TimeInterval");
|
|
2096
|
+
writer.blank();
|
|
2097
|
+
writer.block("public init(maximumAttempts: Int = 3, initialDelay: TimeInterval = 0.5, maximumDelay: TimeInterval = 30)", () => {
|
|
2098
|
+
writer.line("self.maximumAttempts = maximumAttempts");
|
|
2099
|
+
writer.line("self.initialDelay = initialDelay");
|
|
2100
|
+
writer.line("self.maximumDelay = maximumDelay");
|
|
2101
|
+
});
|
|
2102
|
+
});
|
|
2103
|
+
writer.blank();
|
|
2104
|
+
writer.docComment("Reconnects an event stream on a GET, HEAD, OPTIONS, PUT or DELETE when its connection drops, sending the id of the last event as Last-Event-ID.");
|
|
2105
|
+
writer.block("public struct ReconnectPolicy: Sendable", () => {
|
|
2106
|
+
writer.docComment("Reconnections in a row before the stream fails. An event received resets the count.");
|
|
2107
|
+
writer.line("public var maximumAttempts: Int");
|
|
2108
|
+
writer.docComment("Seconds to wait before reconnecting, until the server sends a retry field.");
|
|
2109
|
+
writer.line("public var reconnectionTime: TimeInterval");
|
|
2110
|
+
writer.docComment("Seconds the wait may grow to after reconnections in a row that fail.");
|
|
2111
|
+
writer.line("public var maximumDelay: TimeInterval");
|
|
2112
|
+
writer.blank();
|
|
2113
|
+
writer.block("public init(maximumAttempts: Int = 5, reconnectionTime: TimeInterval = 3, maximumDelay: TimeInterval = 30)", () => {
|
|
2114
|
+
writer.line("self.maximumAttempts = maximumAttempts");
|
|
2115
|
+
writer.line("self.reconnectionTime = reconnectionTime");
|
|
2116
|
+
writer.line("self.maximumDelay = maximumDelay");
|
|
2117
|
+
});
|
|
2118
|
+
});
|
|
1838
2119
|
if (usesMultipart) {
|
|
1839
2120
|
writer.blank();
|
|
1840
2121
|
writer.block("public struct MultipartFile: Sendable, Equatable", () => {
|
|
@@ -1932,14 +2213,18 @@ const emitClient = (writer, config, partition, context, typesByOperation) => {
|
|
|
1932
2213
|
if (contextFields.length > 0) writer.line("let requestContextHeaders: [String: String]");
|
|
1933
2214
|
writer.line("public let requestMiddleware: (@Sendable (inout URLRequest) async throws -> Void)?");
|
|
1934
2215
|
writer.line("public let responseMiddleware: (@Sendable (URLRequest, Foundation.Data, URLResponse) async -> Void)?");
|
|
2216
|
+
writer.line("public let retry: RetryPolicy?");
|
|
2217
|
+
writer.line("public let reconnect: ReconnectPolicy?");
|
|
1935
2218
|
writer.line("let encoder: JSONEncoder");
|
|
1936
2219
|
writer.line("let decoder: JSONDecoder");
|
|
1937
2220
|
writer.blank();
|
|
1938
2221
|
const contextInitParam = contextFields.length > 0 ? `, requestContext: RequestContext${contextRequired ? "" : " = RequestContext()"}` : "";
|
|
1939
|
-
writer.block(`public init(baseURL: URL, session: URLSession = .shared, timeout: TimeInterval = 30${contextInitParam}, requestMiddleware: (@Sendable (inout URLRequest) async throws -> Void)? = nil, responseMiddleware: (@Sendable (URLRequest, Foundation.Data, URLResponse) async -> Void)? = nil)`, () => {
|
|
2222
|
+
writer.block(`public init(baseURL: URL, session: URLSession = .shared, timeout: TimeInterval = 30, retry: RetryPolicy? = nil, reconnect: ReconnectPolicy? = nil${contextInitParam}, requestMiddleware: (@Sendable (inout URLRequest) async throws -> Void)? = nil, responseMiddleware: (@Sendable (URLRequest, Foundation.Data, URLResponse) async -> Void)? = nil)`, () => {
|
|
1940
2223
|
writer.line("self.baseURL = baseURL");
|
|
1941
2224
|
writer.line("self.session = session");
|
|
1942
2225
|
writer.line("self.timeout = timeout");
|
|
2226
|
+
writer.line("self.retry = retry");
|
|
2227
|
+
writer.line("self.reconnect = reconnect");
|
|
1943
2228
|
if (contextFields.length > 0) writer.line("self.requestContextHeaders = requestContext.headerFields");
|
|
1944
2229
|
writer.line("self.requestMiddleware = requestMiddleware");
|
|
1945
2230
|
writer.line("self.responseMiddleware = responseMiddleware");
|
|
@@ -1971,18 +2256,8 @@ const emitClient = (writer, config, partition, context, typesByOperation) => {
|
|
|
1971
2256
|
}
|
|
1972
2257
|
});
|
|
1973
2258
|
};
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
*
|
|
1977
|
-
* - `namespaceName`: the actor class. Defaults to `APIClient`.
|
|
1978
|
-
*/
|
|
1979
|
-
const generateSwiftClient = (api, options) => {
|
|
1980
|
-
const { namespaceName, camelCaseProperties = false, unknownEnumCase = false } = options;
|
|
1981
|
-
const registry = new TypeRegistry(camelCaseProperties, unknownEnumCase);
|
|
1982
|
-
const partition = swiftGenerator(api, {
|
|
1983
|
-
namespaceName,
|
|
1984
|
-
registry
|
|
1985
|
-
});
|
|
2259
|
+
const renderSwiftClient = (api, partition, registry, options) => {
|
|
2260
|
+
const { namespaceName } = options;
|
|
1986
2261
|
const allMethods = [...partition.flatMethods, ...partition.groups.flatMap((group) => group.methods)];
|
|
1987
2262
|
const operationTypeMap = buildOperationTypeMap(allMethods, registry);
|
|
1988
2263
|
const clientName = `${namespaceName}Client`;
|
|
@@ -2043,6 +2318,10 @@ const generateSwiftClient = (api, options) => {
|
|
|
2043
2318
|
};
|
|
2044
2319
|
writer.block(`public enum ${namespaceName}`, () => {
|
|
2045
2320
|
emitTypes(writer, topLevelSharedTypes, context, ownedTypeMap, ownedTypeLookup);
|
|
2321
|
+
for (const brand of registry.allBrands()) {
|
|
2322
|
+
writer.blank();
|
|
2323
|
+
emitBrand(writer, brand);
|
|
2324
|
+
}
|
|
2046
2325
|
});
|
|
2047
2326
|
emitClient(writer, {
|
|
2048
2327
|
clientName,
|
|
@@ -2059,6 +2338,26 @@ const generateSwiftClient = (api, options) => {
|
|
|
2059
2338
|
for (const warning of registry.warnings()) process.stderr.write(`[kizuna/swift] AnyCodable fallback at ${warning}\n`);
|
|
2060
2339
|
return writer.toString();
|
|
2061
2340
|
};
|
|
2341
|
+
/**
|
|
2342
|
+
* The Swift client's walk: the routes into a partition, then the file.
|
|
2343
|
+
*/
|
|
2344
|
+
const swiftClientWalk = (api, options) => {
|
|
2345
|
+
const registry = new TypeRegistry(options.camelCaseProperties ?? false, options.unknownEnumCase ?? false);
|
|
2346
|
+
const routes = swiftRoutesWalk({
|
|
2347
|
+
namespaceName: options.namespaceName,
|
|
2348
|
+
registry
|
|
2349
|
+
});
|
|
2350
|
+
return {
|
|
2351
|
+
processRoute: routes.processRoute,
|
|
2352
|
+
finalize: () => renderSwiftClient(api, routes.finalize(), registry, options)
|
|
2353
|
+
};
|
|
2354
|
+
};
|
|
2355
|
+
/**
|
|
2356
|
+
* Generate a Swift API client from a kizuna config.
|
|
2357
|
+
*
|
|
2358
|
+
* - `namespaceName`: the actor class. Defaults to `APIClient`.
|
|
2359
|
+
*/
|
|
2360
|
+
const generateSwiftClient = (api, options) => (0, kizunajs_generator.walkApi)(api, swiftClientWalk(api, options), { skipHidden: true });
|
|
2062
2361
|
//#endregion
|
|
2063
2362
|
Object.defineProperty(exports, "generateSwiftClient", {
|
|
2064
2363
|
enumerable: true,
|
|
@@ -2066,3 +2365,9 @@ Object.defineProperty(exports, "generateSwiftClient", {
|
|
|
2066
2365
|
return generateSwiftClient;
|
|
2067
2366
|
}
|
|
2068
2367
|
});
|
|
2368
|
+
Object.defineProperty(exports, "swiftClientWalk", {
|
|
2369
|
+
enumerable: true,
|
|
2370
|
+
get: function() {
|
|
2371
|
+
return swiftClientWalk;
|
|
2372
|
+
}
|
|
2373
|
+
});
|