@sdk-it/rpc 0.43.0 → 0.44.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -4,20 +4,6 @@ var __export = (target, all) => {
4
4
  __defProp(target, name, { get: all[name], enumerable: true });
5
5
  };
6
6
 
7
- // packages/rpc/src/lib/rpc.ts
8
- import { tool } from "ai";
9
- import { z as z3 } from "zod";
10
- import {
11
- forEachOperation,
12
- loadSpec,
13
- toIR
14
- } from "@sdk-it/spec";
15
- import {
16
- buildInput,
17
- operationSchema,
18
- toHttpOutput
19
- } from "@sdk-it/typescript";
20
-
21
7
  // packages/rpc/src/lib/http/dispatcher.ts
22
8
  import z from "zod";
23
9
 
@@ -52,6 +38,78 @@ var createBaseUrlInterceptor = (baseUrl) => {
52
38
  }
53
39
  };
54
40
  };
41
+ var logInterceptor = {
42
+ before({ url, init }) {
43
+ console.log("Request:", { url, init });
44
+ return { url, init };
45
+ },
46
+ after(response) {
47
+ console.log("Response:", response);
48
+ return response;
49
+ }
50
+ };
51
+ var createDetailedLogInterceptor = (options) => {
52
+ const logLevel = options?.logLevel || "info";
53
+ const includeRequestBody = options?.includeRequestBody || false;
54
+ const includeResponseBody = options?.includeResponseBody || false;
55
+ return {
56
+ async before(request) {
57
+ const logData = {
58
+ url: request.url,
59
+ method: request.method,
60
+ contentType: request.headers.get("Content-Type"),
61
+ headers: Object.fromEntries([...request.headers.entries()])
62
+ };
63
+ console[logLevel]("\u{1F680} Outgoing Request:", logData);
64
+ if (includeRequestBody) {
65
+ try {
66
+ const clonedRequest = request.clone();
67
+ if (clonedRequest.headers.get("Content-Type")?.includes("application/json")) {
68
+ const body = await clonedRequest.json().catch(() => null);
69
+ console[logLevel]("Request Body:", body);
70
+ } else {
71
+ const body = await clonedRequest.text().catch(() => null);
72
+ console[logLevel]("Request Body:", body);
73
+ }
74
+ } catch (error) {
75
+ console.error("Could not log request body:", error);
76
+ }
77
+ }
78
+ return request;
79
+ },
80
+ async after(response) {
81
+ const logData = {
82
+ status: response.status,
83
+ statusText: response.statusText,
84
+ url: response.url,
85
+ headers: Object.fromEntries([...response.headers.entries()])
86
+ };
87
+ console[logLevel]("\u{1F4E5} Incoming Response:", logData);
88
+ if (includeResponseBody && response.body) {
89
+ try {
90
+ const clonedResponse = response.clone();
91
+ if (clonedResponse.headers.get("Content-Type")?.includes("application/json")) {
92
+ const body = await clonedResponse.json().catch(() => null);
93
+ console[logLevel]("Response Body:", body);
94
+ } else {
95
+ const body = await clonedResponse.text().catch(() => null);
96
+ if (body) {
97
+ console[logLevel](
98
+ "Response Body:",
99
+ body.substring(0, 500) + (body.length > 500 ? "..." : "")
100
+ );
101
+ } else {
102
+ console[logLevel]("No response body");
103
+ }
104
+ }
105
+ } catch (error) {
106
+ console.error("Could not log response body:", error);
107
+ }
108
+ }
109
+ return response;
110
+ }
111
+ };
112
+ };
55
113
 
56
114
  // packages/rpc/src/lib/http/request.ts
57
115
  function template(templateString, templateVariables) {
@@ -64,6 +122,9 @@ function template(templateString, templateVariables) {
64
122
  return result === null || result === void 0 ? "" : String(result);
65
123
  });
66
124
  }
125
+ function toWireValue(value) {
126
+ return value instanceof Date ? value.toISOString() : String(value);
127
+ }
67
128
  var Serializer = class {
68
129
  input;
69
130
  props;
@@ -80,26 +141,29 @@ var Serializer = class {
80
141
  {}
81
142
  );
82
143
  const url = new URL(template(path, params), `local://`);
83
- const headers = new Headers({});
144
+ const headers = { ...this.getHeaders() };
84
145
  for (const header of this.props.inputHeaders) {
85
- headers.set(header, this.input[header]);
146
+ const value = this.input[header];
147
+ if (value !== void 0) {
148
+ headers[header] = toWireValue(value);
149
+ }
86
150
  }
87
151
  for (const key of this.props.inputQuery) {
88
152
  const value = this.input[key];
89
153
  if (value !== void 0) {
90
154
  if (Array.isArray(value)) {
91
155
  for (const item of value) {
92
- url.searchParams.append(key, String(item));
156
+ url.searchParams.append(key, toWireValue(item));
93
157
  }
94
158
  } else {
95
- url.searchParams.set(key, String(value));
159
+ url.searchParams.set(key, toWireValue(value));
96
160
  }
97
161
  }
98
162
  }
99
163
  return {
100
164
  body: this.getBody(),
101
165
  url,
102
- headers: this.getHeaders()
166
+ headers
103
167
  };
104
168
  }
105
169
  };
