@sdkgen/node-runtime 1.6.2 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -14,9 +14,9 @@ async function executeRequest(ctx, apiConfig) {
14
14
  if (!functionDescription || !functionImplementation) {
15
15
  throw new error_1.Fatal(`Function does not exist: ${ctx.request.name}`);
16
16
  }
17
- const args = encode_decode_1.decode(apiConfig.astJson.typeTable, `${ctx.request.name}.args`, functionDescription.args, ctx.request.args);
18
- const ret = await functionImplementation(ctx, args);
19
- const encodedRet = encode_decode_1.encode(apiConfig.astJson.typeTable, `${ctx.request.name}.ret`, functionDescription.ret, ret);
17
+ const args = (0, encode_decode_1.decode)(apiConfig.astJson.typeTable, `${ctx.request.name}.args`, functionDescription.args, ctx.request.args);
18
+ const ret = (await functionImplementation(ctx, args));
19
+ const encodedRet = (0, encode_decode_1.encode)(apiConfig.astJson.typeTable, `${ctx.request.name}.ret`, functionDescription.ret, ret);
20
20
  return { result: encodedRet };
21
21
  }
22
22
  catch (error) {
@@ -43,7 +43,7 @@ async function executeRequest(ctx, apiConfig) {
43
43
  const allowedErrors = functionAst.annotations.filter(ann => ann instanceof parser_1.ThrowsAnnotation).map(ann => ann.error);
44
44
  if (typeof reply.error !== "object" ||
45
45
  reply.error === null ||
46
- !utils_1.has(reply.error, "type") ||
46
+ !(0, utils_1.has)(reply.error, "type") ||
47
47
  typeof reply.error.type !== "string" ||
48
48
  (allowedErrors.length > 0 && !allowedErrors.includes(reply.error.type)) ||
49
49
  !apiConfig.astJson.errors.map(error => (typeof error === "string" ? error : error[0])).includes(reply.error.type)) {
@@ -17,7 +17,7 @@ class SdkgenHttpClient {
17
17
  this.baseUrl = new url_1.URL(baseUrl);
18
18
  }
19
19
  async makeRequest(ctx, functionName, args) {
20
- var _a, _b;
20
+ var _a, _b, _c, _d;
21
21
  const func = this.astJson.functionTable[functionName];
22
22
  if (!func) {
23
23
  throw new Error(`Unknown function ${functionName}`);
@@ -27,11 +27,11 @@ class SdkgenHttpClient {
27
27
  extra[key] = value;
28
28
  }
29
29
  const requestBody = JSON.stringify({
30
- args: encode_decode_1.encode(this.astJson.typeTable, `${functionName}.args`, func.args, args),
31
- deviceInfo: ((_a = ctx === null || ctx === void 0 ? void 0 : ctx.request) === null || _a === void 0 ? void 0 : _a.deviceInfo) ? ctx.request.deviceInfo : { id: os_1.hostname(), type: "node" },
32
- extra: Object.assign(Object.assign({}, extra), ((ctx === null || ctx === void 0 ? void 0 : ctx.request) ? ctx.request.extra : {})),
30
+ args: (0, encode_decode_1.encode)(this.astJson.typeTable, `${functionName}.args`, func.args, args),
31
+ deviceInfo: (_b = (_a = ctx === null || ctx === void 0 ? void 0 : ctx.request) === null || _a === void 0 ? void 0 : _a.deviceInfo) !== null && _b !== void 0 ? _b : { id: (0, os_1.hostname)(), type: "node" },
32
+ extra: Object.assign(Object.assign({}, extra), (_c = ctx === null || ctx === void 0 ? void 0 : ctx.request) === null || _c === void 0 ? void 0 : _c.extra),
33
33
  name: functionName,
34
- requestId: ((_b = ctx === null || ctx === void 0 ? void 0 : ctx.request) === null || _b === void 0 ? void 0 : _b.id) ? ctx.request.id + crypto_1.randomBytes(6).toString("hex") : crypto_1.randomBytes(16).toString("hex"),
34
+ requestId: ((_d = ctx === null || ctx === void 0 ? void 0 : ctx.request) === null || _d === void 0 ? void 0 : _d.id) ? ctx.request.id + (0, crypto_1.randomBytes)(6).toString("hex") : (0, crypto_1.randomBytes)(16).toString("hex"),
35
35
  version: 3,
36
36
  });
37
37
  const options = {
@@ -52,11 +52,11 @@ class SdkgenHttpClient {
52
52
  res.on("end", () => {
53
53
  try {
54
54
  const response = JSON.parse(data);
55
- if (utils_1.has(response, "error") && response.error) {
55
+ if ((0, utils_1.has)(response, "error") && response.error) {
56
56
  reject(response.error);
57
57
  }
58
58
  else {
59
- resolve(utils_1.has(response, "result") ? response.result : null);
59
+ resolve((0, utils_1.has)(response, "result") ? response.result : null);
60
60
  }
61
61
  }
62
62
  catch (error) {
@@ -76,13 +76,13 @@ class SdkgenHttpClient {
76
76
  req.write(requestBody);
77
77
  req.end();
78
78
  }).catch(error => {
79
- if (utils_1.has(error, "type") && utils_1.has(error, "message") && typeof error.type === "string" && typeof error.message === "string") {
79
+ if ((0, utils_1.has)(error, "type") && (0, utils_1.has)(error, "message") && typeof error.type === "string" && typeof error.message === "string") {
80
80
  const errClass = this.errClasses[error.type];
81
81
  if (errClass) {
82
82
  const errorJson = this.astJson.errors.find(err => (Array.isArray(err) ? err[0] === error.type : err === error.type));
83
83
  if (errorJson) {
84
- if (Array.isArray(errorJson) && utils_1.has(error, "data")) {
85
- throw new errClass(error.message, encode_decode_1.decode(this.astJson.typeTable, `${errClass.name}.data`, errorJson[1], error.data));
84
+ if (Array.isArray(errorJson) && (0, utils_1.has)(error, "data")) {
85
+ throw new errClass(error.message, (0, encode_decode_1.decode)(this.astJson.typeTable, `${errClass.name}.data`, errorJson[1], error.data));
86
86
  }
87
87
  else {
88
88
  throw new errClass(error.message, undefined);
@@ -96,7 +96,7 @@ class SdkgenHttpClient {
96
96
  }
97
97
  });
98
98
  // eslint-disable-next-line @typescript-eslint/no-unsafe-return
99
- return encode_decode_1.decode(this.astJson.typeTable, `${functionName}.ret`, func.ret, encodedRet);
99
+ return (0, encode_decode_1.decode)(this.astJson.typeTable, `${functionName}.ret`, func.ret, encodedRet);
100
100
  }
101
101
  }
102
102
  exports.SdkgenHttpClient = SdkgenHttpClient;
@@ -10,6 +10,7 @@ export declare class SdkgenHttpServer<ExtraContextT = unknown> {
10
10
  private handlers;
11
11
  dynamicCorsOrigin: boolean;
12
12
  introspection: boolean;
13
+ log: (message: string) => void;
13
14
  private hasSwagger;
14
15
  private ignoredUrlPrefix;
15
16
  constructor(apiConfig: BaseApiConfig<ExtraContextT>, extraContext: ExtraContextT);
@@ -23,7 +24,6 @@ export declare class SdkgenHttpServer<ExtraContextT = unknown> {
23
24
  private findBestHandler;
24
25
  private attachRestHandlers;
25
26
  private handleRequest;
26
- private log;
27
27
  private handleRequestWithBody;
28
28
  private executeRequest;
29
29
  private parseRequest;
@@ -11,9 +11,13 @@ const os_1 = require("os");
11
11
  const querystring_1 = require("querystring");
12
12
  const url_1 = require("url");
13
13
  const util_1 = require("util");
14
+ const csharp_generator_1 = require("@sdkgen/csharp-generator");
14
15
  const dart_generator_1 = require("@sdkgen/dart-generator");
16
+ const fsharp_generator_1 = require("@sdkgen/fsharp-generator");
17
+ const kotlin_generator_1 = require("@sdkgen/kotlin-generator");
15
18
  const parser_1 = require("@sdkgen/parser");
16
19
  const playground_1 = require("@sdkgen/playground");
20
+ const swift_generator_1 = require("@sdkgen/swift-generator");
17
21
  const typescript_generator_1 = require("@sdkgen/typescript-generator");
18
22
  const busboy_1 = __importDefault(require("busboy"));
19
23
  const file_type_1 = __importDefault(require("file-type"));
@@ -33,16 +37,25 @@ class SdkgenHttpServer {
33
37
  this.handlers = [];
34
38
  this.dynamicCorsOrigin = true;
35
39
  this.introspection = true;
40
+ this.log = (message) => {
41
+ console.log(`${new Date().toISOString()} ${message}`);
42
+ };
36
43
  this.hasSwagger = false;
37
44
  this.ignoredUrlPrefix = "";
38
- this.httpServer = http_1.createServer(this.handleRequest.bind(this));
45
+ this.httpServer = (0, http_1.createServer)(this.handleRequest.bind(this));
39
46
  this.enableCors();
40
47
  this.attachRestHandlers();
41
48
  const targetTable = [
49
+ ["/targets/android/client.kt", (ast) => (0, kotlin_generator_1.generateAndroidClientSource)(ast, true)],
50
+ ["/targets/android/client_without_callbacks.kt", (ast) => (0, kotlin_generator_1.generateAndroidClientSource)(ast, false)],
51
+ ["/targets/dotnet/api.cs", csharp_generator_1.generateCSharpServerSource],
52
+ ["/targets/dotnet/api.fs", fsharp_generator_1.generateFSharpServerSource],
53
+ ["/targets/flutter/client.dart", dart_generator_1.generateDartClientSource],
54
+ ["/targets/ios/client.swift", (ast) => (0, swift_generator_1.generateSwiftClientSource)(ast, false)],
55
+ ["/targets/ios/client-rx.swift", (ast) => (0, swift_generator_1.generateSwiftClientSource)(ast, true)],
42
56
  ["/targets/node/api.ts", typescript_generator_1.generateNodeServerSource],
43
57
  ["/targets/node/client.ts", typescript_generator_1.generateNodeClientSource],
44
58
  ["/targets/web/client.ts", typescript_generator_1.generateBrowserClientSource],
45
- ["/targets/flutter/client.dart", dart_generator_1.generateDartClientSource],
46
59
  ];
47
60
  for (const [path, generateFn] of targetTable) {
48
61
  this.addHttpHandler("GET", path, (_req, res) => {
@@ -82,7 +95,7 @@ class SdkgenHttpServer {
82
95
  if (req.url) {
83
96
  req.url = req.url.endsWith("/playground") ? req.url.replace(/\/playground/u, "/index.html") : req.url.replace(/\/playground/u, "");
84
97
  }
85
- serve_handler_1.default(req, res, {
98
+ (0, serve_handler_1.default)(req, res, {
86
99
  cleanUrls: false,
87
100
  directoryListing: false,
88
101
  etag: true,
@@ -132,7 +145,7 @@ class SdkgenHttpServer {
132
145
  });
133
146
  }
134
147
  async close() {
135
- return util_1.promisify(this.httpServer.close.bind(this.httpServer))();
148
+ return (0, util_1.promisify)(this.httpServer.close.bind(this.httpServer))();
136
149
  }
137
150
  enableCors() {
138
151
  this.addHeader("Access-Control-Allow-Methods", "DELETE, HEAD, PUT, POST, PATCH, GET, OPTIONS");
@@ -201,7 +214,7 @@ class SdkgenHttpServer {
201
214
  continue;
202
215
  }
203
216
  if (!this.hasSwagger) {
204
- swagger_1.setupSwagger(this);
217
+ (0, swagger_1.setupSwagger)(this);
205
218
  this.hasSwagger = true;
206
219
  }
207
220
  const pathFragments = ann.path.split(/\{\w+\}/u);
@@ -222,7 +235,7 @@ class SdkgenHttpServer {
222
235
  try {
223
236
  const args = {};
224
237
  const files = [];
225
- const { pathname, query } = url_1.parse((_a = req.url) !== null && _a !== void 0 ? _a : "");
238
+ const { pathname, query } = (0, url_1.parse)((_a = req.url) !== null && _a !== void 0 ? _a : "");
226
239
  const match = pathname === null || pathname === void 0 ? void 0 : pathname.match(pathRegex);
227
240
  if (!match) {
228
241
  res.statusCode = 404;
@@ -234,7 +247,7 @@ class SdkgenHttpServer {
234
247
  const argValue = match[i + 1];
235
248
  simpleArgs.set(argName, argValue);
236
249
  }
237
- const parsedQuery = query ? querystring_1.parse(query) : {};
250
+ const parsedQuery = query ? (0, querystring_1.parse)(query) : {};
238
251
  for (const argName of ann.queryVariables) {
239
252
  const argValue = (_b = parsedQuery[argName]) !== null && _b !== void 0 ? _b : null;
240
253
  if (argValue === null) {
@@ -250,8 +263,7 @@ class SdkgenHttpServer {
250
263
  simpleArgs.set(argName, Array.isArray(argValue) ? argValue.join("") : argValue);
251
264
  }
252
265
  if (!ann.bodyVariable && ((_d = req.headers["content-type"]) === null || _d === void 0 ? void 0 : _d.match(/^application\/x-www-form-urlencoded/iu))) {
253
- const parsedBody = querystring_1.parse(body.toString());
254
- console.log("parsedBody", parsedBody);
266
+ const parsedBody = (0, querystring_1.parse)(body.toString());
255
267
  for (const argName of ann.queryVariables) {
256
268
  const argValue = (_e = parsedBody[argName]) !== null && _e !== void 0 ? _e : null;
257
269
  if (argValue === null) {
@@ -261,23 +273,23 @@ class SdkgenHttpServer {
261
273
  }
262
274
  }
263
275
  else if (!ann.bodyVariable && ((_f = req.headers["content-type"]) === null || _f === void 0 ? void 0 : _f.match(/^multipart\/form-data/iu))) {
264
- const busboy = new busboy_1.default({ headers: req.headers });
276
+ const busboy = (0, busboy_1.default)({ headers: req.headers });
265
277
  const filePromises = [];
266
278
  busboy.on("field", (field, value) => {
267
279
  if (ann.queryVariables.includes(field)) {
268
280
  simpleArgs.set(field, `${value}`);
269
281
  }
270
282
  });
271
- busboy.on("file", (_field, file, name) => {
272
- const tempName = crypto_1.randomBytes(32).toString("hex");
273
- const writeStream = fs_1.createWriteStream(tempName);
283
+ busboy.on("file", (_field, stream, info) => {
284
+ const tempName = (0, crypto_1.randomBytes)(32).toString("hex");
285
+ const writeStream = (0, fs_1.createWriteStream)(tempName);
274
286
  filePromises.push(new Promise((resolve, reject) => {
275
287
  writeStream.on("error", reject);
276
288
  writeStream.on("close", () => {
277
- const contents = fs_1.createReadStream(tempName);
278
- files.push({ contents, name });
289
+ const contents = (0, fs_1.createReadStream)(tempName);
290
+ files.push({ contents, name: info.filename });
279
291
  contents.on("open", () => {
280
- fs_1.unlink(tempName, err => {
292
+ (0, fs_1.unlink)(tempName, err => {
281
293
  if (err) {
282
294
  reject(err);
283
295
  }
@@ -288,7 +300,7 @@ class SdkgenHttpServer {
288
300
  });
289
301
  });
290
302
  writeStream.on("open", () => {
291
- file.pipe(writeStream);
303
+ stream.pipe(writeStream);
292
304
  });
293
305
  }));
294
306
  });
@@ -383,7 +395,7 @@ class SdkgenHttpServer {
383
395
  args[argName] = argValue;
384
396
  }
385
397
  }
386
- const ip = request_ip_1.getClientIp(req);
398
+ const ip = (0, request_ip_1.getClientIp)(req);
387
399
  if (!ip) {
388
400
  throw new Error("Couldn't determine client IP");
389
401
  }
@@ -391,7 +403,7 @@ class SdkgenHttpServer {
391
403
  args,
392
404
  deviceInfo: {
393
405
  fingerprint: null,
394
- id: crypto_1.randomBytes(16).toString("hex"),
406
+ id: (0, crypto_1.randomBytes)(16).toString("hex"),
395
407
  language: null,
396
408
  platform: null,
397
409
  timezone: null,
@@ -401,7 +413,7 @@ class SdkgenHttpServer {
401
413
  extra: {},
402
414
  files,
403
415
  headers: req.headers,
404
- id: crypto_1.randomBytes(16).toString("hex"),
416
+ id: (0, crypto_1.randomBytes)(16).toString("hex"),
405
417
  ip,
406
418
  name: op.name,
407
419
  version: 3,
@@ -474,7 +486,8 @@ class SdkgenHttpServer {
474
486
  .then(() => {
475
487
  res.write(buffer);
476
488
  res.end();
477
- });
489
+ })
490
+ .catch(() => { });
478
491
  }
479
492
  else {
480
493
  res.setHeader("content-type", "application/json");
@@ -530,17 +543,13 @@ class SdkgenHttpServer {
530
543
  }
531
544
  const body = [];
532
545
  req.on("data", chunk => body.push(chunk));
533
- // eslint-disable-next-line @typescript-eslint/no-misused-promises
534
546
  req.on("end", () => {
535
- this.handleRequestWithBody(req, res, Buffer.concat(body), hrStart).catch(e => this.writeReply(res, null, { error: e }, hrStart));
547
+ this.handleRequestWithBody(req, res, Buffer.concat(body), hrStart).catch((e) => this.writeReply(res, null, { error: e }, hrStart));
536
548
  });
537
549
  }
538
- log(message) {
539
- console.log(`${new Date().toISOString()} ${message}`);
540
- }
541
550
  async handleRequestWithBody(req, res, body, hrStart) {
542
551
  var _a, _b;
543
- const { pathname, query } = url_1.parse((_a = req.url) !== null && _a !== void 0 ? _a : "");
552
+ const { pathname, query } = (0, url_1.parse)((_a = req.url) !== null && _a !== void 0 ? _a : "");
544
553
  let path = pathname !== null && pathname !== void 0 ? pathname : "";
545
554
  if (path.startsWith(this.ignoredUrlPrefix)) {
546
555
  path = path.slice(this.ignoredUrlPrefix.length);
@@ -565,9 +574,8 @@ class SdkgenHttpServer {
565
574
  res.end();
566
575
  return;
567
576
  }
568
- let ok;
577
+ let ok = true;
569
578
  try {
570
- ok = await this.apiConfig.hook.onHealthCheck();
571
579
  for (const healthCheck of this.healthChecks) {
572
580
  if (!ok) {
573
581
  break;
@@ -588,7 +596,7 @@ class SdkgenHttpServer {
588
596
  res.end();
589
597
  return;
590
598
  }
591
- const clientIp = request_ip_1.getClientIp(req);
599
+ const clientIp = (0, request_ip_1.getClientIp)(req);
592
600
  if (!clientIp) {
593
601
  this.writeReply(res, null, {
594
602
  error: new error_1.Fatal("Couldn't determine client IP"),
@@ -606,7 +614,7 @@ class SdkgenHttpServer {
606
614
  }
607
615
  async executeRequest(request, writeReply) {
608
616
  const ctx = Object.assign(Object.assign({}, this.extraContext), { request });
609
- writeReply(ctx, await execute_1.executeRequest(ctx, this.apiConfig));
617
+ writeReply(ctx, await (0, execute_1.executeRequest)(ctx, this.apiConfig));
610
618
  }
611
619
  parseRequest(req, body, ip) {
612
620
  switch (this.identifyRequestVersion(req, body)) {
@@ -622,13 +630,13 @@ class SdkgenHttpServer {
622
630
  }
623
631
  identifyRequestVersion(_req, body) {
624
632
  const parsed = JSON.parse(body);
625
- if (typeof parsed === "object" && parsed && utils_1.has(parsed, "version") && typeof parsed.version === "number") {
633
+ if (typeof parsed === "object" && parsed && (0, utils_1.has)(parsed, "version") && typeof parsed.version === "number") {
626
634
  return parsed.version;
627
635
  }
628
- else if (typeof parsed === "object" && parsed && utils_1.has(parsed, "requestId")) {
636
+ else if (typeof parsed === "object" && parsed && (0, utils_1.has)(parsed, "requestId")) {
629
637
  return 2;
630
638
  }
631
- else if (typeof parsed === "object" && parsed && utils_1.has(parsed, "device")) {
639
+ else if (typeof parsed === "object" && parsed && (0, utils_1.has)(parsed, "device")) {
632
640
  return 1;
633
641
  }
634
642
  return 3;
@@ -636,23 +644,24 @@ class SdkgenHttpServer {
636
644
  // Old Sdkgen format
637
645
  parseRequestV1(req, body, ip) {
638
646
  var _a, _b;
639
- const parsed = encode_decode_1.decode({
647
+ const parsed = (0, encode_decode_1.decode)({
640
648
  Request: {
641
649
  args: "json",
642
- device: {
643
- fingerprint: "string?",
644
- id: "string?",
645
- language: "string?",
646
- platform: "json?",
647
- timezone: "string?",
648
- type: "string?",
649
- version: "string?",
650
- },
650
+ device: "RequestDevice",
651
651
  id: "string",
652
652
  name: "string",
653
653
  },
654
+ RequestDevice: {
655
+ fingerprint: "string?",
656
+ id: "string?",
657
+ language: "string?",
658
+ platform: "json?",
659
+ timezone: "string?",
660
+ type: "string?",
661
+ version: "string?",
662
+ },
654
663
  }, "root", "Request", JSON.parse(body));
655
- const deviceId = (_a = parsed.device.id) !== null && _a !== void 0 ? _a : crypto_1.randomBytes(20).toString("hex");
664
+ const deviceId = (_a = parsed.device.id) !== null && _a !== void 0 ? _a : (0, crypto_1.randomBytes)(20).toString("hex");
656
665
  if (!parsed.args || Array.isArray(parsed.args) || typeof parsed.args !== "object") {
657
666
  throw new Error("Expected 'args' to be an object");
658
667
  }
@@ -679,21 +688,22 @@ class SdkgenHttpServer {
679
688
  // Maxima sdkgen format
680
689
  parseRequestV2(req, body, ip) {
681
690
  var _a, _b;
682
- const parsed = encode_decode_1.decode({
691
+ const parsed = (0, encode_decode_1.decode)({
683
692
  Request: {
684
693
  args: "json",
685
694
  deviceFingerprint: "string?",
686
695
  deviceId: "string",
687
- info: {
688
- browserUserAgent: "string?",
689
- language: "string",
690
- type: "string",
691
- },
696
+ info: "RequestInfo",
692
697
  name: "string",
693
698
  partnerId: "string?",
694
699
  requestId: "string?",
695
700
  sessionId: "string?",
696
701
  },
702
+ RequestInfo: {
703
+ browserUserAgent: "string?",
704
+ language: "string",
705
+ type: "string",
706
+ },
697
707
  }, "root", "Request", JSON.parse(body));
698
708
  if (!parsed.args || Array.isArray(parsed.args) || typeof parsed.args !== "object") {
699
709
  throw new Error("Expected 'args' to be an object");
@@ -717,7 +727,7 @@ class SdkgenHttpServer {
717
727
  },
718
728
  files: [],
719
729
  headers: req.headers,
720
- id: `${parsed.deviceId}-${(_b = parsed.requestId) !== null && _b !== void 0 ? _b : crypto_1.randomBytes(16).toString("hex")}`,
730
+ id: `${parsed.deviceId}-${(_b = parsed.requestId) !== null && _b !== void 0 ? _b : (0, crypto_1.randomBytes)(16).toString("hex")}`,
721
731
  ip,
722
732
  name: parsed.name,
723
733
  version: 2,
@@ -726,7 +736,7 @@ class SdkgenHttpServer {
726
736
  // New sdkgen format
727
737
  parseRequestV3(req, body, ip) {
728
738
  var _a, _b, _c, _d;
729
- const parsed = encode_decode_1.decode({
739
+ const parsed = (0, encode_decode_1.decode)({
730
740
  DeviceInfo: {
731
741
  fingerprint: "string?",
732
742
  id: "string?",
@@ -753,7 +763,7 @@ class SdkgenHttpServer {
753
763
  type: null,
754
764
  version: null,
755
765
  };
756
- const deviceId = (_b = deviceInfo.id) !== null && _b !== void 0 ? _b : crypto_1.randomBytes(16).toString("hex");
766
+ const deviceId = (_b = deviceInfo.id) !== null && _b !== void 0 ? _b : (0, crypto_1.randomBytes)(16).toString("hex");
757
767
  if (!parsed.args || Array.isArray(parsed.args) || typeof parsed.args !== "object") {
758
768
  throw new Error("Expected 'args' to be an object");
759
769
  }
@@ -771,7 +781,7 @@ class SdkgenHttpServer {
771
781
  extra: typeof parsed.extra === "object" ? Object.assign({}, parsed.extra) : {},
772
782
  files: [],
773
783
  headers: req.headers,
774
- id: `${deviceId}-${(_d = parsed.requestId) !== null && _d !== void 0 ? _d : crypto_1.randomBytes(16).toString("hex")}`,
784
+ id: `${deviceId}-${(_d = parsed.requestId) !== null && _d !== void 0 ? _d : (0, crypto_1.randomBytes)(16).toString("hex")}`,
775
785
  ip,
776
786
  name: parsed.name,
777
787
  version: 3,
@@ -779,11 +789,11 @@ class SdkgenHttpServer {
779
789
  }
780
790
  makeResponseError(err) {
781
791
  let type = "Fatal";
782
- if (typeof err === "object" && err !== null && utils_1.has(err, "type") && typeof err.type === "string") {
792
+ if (typeof err === "object" && err !== null && (0, utils_1.has)(err, "type") && typeof err.type === "string") {
783
793
  ({ type } = err);
784
794
  }
785
795
  let message;
786
- if (typeof err === "object" && err !== null && utils_1.has(err, "message") && typeof err.message === "string") {
796
+ if (typeof err === "object" && err !== null && (0, utils_1.has)(err, "message") && typeof err.message === "string") {
787
797
  ({ message } = err);
788
798
  }
789
799
  else if (err instanceof Error) {
@@ -796,14 +806,14 @@ class SdkgenHttpServer {
796
806
  message = `${err}`;
797
807
  }
798
808
  let data;
799
- if (typeof err === "object" && err !== null && utils_1.has(err, "data")) {
809
+ if (typeof err === "object" && err !== null && (0, utils_1.has)(err, "data")) {
800
810
  ({ data } = err);
801
811
  }
802
812
  const error = this.apiConfig.ast.errors.find(x => x.name === type);
803
813
  if (error) {
804
814
  if (!(error.dataType instanceof parser_1.VoidPrimitiveType)) {
805
815
  try {
806
- data = encode_decode_1.encode(this.apiConfig.astJson.typeTable, `error.${type}`, error.dataType.name, data);
816
+ data = (0, encode_decode_1.encode)(this.apiConfig.astJson.typeTable, `error.${type}`, error.dataType.name, data);
807
817
  }
808
818
  catch (encodeError) {
809
819
  message = `Failed to encode error ${type} because: ${encodeError}. Original message: ${message}`;
@@ -838,7 +848,7 @@ class SdkgenHttpServer {
838
848
  deviceId: ctx.request.deviceInfo.id,
839
849
  duration,
840
850
  error: reply.error ? this.makeResponseError(reply.error) : null,
841
- host: os_1.hostname(),
851
+ host: (0, os_1.hostname)(),
842
852
  id: ctx.request.id,
843
853
  ok: !reply.error,
844
854
  result: reply.error ? null : reply.result,
@@ -870,7 +880,7 @@ class SdkgenHttpServer {
870
880
  const response = {
871
881
  duration,
872
882
  error: reply.error ? this.makeResponseError(reply.error) : null,
873
- host: os_1.hostname(),
883
+ host: (0, os_1.hostname)(),
874
884
  result: reply.error ? null : reply.result,
875
885
  };
876
886
  if (response.error) {
@@ -1,7 +1,7 @@
1
- export * from "./api-config";
2
- export * from "./context";
3
- export * from "./encode-decode";
4
- export * from "./error";
5
- export * from "./http-client";
6
- export * from "./http-server";
7
- export * from "./test-wrapper";
1
+ export { BaseApiConfig } from "./api-config";
2
+ export { Context, ContextReply, ContextRequest } from "./context";
3
+ export { decode, encode } from "./encode-decode";
4
+ export { Fatal, SdkgenError, SdkgenErrorWithData } from "./error";
5
+ export { SdkgenHttpClient } from "./http-client";
6
+ export { SdkgenHttpServer } from "./http-server";
7
+ export { apiTestWrapper } from "./test-wrapper";
package/dist/src/index.js CHANGED
@@ -1,19 +1,18 @@
1
1
  "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
- }) : (function(o, m, k, k2) {
6
- if (k2 === undefined) k2 = k;
7
- o[k2] = m[k];
8
- }));
9
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
10
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
11
- };
12
2
  Object.defineProperty(exports, "__esModule", { value: true });
13
- __exportStar(require("./api-config"), exports);
14
- __exportStar(require("./context"), exports);
15
- __exportStar(require("./encode-decode"), exports);
16
- __exportStar(require("./error"), exports);
17
- __exportStar(require("./http-client"), exports);
18
- __exportStar(require("./http-server"), exports);
19
- __exportStar(require("./test-wrapper"), exports);
3
+ exports.apiTestWrapper = exports.SdkgenHttpServer = exports.SdkgenHttpClient = exports.SdkgenErrorWithData = exports.SdkgenError = exports.Fatal = exports.encode = exports.decode = exports.BaseApiConfig = void 0;
4
+ var api_config_1 = require("./api-config");
5
+ Object.defineProperty(exports, "BaseApiConfig", { enumerable: true, get: function () { return api_config_1.BaseApiConfig; } });
6
+ var encode_decode_1 = require("./encode-decode");
7
+ Object.defineProperty(exports, "decode", { enumerable: true, get: function () { return encode_decode_1.decode; } });
8
+ Object.defineProperty(exports, "encode", { enumerable: true, get: function () { return encode_decode_1.encode; } });
9
+ var error_1 = require("./error");
10
+ Object.defineProperty(exports, "Fatal", { enumerable: true, get: function () { return error_1.Fatal; } });
11
+ Object.defineProperty(exports, "SdkgenError", { enumerable: true, get: function () { return error_1.SdkgenError; } });
12
+ Object.defineProperty(exports, "SdkgenErrorWithData", { enumerable: true, get: function () { return error_1.SdkgenErrorWithData; } });
13
+ var http_client_1 = require("./http-client");
14
+ Object.defineProperty(exports, "SdkgenHttpClient", { enumerable: true, get: function () { return http_client_1.SdkgenHttpClient; } });
15
+ var http_server_1 = require("./http-server");
16
+ Object.defineProperty(exports, "SdkgenHttpServer", { enumerable: true, get: function () { return http_server_1.SdkgenHttpServer; } });
17
+ var test_wrapper_1 = require("./test-wrapper");
18
+ Object.defineProperty(exports, "apiTestWrapper", { enumerable: true, get: function () { return test_wrapper_1.apiTestWrapper; } });
@@ -7,7 +7,7 @@ exports.setupSwagger = void 0;
7
7
  const parser_1 = require("@sdkgen/parser");
8
8
  const serve_handler_1 = __importDefault(require("serve-handler"));
9
9
  const swagger_ui_dist_1 = require("swagger-ui-dist");
10
- const swaggerUiAssetPath = swagger_ui_dist_1.getAbsoluteFSPath();
10
+ const swaggerUiAssetPath = (0, swagger_ui_dist_1.getAbsoluteFSPath)();
11
11
  function objectFromEntries(entries) {
12
12
  return Object.assign({}, ...Array.from(entries, ([k, v]) => ({ [k]: v })));
13
13
  }
@@ -206,7 +206,7 @@ function setupSwagger(server) {
206
206
  req.url = req.url.replace(/\/swagger/u, "");
207
207
  }
208
208
  // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call
209
- serve_handler_1.default(req, res, {
209
+ (0, serve_handler_1.default)(req, res, {
210
210
  cleanUrls: false,
211
211
  directoryListing: false,
212
212
  etag: true,
@@ -336,17 +336,22 @@ function setupSwagger(server) {
336
336
  content: {
337
337
  "application/json": {
338
338
  schema: {
339
- properties: {
340
- message: {
341
- type: "string",
342
- },
343
- type: {
344
- enum: server.apiConfig.ast.errors,
345
- type: "string",
346
- },
347
- },
348
- required: ["type", "message"],
349
- type: "object",
339
+ anyOf: [
340
+ server.apiConfig.ast.errors.map(error => ({
341
+ properties: Object.assign({ message: {
342
+ type: "string",
343
+ }, type: {
344
+ enum: [error.name],
345
+ type: "string",
346
+ } }, (error.dataType instanceof parser_1.VoidPrimitiveType
347
+ ? {}
348
+ : {
349
+ data: typeToSchema(definitions, error.dataType),
350
+ })),
351
+ required: ["type", "message"],
352
+ type: "object",
353
+ })),
354
+ ],
350
355
  },
351
356
  },
352
357
  },
@@ -15,12 +15,12 @@ function apiTestWrapper(api) {
15
15
  for (const functionName of Object.keys(api.astJson.functionTable)) {
16
16
  wrappedApi.fn[functionName] = async (ctx, args) => {
17
17
  var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
18
- const encodedArgs = encode_decode_1.encode(api.astJson.typeTable, `fn.${functionName}.args`, api.astJson.functionTable[functionName].args, args);
18
+ const encodedArgs = (0, encode_decode_1.encode)(api.astJson.typeTable, `fn.${functionName}.args`, api.astJson.functionTable[functionName].args, args);
19
19
  ctx.request = {
20
20
  args: encodedArgs,
21
21
  deviceInfo: (_b = (_a = ctx.request) === null || _a === void 0 ? void 0 : _a.deviceInfo) !== null && _b !== void 0 ? _b : {
22
22
  fingerprint: null,
23
- id: crypto_1.randomBytes(16).toString("hex"),
23
+ id: (0, crypto_1.randomBytes)(16).toString("hex"),
24
24
  language: null,
25
25
  platform: null,
26
26
  timezone: null,
@@ -30,17 +30,17 @@ function apiTestWrapper(api) {
30
30
  extra: (_d = (_c = ctx.request) === null || _c === void 0 ? void 0 : _c.extra) !== null && _d !== void 0 ? _d : {},
31
31
  files: (_f = (_e = ctx.request) === null || _e === void 0 ? void 0 : _e.files) !== null && _f !== void 0 ? _f : [],
32
32
  headers: (_h = (_g = ctx.request) === null || _g === void 0 ? void 0 : _g.headers) !== null && _h !== void 0 ? _h : {},
33
- id: (_k = (_j = ctx.request) === null || _j === void 0 ? void 0 : _j.id) !== null && _k !== void 0 ? _k : crypto_1.randomBytes(16).toString("hex"),
33
+ id: (_k = (_j = ctx.request) === null || _j === void 0 ? void 0 : _j.id) !== null && _k !== void 0 ? _k : (0, crypto_1.randomBytes)(16).toString("hex"),
34
34
  ip: (_m = (_l = ctx.request) === null || _l === void 0 ? void 0 : _l.ip) !== null && _m !== void 0 ? _m : "0.0.0.0",
35
35
  name: functionName,
36
36
  version: 3,
37
37
  };
38
- const reply = await execute_1.executeRequest(ctx, api);
38
+ const reply = await (0, execute_1.executeRequest)(ctx, api);
39
39
  if (reply.error) {
40
40
  throw reply.error;
41
41
  }
42
42
  else {
43
- const decodedRet = encode_decode_1.decode(api.astJson.typeTable, `fn.${functionName}.ret`, api.astJson.functionTable[functionName].ret, JSON.parse(JSON.stringify(reply.result)));
43
+ const decodedRet = (0, encode_decode_1.decode)(api.astJson.typeTable, `fn.${functionName}.ret`, api.astJson.functionTable[functionName].ret, JSON.parse(JSON.stringify(reply.result)));
44
44
  return decodedRet;
45
45
  }
46
46
  };