@gtmi/ramp-agent-client 0.0.1

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.
@@ -0,0 +1,1288 @@
1
+ import { z } from 'zod';
2
+
3
+ // This file is auto-generated by @hey-api/openapi-ts
4
+ const jsonBodySerializer = {
5
+ bodySerializer: (body)=>JSON.stringify(body, (_key, value)=>typeof value === 'bigint' ? value.toString() : value)
6
+ };
7
+
8
+ // This file is auto-generated by @hey-api/openapi-ts
9
+ function createSseClient({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }) {
10
+ let lastEventId;
11
+ const sleep = sseSleepFn ?? ((ms)=>new Promise((resolve)=>setTimeout(resolve, ms)));
12
+ const createStream = async function*() {
13
+ let retryDelay = sseDefaultRetryDelay ?? 3000;
14
+ let attempt = 0;
15
+ const signal = options.signal ?? new AbortController().signal;
16
+ while(true){
17
+ if (signal.aborted) break;
18
+ attempt++;
19
+ const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers);
20
+ if (lastEventId !== undefined) {
21
+ headers.set('Last-Event-ID', lastEventId);
22
+ }
23
+ try {
24
+ const requestInit = {
25
+ redirect: 'follow',
26
+ ...options,
27
+ body: options.serializedBody,
28
+ headers,
29
+ signal
30
+ };
31
+ let request = new Request(url, requestInit);
32
+ if (onRequest) {
33
+ request = await onRequest(url, requestInit);
34
+ }
35
+ // fetch must be assigned here, otherwise it would throw the error:
36
+ // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
37
+ const _fetch = options.fetch ?? globalThis.fetch;
38
+ const response = await _fetch(request);
39
+ if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`);
40
+ if (!response.body) throw new Error('No body in SSE response');
41
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
42
+ let buffer = '';
43
+ const abortHandler = ()=>{
44
+ try {
45
+ reader.cancel();
46
+ } catch {
47
+ // noop
48
+ }
49
+ };
50
+ signal.addEventListener('abort', abortHandler);
51
+ try {
52
+ while(true){
53
+ const { done, value } = await reader.read();
54
+ if (done) break;
55
+ buffer += value;
56
+ buffer = buffer.replace(/\r\n?/g, '\n'); // normalize line endings
57
+ const chunks = buffer.split('\n\n');
58
+ buffer = chunks.pop() ?? '';
59
+ for (const chunk of chunks){
60
+ const lines = chunk.split('\n');
61
+ const dataLines = [];
62
+ let eventName;
63
+ for (const line of lines){
64
+ if (line.startsWith('data:')) {
65
+ dataLines.push(line.replace(/^data:\s*/, ''));
66
+ } else if (line.startsWith('event:')) {
67
+ eventName = line.replace(/^event:\s*/, '');
68
+ } else if (line.startsWith('id:')) {
69
+ lastEventId = line.replace(/^id:\s*/, '');
70
+ } else if (line.startsWith('retry:')) {
71
+ const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10);
72
+ if (!Number.isNaN(parsed)) {
73
+ retryDelay = parsed;
74
+ }
75
+ }
76
+ }
77
+ let data;
78
+ let parsedJson = false;
79
+ if (dataLines.length) {
80
+ const rawData = dataLines.join('\n');
81
+ try {
82
+ data = JSON.parse(rawData);
83
+ parsedJson = true;
84
+ } catch {
85
+ data = rawData;
86
+ }
87
+ }
88
+ if (parsedJson) {
89
+ if (responseValidator) {
90
+ await responseValidator(data);
91
+ }
92
+ if (responseTransformer) {
93
+ data = await responseTransformer(data);
94
+ }
95
+ }
96
+ onSseEvent?.({
97
+ data,
98
+ event: eventName,
99
+ id: lastEventId,
100
+ retry: retryDelay
101
+ });
102
+ if (dataLines.length) {
103
+ yield data;
104
+ }
105
+ }
106
+ }
107
+ } finally{
108
+ signal.removeEventListener('abort', abortHandler);
109
+ reader.releaseLock();
110
+ }
111
+ break; // exit loop on normal completion
112
+ } catch (error) {
113
+ // connection failed or aborted; retry after delay
114
+ onSseError?.(error);
115
+ if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) {
116
+ break; // stop after firing error
117
+ }
118
+ // exponential backoff: double retry each attempt, cap at 30s
119
+ const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000);
120
+ await sleep(backoff);
121
+ }
122
+ }
123
+ };
124
+ const stream = createStream();
125
+ return {
126
+ stream
127
+ };
128
+ }
129
+
130
+ // This file is auto-generated by @hey-api/openapi-ts
131
+ const separatorArrayExplode = (style)=>{
132
+ switch(style){
133
+ case 'label':
134
+ return '.';
135
+ case 'matrix':
136
+ return ';';
137
+ case 'simple':
138
+ return ',';
139
+ default:
140
+ return '&';
141
+ }
142
+ };
143
+ const separatorArrayNoExplode = (style)=>{
144
+ switch(style){
145
+ case 'form':
146
+ return ',';
147
+ case 'pipeDelimited':
148
+ return '|';
149
+ case 'spaceDelimited':
150
+ return '%20';
151
+ default:
152
+ return ',';
153
+ }
154
+ };
155
+ const separatorObjectExplode = (style)=>{
156
+ switch(style){
157
+ case 'label':
158
+ return '.';
159
+ case 'matrix':
160
+ return ';';
161
+ case 'simple':
162
+ return ',';
163
+ default:
164
+ return '&';
165
+ }
166
+ };
167
+ const serializeArrayParam = ({ allowReserved, explode, name, style, value })=>{
168
+ if (!explode) {
169
+ const joinedValues = (allowReserved ? value : value.map((v)=>encodeURIComponent(v))).join(separatorArrayNoExplode(style));
170
+ switch(style){
171
+ case 'label':
172
+ return `.${joinedValues}`;
173
+ case 'matrix':
174
+ return `;${name}=${joinedValues}`;
175
+ case 'simple':
176
+ return joinedValues;
177
+ default:
178
+ return `${name}=${joinedValues}`;
179
+ }
180
+ }
181
+ const separator = separatorArrayExplode(style);
182
+ const joinedValues = value.map((v)=>{
183
+ if (style === 'label' || style === 'simple') {
184
+ return allowReserved ? v : encodeURIComponent(v);
185
+ }
186
+ return serializePrimitiveParam({
187
+ allowReserved,
188
+ name,
189
+ value: v
190
+ });
191
+ }).join(separator);
192
+ return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues;
193
+ };
194
+ const serializePrimitiveParam = ({ allowReserved, name, value })=>{
195
+ if (value === undefined || value === null) {
196
+ return '';
197
+ }
198
+ if (typeof value === 'object') {
199
+ throw new Error('Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.');
200
+ }
201
+ return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
202
+ };
203
+ const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly })=>{
204
+ if (value instanceof Date) {
205
+ return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
206
+ }
207
+ if (style !== 'deepObject' && !explode) {
208
+ let values = [];
209
+ Object.entries(value).forEach(([key, v])=>{
210
+ values = [
211
+ ...values,
212
+ key,
213
+ allowReserved ? v : encodeURIComponent(v)
214
+ ];
215
+ });
216
+ const joinedValues = values.join(',');
217
+ switch(style){
218
+ case 'form':
219
+ return `${name}=${joinedValues}`;
220
+ case 'label':
221
+ return `.${joinedValues}`;
222
+ case 'matrix':
223
+ return `;${name}=${joinedValues}`;
224
+ default:
225
+ return joinedValues;
226
+ }
227
+ }
228
+ const separator = separatorObjectExplode(style);
229
+ const joinedValues = Object.entries(value).map(([key, v])=>serializePrimitiveParam({
230
+ allowReserved,
231
+ name: style === 'deepObject' ? `${name}[${key}]` : key,
232
+ value: v
233
+ })).join(separator);
234
+ return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues;
235
+ };
236
+
237
+ // This file is auto-generated by @hey-api/openapi-ts
238
+ const PATH_PARAM_RE = /\{[^{}]+\}/g;
239
+ const defaultPathSerializer = ({ path, url: _url })=>{
240
+ let url = _url;
241
+ const matches = _url.match(PATH_PARAM_RE);
242
+ if (matches) {
243
+ for (const match of matches){
244
+ let explode = false;
245
+ let name = match.substring(1, match.length - 1);
246
+ let style = 'simple';
247
+ if (name.endsWith('*')) {
248
+ explode = true;
249
+ name = name.substring(0, name.length - 1);
250
+ }
251
+ if (name.startsWith('.')) {
252
+ name = name.substring(1);
253
+ style = 'label';
254
+ } else if (name.startsWith(';')) {
255
+ name = name.substring(1);
256
+ style = 'matrix';
257
+ }
258
+ const value = path[name];
259
+ if (value === undefined || value === null) {
260
+ continue;
261
+ }
262
+ if (Array.isArray(value)) {
263
+ url = url.replace(match, serializeArrayParam({
264
+ explode,
265
+ name,
266
+ style,
267
+ value
268
+ }));
269
+ continue;
270
+ }
271
+ if (typeof value === 'object') {
272
+ url = url.replace(match, serializeObjectParam({
273
+ explode,
274
+ name,
275
+ style,
276
+ value: value,
277
+ valueOnly: true
278
+ }));
279
+ continue;
280
+ }
281
+ if (style === 'matrix') {
282
+ url = url.replace(match, `;${serializePrimitiveParam({
283
+ name,
284
+ value: value
285
+ })}`);
286
+ continue;
287
+ }
288
+ const replaceValue = encodeURIComponent(style === 'label' ? `.${value}` : value);
289
+ url = url.replace(match, replaceValue);
290
+ }
291
+ }
292
+ return url;
293
+ };
294
+ const getUrl = ({ baseUrl, path, query, querySerializer, url: _url })=>{
295
+ const pathUrl = _url.startsWith('/') ? _url : `/${_url}`;
296
+ let url = (baseUrl ?? '') + pathUrl;
297
+ if (path) {
298
+ url = defaultPathSerializer({
299
+ path,
300
+ url
301
+ });
302
+ }
303
+ let search = query ? querySerializer(query) : '';
304
+ if (search.startsWith('?')) {
305
+ search = search.substring(1);
306
+ }
307
+ if (search) {
308
+ url += `?${search}`;
309
+ }
310
+ return url;
311
+ };
312
+ function getValidRequestBody(options) {
313
+ const hasBody = options.body !== undefined;
314
+ const isSerializedBody = hasBody && options.bodySerializer;
315
+ if (isSerializedBody) {
316
+ if ('serializedBody' in options) {
317
+ const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== '';
318
+ return hasSerializedBody ? options.serializedBody : null;
319
+ }
320
+ // not all clients implement a serializedBody property (i.e., client-axios)
321
+ return options.body !== '' ? options.body : null;
322
+ }
323
+ // plain/text body
324
+ if (hasBody) {
325
+ return options.body;
326
+ }
327
+ // no body was provided
328
+ return undefined;
329
+ }
330
+
331
+ // This file is auto-generated by @hey-api/openapi-ts
332
+ const getAuthToken = async (auth, callback)=>{
333
+ const token = typeof callback === 'function' ? await callback(auth) : callback;
334
+ if (!token) {
335
+ return;
336
+ }
337
+ if (auth.scheme === 'bearer') {
338
+ return `Bearer ${token}`;
339
+ }
340
+ if (auth.scheme === 'basic') {
341
+ return `Basic ${btoa(token)}`;
342
+ }
343
+ return token;
344
+ };
345
+
346
+ // This file is auto-generated by @hey-api/openapi-ts
347
+ const createQuerySerializer = ({ parameters = {}, ...args } = {})=>{
348
+ const querySerializer = (queryParams)=>{
349
+ const search = [];
350
+ if (queryParams && typeof queryParams === 'object') {
351
+ for(const name in queryParams){
352
+ const value = queryParams[name];
353
+ if (value === undefined || value === null) {
354
+ continue;
355
+ }
356
+ const options = parameters[name] || args;
357
+ if (Array.isArray(value)) {
358
+ const serializedArray = serializeArrayParam({
359
+ allowReserved: options.allowReserved,
360
+ explode: true,
361
+ name,
362
+ style: 'form',
363
+ value,
364
+ ...options.array
365
+ });
366
+ if (serializedArray) search.push(serializedArray);
367
+ } else if (typeof value === 'object') {
368
+ const serializedObject = serializeObjectParam({
369
+ allowReserved: options.allowReserved,
370
+ explode: true,
371
+ name,
372
+ style: 'deepObject',
373
+ value: value,
374
+ ...options.object
375
+ });
376
+ if (serializedObject) search.push(serializedObject);
377
+ } else {
378
+ const serializedPrimitive = serializePrimitiveParam({
379
+ allowReserved: options.allowReserved,
380
+ name,
381
+ value: value
382
+ });
383
+ if (serializedPrimitive) search.push(serializedPrimitive);
384
+ }
385
+ }
386
+ }
387
+ return search.join('&');
388
+ };
389
+ return querySerializer;
390
+ };
391
+ /**
392
+ * Infers parseAs value from provided Content-Type header.
393
+ */ const getParseAs = (contentType)=>{
394
+ if (!contentType) {
395
+ // If no Content-Type header is provided, the best we can do is return the raw response body,
396
+ // which is effectively the same as the 'stream' option.
397
+ return 'stream';
398
+ }
399
+ const cleanContent = contentType.split(';')[0]?.trim();
400
+ if (!cleanContent) {
401
+ return;
402
+ }
403
+ if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) {
404
+ return 'json';
405
+ }
406
+ if (cleanContent === 'multipart/form-data') {
407
+ return 'formData';
408
+ }
409
+ if ([
410
+ 'application/',
411
+ 'audio/',
412
+ 'image/',
413
+ 'video/'
414
+ ].some((type)=>cleanContent.startsWith(type))) {
415
+ return 'blob';
416
+ }
417
+ if (cleanContent.startsWith('text/')) {
418
+ return 'text';
419
+ }
420
+ return;
421
+ };
422
+ const checkForExistence = (options, name)=>{
423
+ if (!name) {
424
+ return false;
425
+ }
426
+ if (options.headers.has(name) || options.query?.[name] || options.headers.get('Cookie')?.includes(`${name}=`)) {
427
+ return true;
428
+ }
429
+ return false;
430
+ };
431
+ async function setAuthParams(options) {
432
+ for (const auth of options.security ?? []){
433
+ if (checkForExistence(options, auth.name)) {
434
+ continue;
435
+ }
436
+ const token = await getAuthToken(auth, options.auth);
437
+ if (!token) {
438
+ continue;
439
+ }
440
+ const name = auth.name ?? 'Authorization';
441
+ switch(auth.in){
442
+ case 'query':
443
+ if (!options.query) {
444
+ options.query = {};
445
+ }
446
+ options.query[name] = token;
447
+ break;
448
+ case 'cookie':
449
+ options.headers.append('Cookie', `${name}=${token}`);
450
+ break;
451
+ case 'header':
452
+ default:
453
+ options.headers.set(name, token);
454
+ break;
455
+ }
456
+ }
457
+ }
458
+ const buildUrl = (options)=>getUrl({
459
+ baseUrl: options.baseUrl,
460
+ path: options.path,
461
+ query: options.query,
462
+ querySerializer: typeof options.querySerializer === 'function' ? options.querySerializer : createQuerySerializer(options.querySerializer),
463
+ url: options.url
464
+ });
465
+ const mergeConfigs = (a, b)=>{
466
+ const config = {
467
+ ...a,
468
+ ...b
469
+ };
470
+ if (config.baseUrl?.endsWith('/')) {
471
+ config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
472
+ }
473
+ config.headers = mergeHeaders(a.headers, b.headers);
474
+ return config;
475
+ };
476
+ const headersEntries = (headers)=>{
477
+ const entries = [];
478
+ headers.forEach((value, key)=>{
479
+ entries.push([
480
+ key,
481
+ value
482
+ ]);
483
+ });
484
+ return entries;
485
+ };
486
+ const mergeHeaders = (...headers)=>{
487
+ const mergedHeaders = new Headers();
488
+ for (const header of headers){
489
+ if (!header) {
490
+ continue;
491
+ }
492
+ const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
493
+ for (const [key, value] of iterator){
494
+ if (value === null) {
495
+ mergedHeaders.delete(key);
496
+ } else if (Array.isArray(value)) {
497
+ for (const v of value){
498
+ mergedHeaders.append(key, v);
499
+ }
500
+ } else if (value !== undefined) {
501
+ // assume object headers are meant to be JSON stringified, i.e., their
502
+ // content value in OpenAPI specification is 'application/json'
503
+ mergedHeaders.set(key, typeof value === 'object' ? JSON.stringify(value) : value);
504
+ }
505
+ }
506
+ }
507
+ return mergedHeaders;
508
+ };
509
+ class Interceptors {
510
+ clear() {
511
+ this.fns = [];
512
+ }
513
+ eject(id) {
514
+ const index = this.getInterceptorIndex(id);
515
+ if (this.fns[index]) {
516
+ this.fns[index] = null;
517
+ }
518
+ }
519
+ exists(id) {
520
+ const index = this.getInterceptorIndex(id);
521
+ return Boolean(this.fns[index]);
522
+ }
523
+ getInterceptorIndex(id) {
524
+ if (typeof id === 'number') {
525
+ return this.fns[id] ? id : -1;
526
+ }
527
+ return this.fns.indexOf(id);
528
+ }
529
+ update(id, fn) {
530
+ const index = this.getInterceptorIndex(id);
531
+ if (this.fns[index]) {
532
+ this.fns[index] = fn;
533
+ return id;
534
+ }
535
+ return false;
536
+ }
537
+ use(fn) {
538
+ this.fns.push(fn);
539
+ return this.fns.length - 1;
540
+ }
541
+ constructor(){
542
+ this.fns = [];
543
+ }
544
+ }
545
+ const createInterceptors = ()=>({
546
+ error: new Interceptors(),
547
+ request: new Interceptors(),
548
+ response: new Interceptors()
549
+ });
550
+ const defaultQuerySerializer = createQuerySerializer({
551
+ allowReserved: false,
552
+ array: {
553
+ explode: true,
554
+ style: 'form'
555
+ },
556
+ object: {
557
+ explode: true,
558
+ style: 'deepObject'
559
+ }
560
+ });
561
+ const defaultHeaders = {
562
+ 'Content-Type': 'application/json'
563
+ };
564
+ const createConfig = (override = {})=>({
565
+ ...jsonBodySerializer,
566
+ headers: defaultHeaders,
567
+ parseAs: 'auto',
568
+ querySerializer: defaultQuerySerializer,
569
+ ...override
570
+ });
571
+
572
+ // This file is auto-generated by @hey-api/openapi-ts
573
+ const createClient = (config = {})=>{
574
+ let _config = mergeConfigs(createConfig(), config);
575
+ const getConfig = ()=>({
576
+ ..._config
577
+ });
578
+ const setConfig = (config)=>{
579
+ _config = mergeConfigs(_config, config);
580
+ return getConfig();
581
+ };
582
+ const interceptors = createInterceptors();
583
+ const beforeRequest = async (options)=>{
584
+ const opts = {
585
+ ..._config,
586
+ ...options,
587
+ fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
588
+ headers: mergeHeaders(_config.headers, options.headers),
589
+ serializedBody: undefined
590
+ };
591
+ if (opts.security) {
592
+ await setAuthParams(opts);
593
+ }
594
+ if (opts.requestValidator) {
595
+ await opts.requestValidator(opts);
596
+ }
597
+ if (opts.body !== undefined && opts.bodySerializer) {
598
+ opts.serializedBody = opts.bodySerializer(opts.body);
599
+ }
600
+ // remove Content-Type header if body is empty to avoid sending invalid requests
601
+ if (opts.body === undefined || opts.serializedBody === '') {
602
+ opts.headers.delete('Content-Type');
603
+ }
604
+ const resolvedOpts = opts;
605
+ const url = buildUrl(resolvedOpts);
606
+ return {
607
+ opts: resolvedOpts,
608
+ url
609
+ };
610
+ };
611
+ const request = async (options)=>{
612
+ const throwOnError = options.throwOnError ?? _config.throwOnError;
613
+ const responseStyle = options.responseStyle ?? _config.responseStyle;
614
+ let request;
615
+ let response;
616
+ try {
617
+ const { opts, url } = await beforeRequest(options);
618
+ const requestInit = {
619
+ redirect: 'follow',
620
+ ...opts,
621
+ body: getValidRequestBody(opts)
622
+ };
623
+ request = new Request(url, requestInit);
624
+ for (const fn of interceptors.request.fns){
625
+ if (fn) {
626
+ request = await fn(request, opts);
627
+ }
628
+ }
629
+ // fetch must be assigned here, otherwise it would throw the error:
630
+ // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
631
+ const _fetch = opts.fetch;
632
+ response = await _fetch(request);
633
+ for (const fn of interceptors.response.fns){
634
+ if (fn) {
635
+ response = await fn(response, request, opts);
636
+ }
637
+ }
638
+ const result = {
639
+ request,
640
+ response
641
+ };
642
+ if (response.ok) {
643
+ const parseAs = (opts.parseAs === 'auto' ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json';
644
+ if (response.status === 204 || response.headers.get('Content-Length') === '0') {
645
+ let emptyData;
646
+ switch(parseAs){
647
+ case 'arrayBuffer':
648
+ case 'blob':
649
+ case 'text':
650
+ emptyData = await response[parseAs]();
651
+ break;
652
+ case 'formData':
653
+ emptyData = new FormData();
654
+ break;
655
+ case 'stream':
656
+ emptyData = response.body;
657
+ break;
658
+ case 'json':
659
+ default:
660
+ emptyData = {};
661
+ break;
662
+ }
663
+ return opts.responseStyle === 'data' ? emptyData : {
664
+ data: emptyData,
665
+ ...result
666
+ };
667
+ }
668
+ let data;
669
+ switch(parseAs){
670
+ case 'arrayBuffer':
671
+ case 'blob':
672
+ case 'formData':
673
+ case 'text':
674
+ data = await response[parseAs]();
675
+ break;
676
+ case 'json':
677
+ {
678
+ // Some servers return 200 with no Content-Length and empty body.
679
+ // response.json() would throw; read as text and parse if non-empty.
680
+ const text = await response.text();
681
+ data = text ? JSON.parse(text) : {};
682
+ break;
683
+ }
684
+ case 'stream':
685
+ return opts.responseStyle === 'data' ? response.body : {
686
+ data: response.body,
687
+ ...result
688
+ };
689
+ }
690
+ if (parseAs === 'json') {
691
+ if (opts.responseValidator) {
692
+ await opts.responseValidator(data);
693
+ }
694
+ if (opts.responseTransformer) {
695
+ data = await opts.responseTransformer(data);
696
+ }
697
+ }
698
+ return opts.responseStyle === 'data' ? data : {
699
+ data,
700
+ ...result
701
+ };
702
+ }
703
+ const textError = await response.text();
704
+ let jsonError;
705
+ try {
706
+ jsonError = JSON.parse(textError);
707
+ } catch {
708
+ // noop
709
+ }
710
+ throw jsonError ?? textError;
711
+ } catch (error) {
712
+ let finalError = error;
713
+ for (const fn of interceptors.error.fns){
714
+ if (fn) {
715
+ finalError = await fn(finalError, response, request, options);
716
+ }
717
+ }
718
+ finalError = finalError || {};
719
+ if (throwOnError) {
720
+ throw finalError;
721
+ }
722
+ // TODO: we probably want to return error and improve types
723
+ return responseStyle === 'data' ? undefined : {
724
+ error: finalError,
725
+ request,
726
+ response
727
+ };
728
+ }
729
+ };
730
+ const makeMethodFn = (method)=>(options)=>request({
731
+ ...options,
732
+ method
733
+ });
734
+ const makeSseFn = (method)=>async (options)=>{
735
+ const { opts, url } = await beforeRequest(options);
736
+ return createSseClient({
737
+ ...opts,
738
+ body: opts.body,
739
+ method,
740
+ onRequest: async (url, init)=>{
741
+ let request = new Request(url, init);
742
+ for (const fn of interceptors.request.fns){
743
+ if (fn) {
744
+ request = await fn(request, opts);
745
+ }
746
+ }
747
+ return request;
748
+ },
749
+ serializedBody: getValidRequestBody(opts),
750
+ url
751
+ });
752
+ };
753
+ const _buildUrl = (options)=>buildUrl({
754
+ ..._config,
755
+ ...options
756
+ });
757
+ return {
758
+ buildUrl: _buildUrl,
759
+ connect: makeMethodFn('CONNECT'),
760
+ delete: makeMethodFn('DELETE'),
761
+ get: makeMethodFn('GET'),
762
+ getConfig,
763
+ head: makeMethodFn('HEAD'),
764
+ interceptors,
765
+ options: makeMethodFn('OPTIONS'),
766
+ patch: makeMethodFn('PATCH'),
767
+ post: makeMethodFn('POST'),
768
+ put: makeMethodFn('PUT'),
769
+ request,
770
+ setConfig,
771
+ sse: {
772
+ connect: makeSseFn('CONNECT'),
773
+ delete: makeSseFn('DELETE'),
774
+ get: makeSseFn('GET'),
775
+ head: makeSseFn('HEAD'),
776
+ options: makeSseFn('OPTIONS'),
777
+ patch: makeSseFn('PATCH'),
778
+ post: makeSseFn('POST'),
779
+ put: makeSseFn('PUT'),
780
+ trace: makeSseFn('TRACE')
781
+ },
782
+ trace: makeMethodFn('TRACE')
783
+ };
784
+ };
785
+
786
+ const createRampAgentClient = ({ baseUrl, getAuthToken, ...config })=>createClient(createConfig({
787
+ baseUrl,
788
+ ...getAuthToken ? {
789
+ auth: getAuthToken
790
+ } : {},
791
+ ...config
792
+ }));
793
+
794
+ // This file is auto-generated by @hey-api/openapi-ts
795
+ const client = createClient(createConfig());
796
+
797
+ // This file is auto-generated by @hey-api/openapi-ts
798
+ /**
799
+ * GET /country-configs
800
+ *
801
+ * Returns the list of available country configurations with their phone numbers
802
+ */ const getCountryConfigs = (options)=>(options?.client ?? client).get({
803
+ security: [
804
+ {
805
+ scheme: 'bearer',
806
+ type: 'http'
807
+ }
808
+ ],
809
+ url: '/country-configs',
810
+ ...options
811
+ });
812
+ /**
813
+ * GET /recently-active-numbers
814
+ *
815
+ * Retrieves a list of all phone numbers with recent activity, including both
816
+ * active conversations and recently completed ones
817
+ */ const getRecentlyActiveNumbers = (options)=>(options?.client ?? client).get({
818
+ security: [
819
+ {
820
+ scheme: 'bearer',
821
+ type: 'http'
822
+ }
823
+ ],
824
+ url: '/recently-active-numbers',
825
+ ...options
826
+ });
827
+ /**
828
+ * GET /stats
829
+ *
830
+ * Retrieves server statistics including the number of active calls and deployment timestamp
831
+ */ const getStats = (options)=>(options?.client ?? client).get({
832
+ security: [
833
+ {
834
+ scheme: 'bearer',
835
+ type: 'http'
836
+ }
837
+ ],
838
+ url: '/stats',
839
+ ...options
840
+ });
841
+ /**
842
+ * GET /phone-logs/:phoneNumber
843
+ *
844
+ * Retrieves complete call logs and conversation history for a specific phone number
845
+ */ const getPhoneLogsByPhoneNumber = (options)=>(options.client ?? client).get({
846
+ security: [
847
+ {
848
+ scheme: 'bearer',
849
+ type: 'http'
850
+ }
851
+ ],
852
+ url: '/phone-logs/{phoneNumber}',
853
+ ...options
854
+ });
855
+ /**
856
+ * POST /outbound-call
857
+ *
858
+ * Initiates an outbound phone call using Twilio
859
+ */ const postOutboundCall = (options)=>(options.client ?? client).post({
860
+ security: [
861
+ {
862
+ scheme: 'bearer',
863
+ type: 'http'
864
+ }
865
+ ],
866
+ url: '/outbound-call',
867
+ ...options,
868
+ headers: {
869
+ 'Content-Type': 'application/json',
870
+ ...options.headers
871
+ }
872
+ });
873
+ /**
874
+ * GET /outbound-call/:callSid
875
+ *
876
+ * Retrieves the current status and details of a Twilio call by its SID
877
+ */ const getOutboundCallByCallSid = (options)=>(options.client ?? client).get({
878
+ security: [
879
+ {
880
+ scheme: 'bearer',
881
+ type: 'http'
882
+ }
883
+ ],
884
+ url: '/outbound-call/{callSid}',
885
+ ...options
886
+ });
887
+ /**
888
+ * POST /outbound-communication-text
889
+ *
890
+ * Initiates an outbound text message (SMS, RCS, or WhatsApp) to a customer
891
+ */ const postOutboundCommunicationText = (options)=>(options.client ?? client).post({
892
+ security: [
893
+ {
894
+ scheme: 'bearer',
895
+ type: 'http'
896
+ }
897
+ ],
898
+ url: '/outbound-communication-text',
899
+ ...options,
900
+ headers: {
901
+ 'Content-Type': 'application/json',
902
+ ...options.headers
903
+ }
904
+ });
905
+ /**
906
+ * POST /export-logs
907
+ */ const postExportLogs = (options)=>(options?.client ?? client).post({
908
+ security: [
909
+ {
910
+ scheme: 'bearer',
911
+ type: 'http'
912
+ }
913
+ ],
914
+ url: '/export-logs',
915
+ ...options
916
+ });
917
+ /**
918
+ * DELETE /live-numbers
919
+ *
920
+ * Terminates all active conversations, closes websocket connections, and ends all active calls
921
+ */ const deleteLiveNumbers = (options)=>(options?.client ?? client).delete({
922
+ security: [
923
+ {
924
+ scheme: 'bearer',
925
+ type: 'http'
926
+ }
927
+ ],
928
+ url: '/live-numbers',
929
+ ...options
930
+ });
931
+ /**
932
+ * GET /live-numbers
933
+ *
934
+ * Retrieves a list of all currently active conversations with their phone numbers and metadata
935
+ */ const getLiveNumbers = (options)=>(options?.client ?? client).get({
936
+ security: [
937
+ {
938
+ scheme: 'bearer',
939
+ type: 'http'
940
+ }
941
+ ],
942
+ url: '/live-numbers',
943
+ ...options
944
+ });
945
+ /**
946
+ * DELETE /live-numbers/:phoneNumber
947
+ *
948
+ * Ends an active conversation for a specific phone number by terminating the call,
949
+ * closing the conversation, and removing it from active conversations
950
+ */ const deleteLiveNumbersByPhoneNumber = (options)=>(options.client ?? client).delete({
951
+ url: '/live-numbers/{phoneNumber}',
952
+ ...options
953
+ });
954
+ /**
955
+ * DELETE /kill-conversation/:phoneNumber
956
+ *
957
+ * Removes ALL Twilio conversations associated with a phone number,
958
+ * clears in-memory state, and terminates any active calls
959
+ */ const deleteKillConversationByPhoneNumber = (options)=>(options.client ?? client).delete({
960
+ security: [
961
+ {
962
+ scheme: 'bearer',
963
+ type: 'http'
964
+ }
965
+ ],
966
+ url: '/kill-conversation/{phoneNumber}',
967
+ ...options
968
+ });
969
+ /**
970
+ * POST /send-email
971
+ *
972
+ * Sends an email via SendGrid using the environment-configured credentials
973
+ */ const postSendEmail = (options)=>(options.client ?? client).post({
974
+ security: [
975
+ {
976
+ scheme: 'bearer',
977
+ type: 'http'
978
+ }
979
+ ],
980
+ url: '/send-email',
981
+ ...options,
982
+ headers: {
983
+ 'Content-Type': 'application/json',
984
+ ...options.headers
985
+ }
986
+ });
987
+ /**
988
+ * POST /add-message
989
+ *
990
+ * Injects a message directly into an active LLM session and optionally resumes
991
+ * the conversation
992
+ */ const postAddMessage = (options)=>(options.client ?? client).post({
993
+ security: [
994
+ {
995
+ scheme: 'bearer',
996
+ type: 'http'
997
+ }
998
+ ],
999
+ url: '/add-message',
1000
+ ...options,
1001
+ headers: {
1002
+ 'Content-Type': 'application/json',
1003
+ ...options.headers
1004
+ }
1005
+ });
1006
+ /**
1007
+ * POST /active-conversations/agent/claim
1008
+ */ const postActiveConversationsAgentClaim = (options)=>(options.client ?? client).post({
1009
+ security: [
1010
+ {
1011
+ scheme: 'bearer',
1012
+ type: 'http'
1013
+ }
1014
+ ],
1015
+ url: '/active-conversations/agent/claim',
1016
+ ...options,
1017
+ headers: {
1018
+ 'Content-Type': 'application/json',
1019
+ ...options.headers
1020
+ }
1021
+ });
1022
+ /**
1023
+ * GET /active-conversations/agent/:agentNumber
1024
+ */ const getActiveConversationsAgentByAgentNumber = (options)=>(options.client ?? client).get({
1025
+ security: [
1026
+ {
1027
+ scheme: 'bearer',
1028
+ type: 'http'
1029
+ }
1030
+ ],
1031
+ url: '/active-conversations/agent/{agentNumber}',
1032
+ ...options
1033
+ });
1034
+ /**
1035
+ * GET /active-conversations/:customerNumber
1036
+ *
1037
+ * Retrieves an active conversation by customer phone number
1038
+ */ const getActiveConversationsByCustomerNumber = (options)=>(options.client ?? client).get({
1039
+ security: [
1040
+ {
1041
+ scheme: 'bearer',
1042
+ type: 'http'
1043
+ }
1044
+ ],
1045
+ url: '/active-conversations/{customerNumber}',
1046
+ ...options
1047
+ });
1048
+ /**
1049
+ * GET /health
1050
+ *
1051
+ * Health check endpoint for the agent service
1052
+ */ const getHealth = (options)=>(options?.client ?? client).get({
1053
+ url: '/health',
1054
+ ...options
1055
+ });
1056
+ /**
1057
+ * POST /call
1058
+ *
1059
+ * Twilio webhook endpoint that generates TwiML for incoming/outgoing voice calls
1060
+ */ const postCall = (options)=>(options.client ?? client).post({
1061
+ url: '/call',
1062
+ ...options,
1063
+ headers: {
1064
+ 'Content-Type': 'application/json',
1065
+ ...options.headers
1066
+ }
1067
+ });
1068
+ /**
1069
+ * POST /live-agent
1070
+ *
1071
+ * Twilio webhook endpoint that generates TwiML for handoff to live agent (Flex or external Flex)
1072
+ */ const postLiveAgent = (options)=>(options.client ?? client).post({
1073
+ url: '/live-agent',
1074
+ ...options,
1075
+ headers: {
1076
+ 'Content-Type': 'application/json',
1077
+ ...options.headers
1078
+ }
1079
+ });
1080
+ /**
1081
+ * POST /redirect-to-live-agent
1082
+ *
1083
+ * Redirects an active call to the live agent endpoint while gracefully ending the Conversation Relay session
1084
+ */ const postRedirectToLiveAgent = (options)=>(options.client ?? client).post({
1085
+ url: '/redirect-to-live-agent',
1086
+ ...options,
1087
+ headers: {
1088
+ 'Content-Type': 'application/json',
1089
+ ...options.headers
1090
+ }
1091
+ });
1092
+ /**
1093
+ * GET /stress-test
1094
+ *
1095
+ * Twilio webhook endpoint for stress testing voice calls
1096
+ */ const getStressTest = (options)=>(options?.client ?? client).get({
1097
+ url: '/stress-test',
1098
+ ...options
1099
+ });
1100
+ /**
1101
+ * POST /stress-test-sms
1102
+ *
1103
+ * Twilio webhook endpoint for stress testing voice calls
1104
+ */ const postStressTestSms = (options)=>(options.client ?? client).post({
1105
+ url: '/stress-test-sms',
1106
+ ...options,
1107
+ headers: {
1108
+ 'Content-Type': 'application/json',
1109
+ ...options.headers
1110
+ }
1111
+ });
1112
+ /**
1113
+ * POST /webchat-send
1114
+ *
1115
+ * Handles an inbound webchat message and returns the agent's reply
1116
+ */ const postWebchatSend = (options)=>(options.client ?? client).post({
1117
+ url: '/webchat-send',
1118
+ ...options,
1119
+ headers: {
1120
+ 'Content-Type': 'application/json',
1121
+ ...options.headers
1122
+ }
1123
+ });
1124
+ /**
1125
+ * POST /cintel-operators
1126
+ *
1127
+ * Handles incoming CINTEL operator webhook responses from Twilio
1128
+ */ const postCintelOperators = (options)=>(options.client ?? client).post({
1129
+ url: '/cintel-operators',
1130
+ ...options,
1131
+ headers: {
1132
+ 'Content-Type': 'application/json',
1133
+ ...options.headers
1134
+ }
1135
+ });
1136
+ /**
1137
+ * POST /flex-transcription
1138
+ */ const postFlexTranscription = (options)=>(options.client ?? client).post({
1139
+ url: '/flex-transcription',
1140
+ ...options,
1141
+ headers: {
1142
+ 'Content-Type': 'application/json',
1143
+ ...options.headers
1144
+ }
1145
+ });
1146
+ /**
1147
+ * POST /taskrouter-webhook
1148
+ */ const postTaskrouterWebhook = (options)=>(options.client ?? client).post({
1149
+ url: '/taskrouter-webhook',
1150
+ ...options,
1151
+ headers: {
1152
+ 'Content-Type': 'application/json',
1153
+ ...options.headers
1154
+ }
1155
+ });
1156
+ /**
1157
+ * POST /resolve-phone
1158
+ *
1159
+ * Resolves a phone number from the Segment Profiles API given an email
1160
+ */ const postResolvePhone = (options)=>(options.client ?? client).post({
1161
+ url: '/resolve-phone',
1162
+ ...options,
1163
+ headers: {
1164
+ 'Content-Type': 'application/json',
1165
+ ...options.headers
1166
+ }
1167
+ });
1168
+ /**
1169
+ * POST /communication-text
1170
+ *
1171
+ * Handles inbound text messages (SMS, RCS, WhatsApp) from Twilio
1172
+ */ const postCommunicationText = (options)=>(options.client ?? client).post({
1173
+ url: '/communication-text',
1174
+ ...options,
1175
+ headers: {
1176
+ 'Content-Type': 'application/json',
1177
+ ...options.headers
1178
+ }
1179
+ });
1180
+ /**
1181
+ * GET /docs/openapi.json
1182
+ *
1183
+ * docsSpecGet
1184
+ * Serves the generated OpenAPI JSON spec
1185
+ */ const getDocsOpenapiJson = (options)=>(options?.client ?? client).get({
1186
+ security: [
1187
+ {
1188
+ scheme: 'bearer',
1189
+ type: 'http'
1190
+ }
1191
+ ],
1192
+ url: '/docs/openapi.json',
1193
+ ...options
1194
+ });
1195
+
1196
+ // This file is auto-generated by @hey-api/openapi-ts
1197
+ const zGetPhoneLogsByPhoneNumberPath = z.object({
1198
+ phoneNumber: z.string()
1199
+ });
1200
+ const zPostOutboundCallBody = z.object({
1201
+ to: z.string(),
1202
+ from: z.string()
1203
+ });
1204
+ const zGetOutboundCallByCallSidPath = z.object({
1205
+ callSid: z.string()
1206
+ });
1207
+ const zPostOutboundCommunicationTextBody = z.record(z.unknown());
1208
+ const zDeleteLiveNumbersByPhoneNumberPath = z.object({
1209
+ phoneNumber: z.string()
1210
+ });
1211
+ const zDeleteKillConversationByPhoneNumberPath = z.object({
1212
+ phoneNumber: z.string()
1213
+ });
1214
+ const zPostSendEmailBody = z.object({
1215
+ to: z.string(),
1216
+ subject: z.string(),
1217
+ text: z.string()
1218
+ });
1219
+ const zPostAddMessageBody = z.object({
1220
+ to: z.string(),
1221
+ content: z.string()
1222
+ });
1223
+ const zPostActiveConversationsAgentClaimBody = z.record(z.unknown());
1224
+ const zGetActiveConversationsAgentByAgentNumberPath = z.object({
1225
+ agentNumber: z.string()
1226
+ });
1227
+ const zGetActiveConversationsByCustomerNumberPath = z.object({
1228
+ customerNumber: z.string()
1229
+ });
1230
+ const zPostCallBody = z.record(z.unknown());
1231
+ const zPostLiveAgentBody = z.object({
1232
+ From: z.string(),
1233
+ To: z.string(),
1234
+ Direction: z.string()
1235
+ });
1236
+ const zPostRedirectToLiveAgentBody = z.record(z.unknown());
1237
+ const zGetStressTestQuery = z.object({
1238
+ From: z.string().optional(),
1239
+ To: z.string().optional(),
1240
+ CallSid: z.string().optional(),
1241
+ SpeechResult: z.string().optional(),
1242
+ Confidence: z.string().optional(),
1243
+ CallStatus: z.string().optional()
1244
+ });
1245
+ const zPostStressTestSmsBody = z.record(z.unknown());
1246
+ const zPostStressTestSmsQuery = z.object({
1247
+ From: z.string().optional(),
1248
+ To: z.string().optional(),
1249
+ CallSid: z.string().optional(),
1250
+ SpeechResult: z.string().optional(),
1251
+ Confidence: z.string().optional(),
1252
+ CallStatus: z.string().optional()
1253
+ });
1254
+ const zPostWebchatSendBody = z.record(z.unknown());
1255
+ const zPostCintelOperatorsBody = z.record(z.unknown());
1256
+ const zPostFlexTranscriptionBody = z.record(z.unknown());
1257
+ const zPostTaskrouterWebhookBody = z.record(z.unknown());
1258
+ const zPostResolvePhoneBody = z.record(z.unknown());
1259
+ const zPostCommunicationTextBody = z.record(z.unknown());
1260
+
1261
+ var zod_gen = {
1262
+ __proto__: null,
1263
+ zDeleteKillConversationByPhoneNumberPath: zDeleteKillConversationByPhoneNumberPath,
1264
+ zDeleteLiveNumbersByPhoneNumberPath: zDeleteLiveNumbersByPhoneNumberPath,
1265
+ zGetActiveConversationsAgentByAgentNumberPath: zGetActiveConversationsAgentByAgentNumberPath,
1266
+ zGetActiveConversationsByCustomerNumberPath: zGetActiveConversationsByCustomerNumberPath,
1267
+ zGetOutboundCallByCallSidPath: zGetOutboundCallByCallSidPath,
1268
+ zGetPhoneLogsByPhoneNumberPath: zGetPhoneLogsByPhoneNumberPath,
1269
+ zGetStressTestQuery: zGetStressTestQuery,
1270
+ zPostActiveConversationsAgentClaimBody: zPostActiveConversationsAgentClaimBody,
1271
+ zPostAddMessageBody: zPostAddMessageBody,
1272
+ zPostCallBody: zPostCallBody,
1273
+ zPostCintelOperatorsBody: zPostCintelOperatorsBody,
1274
+ zPostCommunicationTextBody: zPostCommunicationTextBody,
1275
+ zPostFlexTranscriptionBody: zPostFlexTranscriptionBody,
1276
+ zPostLiveAgentBody: zPostLiveAgentBody,
1277
+ zPostOutboundCallBody: zPostOutboundCallBody,
1278
+ zPostOutboundCommunicationTextBody: zPostOutboundCommunicationTextBody,
1279
+ zPostRedirectToLiveAgentBody: zPostRedirectToLiveAgentBody,
1280
+ zPostResolvePhoneBody: zPostResolvePhoneBody,
1281
+ zPostSendEmailBody: zPostSendEmailBody,
1282
+ zPostStressTestSmsBody: zPostStressTestSmsBody,
1283
+ zPostStressTestSmsQuery: zPostStressTestSmsQuery,
1284
+ zPostTaskrouterWebhookBody: zPostTaskrouterWebhookBody,
1285
+ zPostWebchatSendBody: zPostWebchatSendBody
1286
+ };
1287
+
1288
+ export { createRampAgentClient, deleteKillConversationByPhoneNumber, deleteLiveNumbers, deleteLiveNumbersByPhoneNumber, getActiveConversationsAgentByAgentNumber, getActiveConversationsByCustomerNumber, getCountryConfigs, getDocsOpenapiJson, getHealth, getLiveNumbers, getOutboundCallByCallSid, getPhoneLogsByPhoneNumber, getRecentlyActiveNumbers, getStats, getStressTest, postActiveConversationsAgentClaim, postAddMessage, postCall, postCintelOperators, postCommunicationText, postExportLogs, postFlexTranscription, postLiveAgent, postOutboundCall, postOutboundCommunicationText, postRedirectToLiveAgent, postResolvePhone, postSendEmail, postStressTestSms, postTaskrouterWebhook, postWebchatSend, zod_gen as schemas };