@@ -125,7 +189,7 @@ var UrlencodedSerializer = class extends Serializer {
125
189
  getBody() {
126
190
  const body = new URLSearchParams();
127
191
  for (const prop of this.props.inputBody) {
128
- body.set(prop, this.input[prop]);
192
+ body.set(prop, toWireValue(this.input[prop]));
129
193
  }
130
194
  return body;
131
195
  }
@@ -185,23 +249,53 @@ function toRequest(endpoint, serializer) {
185
249
 
186
250
  // packages/rpc/src/lib/http/parse-response.ts
187
251
  import { parse } from "fast-content-type-parse";
252
+ function isBinaryContentType(contentType) {
253
+ const type = contentType.toLowerCase();
254
+ if (type.startsWith("image/")) {
255
+ return true;
256
+ }
257
+ if (type.startsWith("audio/")) {
258
+ return true;
259
+ }
260
+ if (type.startsWith("video/")) {
261
+ return true;
262
+ }
263
+ switch (type) {
264
+ case "application/pdf":
265
+ case "application/zip":
266
+ case "application/gzip":
267
+ case "application/x-7z-compressed":
268
+ case "application/x-tar":
269
+ case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
270
+ case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
271
+ case "application/vnd.openxmlformats-officedocument.presentationml.presentation":
272
+ case "application/vnd.ms-excel":
273
+ case "application/vnd.ms-powerpoint":
274
+ case "application/msword":
275
+ case "application/octet-stream":
276
+ return true;
277
+ default:
278
+ return false;
279
+ }
280
+ }
188
281
  async function buffered(response) {
282
+ if (response.status === 204 || response.status === 205 || response.status === 304) {
283
+ return null;
284
+ }
189
285
  const contentType = response.headers.get("Content-Type");
190
286
  if (!contentType) {
191
287
  throw new Error("Content-Type header is missing");
192
288
  }
193
- if (response.status === 204) {
194
- return null;
195
- }
196
289
  const { type } = parse(contentType);
290
+ if (isBinaryContentType(type)) {
291
+ return response.blob();
292
+ }
293
+ if (type.startsWith("text/")) {
294
+ return response.text();
295
+ }
197
296
  switch (type) {
198
297
  case "application/json":
199
298
  return response.json();
200
- case "text/plain":
201
- return response.text();
202
- case "text/html":
203
- return response.text();
204
- case "text/xml":
205
299
  case "application/xml":
206
300
  return response.text();
207
301
  case "application/x-www-form-urlencoded": {
@@ -229,7 +323,6 @@ __export(response_exports, {
229
323
  GatewayTimeout: () => GatewayTimeout,
230
324
  Gone: () => Gone,
231
325
  InternalServerError: () => InternalServerError,
232
- KIND: () => KIND,
233
326
  MethodNotAllowed: () => MethodNotAllowed,
234
327
  NoContent: () => NoContent,
235
328
  NotAcceptable: () => NotAcceptable,
@@ -245,357 +338,246 @@ __export(response_exports, {
245
338
  UnprocessableEntity: () => UnprocessableEntity,
246
339
  UnsupportedMediaType: () => UnsupportedMediaType
247
340
  });
248
- var KIND = Symbol("APIDATA");
249
341
  var APIResponse = class {
250
342
  static status;
251
- static kind = Symbol.for("APIResponse");
252
343
  status;
253
344
  data;
254
- constructor(status, data) {
345
+ headers;
346
+ constructor(status, headers, data) {
255
347
  this.status = status;
348
+ this.headers = headers;
256
349
  this.data = data;
257
350
  }
258
- static create(status, data) {
259
- return new this(status, data);
351
+ static create(status, headers, data) {
352
+ return new this(status, headers, data);
260
353
  }
261
354
  };
262
355
  var APIError = class extends APIResponse {
263
- static create(status, data) {
264
- return new this(status, data);
356
+ static create(status, headers, data) {
357
+ return new this(status, headers, data);
265
358
  }
266
359
  };
267
360
  var Ok = class _Ok extends APIResponse {
268
- static kind = Symbol.for("Ok");
269
361
  static status = 200;
270
- constructor(data) {
271
- super(_Ok.status, data);
272
- }
273
- static create(status, data) {
274
- Object.defineProperty(data, KIND, { value: this.kind });
275
- return new this(data);
362
+ constructor(headers, data) {
363
+ super(_Ok.status, headers, data);
276
364
  }
277
- static is(value) {
278
- return typeof value === "object" && value !== null && KIND in value && value[KIND] === this.kind;
365
+ static create(status, headers, data) {
366
+ return new this(headers, data);
279
367
  }
280
368
  };
281
369
  var Created = class _Created extends APIResponse {
282
- static kind = Symbol.for("Created");
283
370
  static status = 201;
284
- constructor(data) {
285
- super(_Created.status, data);
371
+ constructor(headers, data) {
372
+ super(_Created.status, headers, data);
286
373
  }
287
- static create(status, data) {
288
- Object.defineProperty(data, KIND, { value: this.kind });
289
- return new this(data);
290
- }
291
- static is(value) {
292
- return typeof value === "object" && value !== null && KIND in value && value[KIND] === this.kind;
374
+ static create(status, headers, data) {
375
+ return new this(headers, data);
293
376
  }
294
377
  };
295
378
  var Accepted = class _Accepted extends APIResponse {
296
- static kind = Symbol.for("Accepted");
297
379
  static status = 202;
298
- constructor(data) {
299
- super(_Accepted.status, data);
380
+ constructor(headers, data) {
381
+ super(_Accepted.status, headers, data);
300
382
  }
301
- static create(status, data) {
302
- Object.defineProperty(data, KIND, { value: this.kind });
303
- return new this(data);
304
- }
305
- static is(value) {
306
- return typeof value === "object" && value !== null && KIND in value && value[KIND] === this.kind;
383
+ static create(status, headers, data) {
384
+ return new this(headers, data);
307
385
  }
308
386
  };
309
387
  var NoContent = class _NoContent extends APIResponse {
310
- static kind = Symbol.for("NoContent");
311
388
  static status = 204;
312
- constructor() {
313
- super(_NoContent.status, null);
314
- }
315
- static create(status, data) {
316
- return new this();
389
+ constructor(headers) {
390
+ super(_NoContent.status, headers, null);
317
391
  }
318
- static is(value) {
319
- return typeof value === "object" && value !== null && KIND in value && value[KIND] === this.kind;
392
+ static create(status, headers, data) {
393
+ return new this(headers);
320
394
  }
321
395
  };
322
396
  var BadRequest = class _BadRequest extends APIError {
323
- static kind = Symbol.for("BadRequest");
324
397
  static status = 400;
325
- constructor(data) {
326
- super(_BadRequest.status, data);
398
+ constructor(headers, data) {
399
+ super(_BadRequest.status, headers, data);
327
400
  }
328
- static create(status, data) {
329
- Object.defineProperty(data, KIND, { value: this.kind });
330
- return new this(data);
331
- }
332
- static is(value) {
333
- return typeof value === "object" && value !== null && KIND in value && value[KIND] === this.kind;
401
+ static create(status, headers, data) {
402
+ return new this(headers, data);
334
403
  }
335
404
  };
336
405
  var Unauthorized = class _Unauthorized extends APIError {
337
- static kind = Symbol.for("Unauthorized");
338
406
  static status = 401;
339
- constructor(data) {
340
- super(_Unauthorized.status, data);
407
+ constructor(headers, data) {
408
+ super(_Unauthorized.status, headers, data);
341
409
  }
342
- static create(status, data) {
343
- Object.defineProperty(data, KIND, { value: this.kind });
344
- return new this(data);
345
- }
346
- static is(value) {
347
- return typeof value === "object" && value !== null && KIND in value && value[KIND] === this.kind;
410
+ static create(status, headers, data) {
411
+ return new this(headers, data);
348
412
  }
349
413
  };
350
414
  var PaymentRequired = class _PaymentRequired extends APIError {
351
- static kind = Symbol.for("PaymentRequired");
352
415
  static status = 402;
353
- constructor(data) {
354
- super(_PaymentRequired.status, data);
355
- }
356
- static create(status, data) {
357
- Object.defineProperty(data, KIND, { value: this.kind });
358
- return new this(data);
416
+ constructor(headers, data) {
417
+ super(_PaymentRequired.status, headers, data);
359
418
  }
360
- static is(value) {
361
- return typeof value === "object" && value !== null && KIND in value && value[KIND] === this.kind;
419
+ static create(status, headers, data) {
420
+ return new this(headers, data);
362
421
  }
363
422
  };
364
423
  var Forbidden = class _Forbidden extends APIError {
365
- static kind = Symbol.for("Forbidden");
366
424
  static status = 403;
367
- constructor(data) {
368
- super(_Forbidden.status, data);
369
- }
370
- static create(status, data) {
371
- Object.defineProperty(data, KIND, { value: this.kind });
372
- return new this(data);
425
+ constructor(headers, data) {
426
+ super(_Forbidden.status, headers, data);
373
427
  }
374
- static is(value) {
375
- return typeof value === "object" && value !== null && KIND in value && value[KIND] === this.kind;
428
+ static create(status, headers, data) {
429
+ return new this(headers, data);
376
430
  }
377
431
  };
378
432
  var NotFound = class _NotFound extends APIError {
379
- static kind = Symbol.for("NotFound");
380
433
  static status = 404;
381
- constructor(data) {
382
- super(_NotFound.status, data);
383
- }
384
- static create(status, data) {
385
- Object.defineProperty(data, KIND, { value: this.kind });
386
- return new this(data);
434
+ constructor(headers, data) {
435
+ super(_NotFound.status, headers, data);
387
436
  }
388
- static is(value) {
389
- return typeof value === "object" && value !== null && KIND in value && value[KIND] === this.kind;
437
+ static create(status, headers, data) {
438
+ return new this(headers, data);
390
439
  }
391
440
  };
392
441
  var MethodNotAllowed = class _MethodNotAllowed extends APIError {
393
- static kind = Symbol.for("MethodNotAllowed");
394
442
  static status = 405;
395
- constructor(data) {
396
- super(_MethodNotAllowed.status, data);
443
+ constructor(headers, data) {
444
+ super(_MethodNotAllowed.status, headers, data);
397
445
  }
398
- static create(status, data) {
399
- Object.defineProperty(data, KIND, { value: this.kind });
400
- return new this(data);
401
- }
402
- static is(value) {
403
- return typeof value === "object" && value !== null && KIND in value && value[KIND] === this.kind;
446
+ static create(status, headers, data) {
447
+ return new this(headers, data);
404
448
  }
405
449
  };
406
450
  var NotAcceptable = class _NotAcceptable extends APIError {
407
- static kind = Symbol.for("NotAcceptable");
408
451
  static status = 406;
409
- constructor(data) {
410
- super(_NotAcceptable.status, data);
452
+ constructor(headers, data) {
453
+ super(_NotAcceptable.status, headers, data);
411
454
  }
412
- static create(status, data) {
413
- Object.defineProperty(data, KIND, { value: this.kind });
414
- return new this(data);
415
- }
416
- static is(value) {
417
- return typeof value === "object" && value !== null && KIND in value && value[KIND] === this.kind;
455
+ static create(status, headers, data) {
456
+ return new this(headers, data);
418
457
  }
419
458
  };
420
459
  var Conflict = class _Conflict extends APIError {
421
- static kind = Symbol.for("Conflict");
422
460
  static status = 409;
423
- constructor(data) {
424
- super(_Conflict.status, data);
425
- }
426
- static create(status, data) {
427
- Object.defineProperty(data, KIND, { value: this.kind });
428
- return new this(data);
461
+ constructor(headers, data) {
462
+ super(_Conflict.status, headers, data);
429
463
  }
430
- static is(value) {
431
- return typeof value === "object" && value !== null && KIND in value && value[KIND] === this.kind;
464
+ static create(status, headers, data) {
465
+ return new this(headers, data);
432
466
  }
433
467
  };
434
468
  var Gone = class _Gone extends APIError {
435
- static kind = Symbol.for("Gone");
436
469
  static status = 410;
437
- constructor(data) {
438
- super(_Gone.status, data);
439
- }
440
- static create(status, data) {
441
- Object.defineProperty(data, KIND, { value: this.kind });
442
- return new this(data);
470
+ constructor(headers, data) {
471
+ super(_Gone.status, headers, data);
443
472
  }
444
- static is(value) {
445
- return typeof value === "object" && value !== null && KIND in value && value[KIND] === this.kind;
473
+ static create(status, headers, data) {
474
+ return new this(headers, data);
446
475
  }
447
476
  };
448
477
  var PreconditionFailed = class _PreconditionFailed extends APIError {
449
- static kind = Symbol.for("PreconditionFailed");
450
478
  static status = 412;
451
- constructor(data) {
452
- super(_PreconditionFailed.status, data);
453
- }
454
- static create(status, data) {
455
- Object.defineProperty(data, KIND, { value: this.kind });
456
- return new this(data);
479
+ constructor(headers, data) {
480
+ super(_PreconditionFailed.status, headers, data);
457
481
  }
458
- static is(value) {
459
- return typeof value === "object" && value !== null && KIND in value && value[KIND] === this.kind;
482
+ static create(status, headers, data) {
483
+ return new this(headers, data);
460
484
  }
461
485
  };
462
486
  var UnprocessableEntity = class _UnprocessableEntity extends APIError {
463
- static kind = Symbol.for("UnprocessableEntity");
464
487
  static status = 422;
465
- constructor(data) {
466
- super(_UnprocessableEntity.status, data);
467
- }
468
- static create(status, data) {
469
- Object.defineProperty(data, KIND, { value: this.kind });
470
- return new this(data);
488
+ constructor(headers, data) {
489
+ super(_UnprocessableEntity.status, headers, data);
471
490
  }
472
- static is(value) {
473
- return typeof value === "object" && value !== null && KIND in value && value[KIND] === this.kind;
491
+ static create(status, headers, data) {
492
+ return new this(headers, data);
474
493
  }
475
494
  };
476
495
  var TooManyRequests = class _TooManyRequests extends APIError {
477
- static kind = Symbol.for("TooManyRequests");
478
496
  static status = 429;
479
- constructor(data) {
480
- super(_TooManyRequests.status, data);
481
- }
482
- static create(status, data) {
483
- Object.defineProperty(data, KIND, { value: this.kind });
484
- return new this(data);
497
+ constructor(headers, data) {
498
+ super(_TooManyRequests.status, headers, data);
485
499
  }
486
- static is(value) {
487
- return typeof value === "object" && value !== null && KIND in value && value[KIND] === this.kind;
500
+ static create(status, headers, data) {
501
+ return new this(headers, data);
488
502
  }
489
503
  };
490
504
  var PayloadTooLarge = class _PayloadTooLarge extends APIError {
491
- static kind = Symbol.for("PayloadTooLarge");
492
505
  static status = 413;
493
- constructor(data) {
494
- super(_PayloadTooLarge.status, data);
506
+ constructor(headers, data) {
507
+ super(_PayloadTooLarge.status, headers, data);
495
508
  }
496
- static create(status, data) {
497
- Object.defineProperty(data, KIND, { value: this.kind });
498
- return new this(data);
499
- }
500
- static is(value) {
501
- return typeof value === "object" && value !== null && KIND in value && value[KIND] === this.kind;
509
+ static create(status, headers, data) {
510
+ return new this(headers, data);
502
511
  }
503
512
  };
504
513
  var UnsupportedMediaType = class _UnsupportedMediaType extends APIError {
505
- static kind = Symbol.for("UnsupportedMediaType");
506
514
  static status = 415;
507
- constructor(data) {
508
- super(_UnsupportedMediaType.status, data);
515
+ constructor(headers, data) {
516
+ super(_UnsupportedMediaType.status, headers, data);
509
517
  }
510
- static create(status, data) {
511
- Object.defineProperty(data, KIND, { value: this.kind });
512
- return new this(data);
513
- }
514
- static is(value) {
515
- return typeof value === "object" && value !== null && KIND in value && value[KIND] === this.kind;
518
+ static create(status, headers, data) {
519
+ return new this(headers, data);
516
520
  }
517
521
  };
518
522
  var InternalServerError = class _InternalServerError extends APIError {
519
- static kind = Symbol.for("InternalServerError");
520
523
  static status = 500;
521
- constructor(data) {
522
- super(_InternalServerError.status, data);
523
- }
524
- static create(status, data) {
525
- Object.defineProperty(data, KIND, { value: this.kind });
526
- return new this(data);
524
+ constructor(headers, data) {
525
+ super(_InternalServerError.status, headers, data);
527
526
  }
528
- static is(value) {
529
- return typeof value === "object" && value !== null && KIND in value && value[KIND] === this.kind;
527
+ static create(status, headers, data) {
528
+ return new this(headers, data);
530
529
  }
531
530
  };
532
531
  var NotImplemented = class _NotImplemented extends APIError {
533
- static kind = Symbol.for("NotImplemented");
534
532
  static status = 501;
535
- constructor(data) {
536
- super(_NotImplemented.status, data);
537
- }
538
- static create(status, data) {
539
- Object.defineProperty(data, KIND, { value: this.kind });
540
- return new this(data);
533
+ constructor(headers, data) {
534
+ super(_NotImplemented.status, headers, data);
541
535
  }
542
- static is(value) {
543
- return typeof value === "object" && value !== null && KIND in value && value[KIND] === this.kind;
536
+ static create(status, headers, data) {
537
+ return new this(headers, data);
544
538
  }
545
539
  };
546
540
  var BadGateway = class _BadGateway extends APIError {
547
- static kind = Symbol.for("BadGateway");
548
541
  static status = 502;
549
- constructor(data) {
550
- super(_BadGateway.status, data);
551
- }
552
- static create(status, data) {
553
- Object.defineProperty(data, KIND, { value: this.kind });
554
- return new this(data);
542
+ constructor(headers, data) {
543
+ super(_BadGateway.status, headers, data);
555
544
  }
556
- static is(value) {
557
- return typeof value === "object" && value !== null && KIND in value && value[KIND] === this.kind;
545
+ static create(status, headers, data) {
546
+ return new this(headers, data);
558
547
  }
559
548
  };
560
549
  var ServiceUnavailable = class _ServiceUnavailable extends APIError {
561
- static kind = Symbol.for("ServiceUnavailable");
562
550
  static status = 503;
563
- constructor(data) {
564
- super(_ServiceUnavailable.status, data);
551
+ constructor(headers, data) {
552
+ super(_ServiceUnavailable.status, headers, data);
565
553
  }
566
- static create(status, data) {
567
- Object.defineProperty(data, KIND, { value: this.kind });
568
- return new this(data);
569
- }
570
- static is(value) {
571
- return typeof value === "object" && value !== null && KIND in value && value[KIND] === this.kind;
554
+ static create(status, headers, data) {
555
+ return new this(headers, data);
572
556
  }
573
557
  };
574
558
  var GatewayTimeout = class _GatewayTimeout extends APIError {
575
- static kind = Symbol.for("GatewayTimeout");
576
559
  static status = 504;
577
- constructor(data) {
578
- super(_GatewayTimeout.status, data);
560
+ constructor(headers, data) {
561
+ super(_GatewayTimeout.status, headers, data);
579
562
  }
580
- static create(status, data) {
581
- Object.defineProperty(data, KIND, { value: this.kind });
582
- return new this(data);
583
- }
584
- static is(value) {
585
- return typeof value === "object" && value !== null && KIND in value && value[KIND] === this.kind;
563
+ static create(status, headers, data) {
564
+ return new this(headers, data);
586
565
  }
587
566
  };
588
567
 
589
568
  // packages/rpc/src/lib/http/dispatcher.ts
590
- var fetchType = z.function().args(z.custom()).returns(z.promise(z.custom())).optional();
591
- async function parse2(outputs, response) {
569
+ var fetchType = z.function({
570
+ input: [z.custom()],
571
+ output: z.custom()
572
+ }).optional();
573
+ async function parse2(outputs, response, mapper) {
592
574
  let output = null;
593
575
  let parser = buffered;
594
576
  for (const outputType of outputs) {
595
577
  if ("parser" in outputType) {
596
- parser = outputType.parser;
597
578
  if (isTypeOf(outputType.type, APIResponse)) {
598
579
  if (response.status === outputType.type.status) {
580
+ parser = outputType.parser;
599
581
  output = outputType.type;
600
582
  break;
601
583
  }
@@ -608,13 +590,20 @@ async function parse2(outputs, response) {
608
590
  }
609
591
  }
610
592
  if (response.ok) {
593
+ const data = await parser(response);
594
+ const mapped = mapper ? mapper(data) : data;
611
595
  const apiresponse = (output || APIResponse).create(
612
596
  response.status,
613
- await parser(response)
597
+ response.headers,
598
+ mapped
614
599
  );
615
600
  return apiresponse;
616
601
  }
617
- throw (output || APIError).create(response.status, await parser(response));
602
+ throw (output || APIError).create(
603
+ response.status,
604
+ response.headers,
605
+ await parser(response)
606
+ );
618
607
  }
619
608
  function isTypeOf(instance, baseType) {
620
609
  if (instance === baseType) {
@@ -633,7 +622,7 @@ var Dispatcher = class {
633
622
  this.#interceptors = interceptors;
634
623
  this.#fetch = fetch2;
635
624
  }
636
- async send(config, outputs, signal) {
625
+ async send(config, outputs, signal, mapper) {
637
626
  for (const interceptor of this.#interceptors) {
638
627
  if (interceptor.before) {
639
628
  config = await interceptor.before(config);
@@ -647,13 +636,52 @@ var Dispatcher = class {
647
636
  response = await interceptor.after(response.clone());
648
637
  }
649
638
  }
639
+ if (mapper) {
640
+ return await parse2(outputs, response, mapper);
641
+ }
650
642
  return await parse2(outputs, response);
651
643
  }
652
644
  };
653
645
 
654
- // packages/rpc/src/lib/zod.ts
646
+ // packages/rpc/src/lib/http/parser.ts
655
647
  import { z as z2 } from "zod";
648
+ var ParseError = class extends Error {
649
+ data;
650
+ constructor(data) {
651
+ super("Validation failed");
652
+ this.name = "ParseError";
653
+ this.data = data;
654
+ }
655
+ };
656
+ function parseInput(schema, input) {
657
+ const result = schema.safeParse(input);
658
+ if (!result.success) {
659
+ const error = z2.flattenError(result.error, (issue) => issue);
660
+ throw new ParseError(error);
661
+ }
662
+ return result.data;
663
+ }
664
+
665
+ // packages/rpc/src/lib/rpc.ts
666
+ import { jsonSchema, tool } from "ai";
667
+ import { z as z4 } from "zod";
668
+ import {
669
+ forEachOperation,
670
+ loadSpec,
671
+ toIR
672
+ } from "@sdk-it/spec";
673
+ import {
674
+ buildInput,
675
+ operationSchema,
676
+ toHttpOutput
677
+ } from "@sdk-it/typescript";
678
+
679
+ // packages/rpc/src/lib/zod.ts
680
+ import { z as z3 } from "zod";
656
681
  import { followRef, isRef } from "@sdk-it/core";
682
+ var isoTime = z3.string().regex(
683
+ /^([01]\d|2[0-3]):[0-5]\d(:[0-5]\d(\.\d+)?)?(Z|[+-]([01]\d|2[0-3]):[0-5]\d)?$/
684
+ );
657
685
  var RuntimeZodConverter = class {
658
686
  #spec;
659
687
  constructor(spec) {
@@ -667,13 +695,13 @@ var RuntimeZodConverter = class {
667
695
  const isRequired = required.includes(key);
668
696
  shape[key] = this.handle(propSchema, isRequired);
669
697
  }
670
- let result = z2.object(shape);
698
+ let result = z3.object(shape);
671
699
  if (schema.additionalProperties) {
672
700
  if (typeof schema.additionalProperties === "object") {
673
701
  const addPropSchema = this.handle(schema.additionalProperties, true);
674
702
  result = result.catchall(addPropSchema);
675
703
  } else if (schema.additionalProperties === true) {
676
- result = result.catchall(z2.unknown());
704
+ result = result.catchall(z3.unknown());
677
705
  }
678
706
  }
679
707
  return result;
@@ -681,20 +709,20 @@ var RuntimeZodConverter = class {
681
709
  #array(schema) {
682
710
  const { items } = schema;
683
711
  if (!items) {
684
- let result2 = z2.array(z2.unknown());
712
+ let result2 = z3.array(z3.unknown());
685
713
  if (schema.default !== void 0) {
686
- result2 = z2.array(z2.unknown()).default(schema.default);
714
+ result2 = z3.array(z3.unknown()).default(schema.default);
687
715
  }
688
716
  return result2;
689
717
  }
690
718
  if (Array.isArray(items)) {
691
719
  const tupleItems = items.map((sub) => this.handle(sub, true));
692
- return z2.tuple(tupleItems);
720
+ return z3.tuple(tupleItems);
693
721
  }
694
722
  const itemsSchema = this.handle(items, true);
695
- let result = z2.array(itemsSchema);
723
+ let result = z3.array(itemsSchema);
696
724
  if (schema.default !== void 0) {
697
- result = z2.array(itemsSchema).default(schema.default);
725
+ result = z3.array(itemsSchema).default(schema.default);
698
726
  }
699
727
  return result;
700
728
  }
@@ -708,12 +736,12 @@ var RuntimeZodConverter = class {
708
736
  if (!right.length) {
709
737
  return left;
710
738
  }
711
- return z2.intersection(left, this.#toIntersection(right));
739
+ return z3.intersection(left, this.#toIntersection(right));
712
740
  }
713
741
  allOf(schemas) {
714
742
  const allOfSchemas = schemas.map((sub) => this.handle(sub, true));
715
743
  if (allOfSchemas.length === 0) {
716
- return z2.unknown();
744
+ return z3.unknown();
717
745
  }
718
746
  if (allOfSchemas.length === 1) {
719
747
  return allOfSchemas[0];
@@ -725,74 +753,66 @@ var RuntimeZodConverter = class {
725
753
  if (anyOfSchemas.length === 1) {
726
754
  return anyOfSchemas[0];
727
755
  }
728
- return z2.union(anyOfSchemas);
756
+ return z3.union(anyOfSchemas);
729
757
  }
730
758
  oneOf(schemas) {
731
759
  const oneOfSchemas = schemas.map((sub) => this.handle(sub, true));
732
760
  if (oneOfSchemas.length === 1) {
733
761
  return oneOfSchemas[0];
734
762
  }
735
- return z2.union(oneOfSchemas);
763
+ return z3.xor(oneOfSchemas);
736
764
  }
737
765
  enum(type, values) {
738
766
  if (values.length === 1) {
739
- return z2.literal(values[0]);
767
+ return z3.literal(values[0]);
740
768
  }
741
- if (type === "integer") {
742
- if (values.length >= 2) {
743
- const [first, second, ...rest] = values.map(
744
- (val) => z2.literal(val)
745
- );
746
- return z2.union([first, second, ...rest]);
747
- }
748
- return z2.literal(values[0]);
769
+ if (values.every((value) => typeof value === "string")) {
770
+ return z3.enum(values);
749
771
  }
750
- const stringValues = values;
751
- if (stringValues.length >= 2) {
752
- const [first, ...rest] = stringValues;
753
- return z2.enum([first, ...rest]);
754
- }
755
- return z2.literal(stringValues[0]);
772
+ return z3.literal(values);
756
773
  }
757
774
  /**
758
775
  * Handle a `string` schema with possible format keywords (JSON Schema).
759
776
  */
760
777
  string(schema) {
761
778
  if (schema.contentEncoding === "binary") {
762
- return z2.custom();
779
+ return z3.custom();
763
780
  }
764
- const base = schema["x-zod-type"] === "coerce-string" ? z2.coerce.string() : z2.string();
781
+ const coerced = schema["x-zod-type"] === "coerce-string";
782
+ const base = coerced ? z3.coerce.string() : z3.string();
783
+ const withFormat = (format) => coerced ? base.pipe(format) : format;
765
784
  switch (schema.format) {
766
785
  case "date-time":
767
786
  case "datetime":
768
787
  if (schema["x-zod-type"] === "coerce-date") {
769
- return z2.coerce.date();
788
+ return z3.coerce.date();
770
789
  } else if (schema["x-zod-type"] === "date") {
771
- return z2.date();
790
+ return z3.date();
772
791
  } else {
773
- return base.datetime();
792
+ return withFormat(z3.iso.datetime({ offset: true }));
774
793
  }
775
794
  case "date":
776
- return base.date();
795
+ return withFormat(z3.iso.date());
777
796
  case "time":
778
- return base;
779
- // Could add regex for HH:MM:SS format
797
+ return withFormat(isoTime);
780
798
  case "email":
781
- return base.email();
799
+ return withFormat(z3.email());
782
800
  case "uuid":
783
- return base.uuid();
801
+ return withFormat(z3.guid());
784
802
  case "url":
785
803
  case "uri":
786
- return base.url();
804
+ return withFormat(z3.url());
787
805
  case "ipv4":
788
- return base.ip({ version: "v4" });
806
+ return withFormat(z3.ipv4());
789
807
  case "ipv6":
790
- return base.ip({ version: "v6" });
808
+ return withFormat(z3.ipv6());
809
+ case "cidrv4":
810
+ return withFormat(z3.cidrv4());
811
+ case "cidrv6":
812
+ return withFormat(z3.cidrv6());
791
813
  case "byte":
792
814
  case "binary":
793
- return z2.custom();
794
- case "int64":
795
- return base;
815
+ return z3.custom();
796
816
  default:
797
817
  return base;
798
818
  }
@@ -801,23 +821,7 @@ var RuntimeZodConverter = class {
801
821
  * Handle number/integer constraints from OpenAPI/JSON Schema.
802
822
  */
803
823
  #number(schema) {
804
- if (schema.format === "int64") {
805
- let base2 = schema["x-zod-type"] === "coerce-bigint" ? z2.coerce.bigint() : z2.bigint();
806
- if (typeof schema.exclusiveMinimum === "number") {
807
- base2 = base2.gt(BigInt(schema.exclusiveMinimum));
808
- }
809
- if (typeof schema.exclusiveMaximum === "number") {
810
- base2 = base2.lt(BigInt(schema.exclusiveMaximum));
811
- }
812
- if (typeof schema.minimum === "number") {
813
- base2 = base2.min(BigInt(schema.minimum));
814
- }
815
- if (typeof schema.maximum === "number") {
816
- base2 = base2.max(BigInt(schema.maximum));
817
- }
818
- return base2;
819
- }
820
- let base = schema["x-zod-type"] === "coerce-number" ? z2.coerce.number() : z2.number();
824
+ let base = schema["x-zod-type"] === "coerce-number" ? z3.coerce.number() : z3.number();
821
825
  if (schema.type === "integer" || schema.format === "int32") {
822
826
  base = base.int();
823
827
  }
@@ -835,7 +839,7 @@ var RuntimeZodConverter = class {
835
839
  }
836
840
  if (typeof schema.multipleOf === "number") {
837
841
  const multipleOf = schema.multipleOf;
838
- base = base.refine(
842
+ return base.refine(
839
843
  (val) => Number.isInteger(Number(val) / multipleOf),
840
844
  `Must be a multiple of ${multipleOf}`
841
845
  );
@@ -856,7 +860,7 @@ var RuntimeZodConverter = class {
856
860
  base = this.#number(schema);
857
861
  break;
858
862
  case "boolean":
859
- base = schema["x-zod-type"] === "coerce-boolean" ? z2.coerce.boolean() : z2.boolean();
863
+ base = schema["x-zod-type"] === "coerce-boolean" ? z3.union([z3.boolean(), z3.stringbool()]) : z3.boolean();
860
864
  break;
861
865
  case "object":
862
866
  base = this.#object(schema);
@@ -865,10 +869,10 @@ var RuntimeZodConverter = class {
865
869
  base = this.#array(schema);
866
870
  break;
867
871
  case "null":
868
- base = z2.null();
872
+ base = z3.null();
869
873
  break;
870
874
  default:
871
- base = z2.unknown();
875
+ base = z3.unknown();
872
876
  break;
873
877
  }
874
878
  if (nullable) {
@@ -878,7 +882,7 @@ var RuntimeZodConverter = class {
878
882
  base = base.optional();
879
883
  }
880
884
  if (schema.default !== void 0) {
881
- const defaultValue = schema.format === "int64" ? BigInt(schema.default) : (schema["x-zod-type"] === "date" || schema["x-zod-type"] === "coerce-date") && schema.default ? new Date(schema.default) : schema.default;
885
+ const defaultValue = (schema["x-zod-type"] === "date" || schema["x-zod-type"] === "coerce-date") && schema.default ? new Date(schema.default) : schema.default;
882
886
  base = base.default(defaultValue);
883
887
  }
884
888
  if (schema["x-prefix"]) {
@@ -902,7 +906,7 @@ var RuntimeZodConverter = class {
902
906
  }
903
907
  return result2;
904
908
  }
905
- let result = z2.unknown();
909
+ let result = z3.unknown();
906
910
  if (schema.allOf && Array.isArray(schema.allOf)) {
907
911
  result = this.allOf(schema.allOf);
908
912
  if (!required) {
@@ -920,30 +924,8 @@ var RuntimeZodConverter = class {
920
924
  }
921
925
  } else if (schema.enum && Array.isArray(schema.enum)) {
922
926
  result = this.enum(schema.type, schema.enum);
923
- if (schema.default !== void 0 && schema.enum.includes(schema.default)) {
924
- const defaultValue = schema.default;
925
- const enumValues = schema.enum;
926
- const enumType = schema.type;
927
- if (enumValues.length === 1) {
928
- result = z2.literal(enumValues[0]).default(defaultValue);
929
- } else if (enumType === "integer") {
930
- if (enumValues.length >= 2) {
931
- const [first, second, ...rest] = enumValues.map(
932
- (val) => z2.literal(val)
933
- );
934
- result = z2.union([first, second, ...rest]).default(defaultValue);
935
- } else {
936
- result = z2.literal(enumValues[0]).default(defaultValue);
937
- }
938
- } else {
939
- const stringValues = enumValues;
940
- if (stringValues.length >= 2) {
941
- const [first, ...rest] = stringValues;
942
- result = z2.enum([first, ...rest]).default(defaultValue);
943
- } else {
944
- result = z2.literal(stringValues[0]).default(defaultValue);
945
- }
946
- }
927
+ if (schema.default !== void 0 && schema.enum.includes(schema.default) && required) {
928
+ result = result.default(schema.default);
947
929
  }
948
930
  if (!required) {
949
931
  result = result.optional();
@@ -956,21 +938,15 @@ var RuntimeZodConverter = class {
956
938
  types.push("null");
957
939
  }
958
940
  if (!types.length) {
959
- result = required ? z2.unknown() : z2.unknown().optional();
941
+ result = required ? z3.unknown() : z3.unknown().optional();
960
942
  } else if (types.length > 1) {
961
943
  const realTypes = types.filter((t) => t !== "null");
962
944
  if (realTypes.length === 1 && types.includes("null")) {
963
945
  result = this.normal(realTypes[0], schema, required, true);
964
946
  } else {
965
- const subSchemas = types.map((t) => this.normal(t, schema, true));
966
- if (subSchemas.length >= 2) {
967
- const [first, second, ...rest] = subSchemas;
968
- result = z2.union([first, second, ...rest]);
969
- if (!required) {
970
- result = result.optional();
971
- }
972
- } else {
973
- result = this.normal(types[0], schema, required, false);
947
+ result = z3.union(types.map((t) => this.normal(t, schema, true)));
948
+ if (!required) {
949
+ result = result.optional();
974
950
  }
975
951
  }
976
952
  } else {
@@ -989,29 +965,36 @@ function schemaToZod(schema, spec, options) {
989
965
  }
990
966
 
991
967
  // packages/rpc/src/lib/rpc.ts
992
- var baseUrlSchema = z3.union([
993
- z3.string(),
994
- z3.function().returns(z3.union([z3.string(), z3.promise(z3.string())]))
995
- ]).transform(async (baseUrl) => {
996
- if (typeof baseUrl === "function") {
997
- return Promise.resolve(baseUrl());
998
- }
999
- return baseUrl;
968
+ var callable = z4.custom(
969
+ (value) => typeof value === "function"
970
+ );
971
+ var baseUrlSchema = z4.union([z4.string(), callable]).transform(async (baseUrl, ctx) => {
972
+ const value = typeof baseUrl === "function" ? await baseUrl() : baseUrl;
973
+ if (typeof value !== "string") {
974
+ ctx.addIssue({
975
+ code: "custom",
976
+ message: "baseUrl must resolve to a string"
977
+ });
978
+ return z4.NEVER;
979
+ }
980
+ return value;
1000
981
  });
1001
- var optionsSchema = z3.object({
1002
- token: z3.union([
1003
- z3.string(),
1004
- z3.function().returns(z3.union([z3.string(), z3.promise(z3.string())]))
1005
- ]).optional().transform(async (token) => {
982
+ var optionsSchema = z4.object({
983
+ token: z4.union([z4.string(), callable]).optional().transform(async (token, ctx) => {
1006
984
  if (!token) return void 0;
1007
- if (typeof token === "function") {
1008
- token = await Promise.resolve(token());
985
+ const value = typeof token === "function" ? await token() : token;
986
+ if (typeof value !== "string") {
987
+ ctx.addIssue({
988
+ code: "custom",
989
+ message: "token must resolve to a string"
990
+ });
991
+ return z4.NEVER;
1009
992
  }
1010
- return `Bearer ${token}`;
993
+ return `Bearer ${value}`;
1011
994
  }),
1012
995
  fetch: fetchType,
1013
996
  baseUrl: baseUrlSchema,
1014
- headers: z3.record(z3.string()).optional()
997
+ headers: z4.record(z4.string(), z4.string()).optional()
1015
998
  });
1016
999
  function inputToPath(operation, inputs) {
1017
1000
  const inputHeaders = [];
@@ -1052,7 +1035,7 @@ var Client = class {
1052
1035
  async request(endpoint, input, options) {
1053
1036
  const route = this.schemas[endpoint];
1054
1037
  const withDefaultInputs = Object.assign({}, this.#defaultInputs, input);
1055
- const parsedInput = input;
1038
+ const parsedInput = parseInput(route.schema, withDefaultInputs);
1056
1039
  const clientOptions = await optionsSchema.parseAsync(this.options);
1057
1040
  const result = await route.dispatch(parsedInput, {
1058
1041
  fetch: clientOptions.fetch,
@@ -1165,9 +1148,8 @@ async function toAgents(openapi, options) {
1165
1148
  groups[entry.tag].tools[toolInfo?.name || operation["x-fn-name"]] = tool({
1166
1149
  type: "function",
1167
1150
  description: toolInfo?.description || operation.description || operation.summary,
1168
- inputSchema: client.schemas[endpoint].schema,
1151
+ inputSchema: toToolSchema(client.schemas[endpoint].schema),
1169
1152
  execute: async (input) => {
1170
- console.log("Executing tool with input:", input);
1171
1153
  const response = await client.request(endpoint, input);
1172
1154
  return JSON.stringify(response);
1173
1155
  }
@@ -1194,13 +1176,121 @@ async function toAgents(openapi, options) {
1194
1176
  function defaultSerializer(ct) {
1195
1177
  throw new Error(`Unsupported content type: ${ct}`);
1196
1178
  }
1179
+ var TOOL_COERCE_MARKER = "x-sdkit-tool-coerce";
1180
+ function coerceToolValue(value, schema) {
1181
+ if (!schema || typeof schema !== "object" || value === null || value === void 0) {
1182
+ return value;
1183
+ }
1184
+ const marker = schema[TOOL_COERCE_MARKER];
1185
+ if (marker === "date" && typeof value === "string") {
1186
+ const date = new Date(value);
1187
+ return Number.isNaN(date.getTime()) ? value : date;
1188
+ }
1189
+ if (Array.isArray(value)) {
1190
+ if (Array.isArray(schema.items)) {
1191
+ return value.map(
1192
+ (item, index) => coerceToolValue(item, schema.items[index] ?? schema.additionalItems)
1193
+ );
1194
+ }
1195
+ if (schema.items) {
1196
+ return value.map((item) => coerceToolValue(item, schema.items));
1197
+ }
1198
+ return value;
1199
+ }
1200
+ if (typeof value === "object" && (schema.properties || schema.additionalProperties)) {
1201
+ const out = { ...value };
1202
+ for (const [key, propValue] of Object.entries(out)) {
1203
+ const propSchema = schema.properties?.[key] ?? (typeof schema.additionalProperties === "object" ? schema.additionalProperties : void 0);
1204
+ if (propSchema) out[key] = coerceToolValue(propValue, propSchema);
1205
+ }
1206
+ return out;
1207
+ }
1208
+ for (const key of ["anyOf", "oneOf", "allOf"]) {
1209
+ if (Array.isArray(schema[key])) {
1210
+ for (const member of schema[key]) {
1211
+ const coerced = coerceToolValue(value, member);
1212
+ if (coerced !== value) return coerced;
1213
+ }
1214
+ }
1215
+ }
1216
+ return value;
1217
+ }
1218
+ function toToolSchema(schema) {
1219
+ const marked = z4.toJSONSchema(schema, {
1220
+ target: "draft-7",
1221
+ io: "input",
1222
+ unrepresentable: "any",
1223
+ override(ctx) {
1224
+ const def = ctx.zodSchema._zod.def;
1225
+ const json2 = ctx.jsonSchema;
1226
+ if (def.type === "date") {
1227
+ json2.type = "string";
1228
+ json2.format = "date-time";
1229
+ json2[TOOL_COERCE_MARKER] = "date";
1230
+ }
1231
+ }
1232
+ });
1233
+ const advertised = JSON.parse(
1234
+ JSON.stringify(
1235
+ marked,
1236
+ (key, value) => key === TOOL_COERCE_MARKER ? void 0 : value
1237
+ )
1238
+ );
1239
+ return jsonSchema(advertised, {
1240
+ validate: (value) => {
1241
+ const coerced = coerceToolValue(value, marked);
1242
+ const result = schema.safeParse(coerced);
1243
+ return result.success ? { success: true, value: coerced } : { success: false, error: result.error };
1244
+ }
1245
+ });
1246
+ }
1197
1247
  export {
1248
+ APIError,
1249
+ APIResponse,
1250
+ Accepted,
1251
+ BadGateway,
1252
+ BadRequest,
1198
1253
  Client,
1254
+ Conflict,
1255
+ Created,
1256
+ Dispatcher,
1257
+ Forbidden,
1258
+ GatewayTimeout,
1259
+ Gone,
1260
+ InternalServerError,
1261
+ MethodNotAllowed,
1262
+ NoContent,
1263
+ NotAcceptable,
1264
+ NotFound,
1265
+ NotImplemented,
1266
+ Ok,
1267
+ ParseError,
1268
+ PayloadTooLarge,
1269
+ PaymentRequired,
1270
+ PreconditionFailed,
1199
1271
  RuntimeZodConverter,
1272
+ ServiceUnavailable,
1273
+ TooManyRequests,
1274
+ Unauthorized,
1275
+ UnprocessableEntity,
1276
+ UnsupportedMediaType,
1277
+ createBaseUrlInterceptor,
1278
+ createDetailedLogInterceptor,
1279
+ createHeadersInterceptor,
1200
1280
  createRpc,
1281
+ empty,
1282
+ fetchType,
1283
+ formdata,
1201
1284
  inputToPath,
1285
+ isTypeOf,
1286
+ json,
1287
+ logInterceptor,
1288
+ parse2 as parse,
1289
+ parseInput,
1202
1290
  rpc,
1203
1291
  schemaToZod,
1204
- toAgents
1292
+ toAgents,
1293
+ toRequest,
1294
+ urlencoded
1205
1295
  };
1206
1296
  //# sourceMappingURL=index.js.map