@sinatra-dev/sdk 0.0.0-stage → 0.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.
package/dist/index.cjs ADDED
@@ -0,0 +1,1170 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ DEFAULT_BASE_URL: () => DEFAULT_BASE_URL,
24
+ DEFAULT_TIMEOUT_MS: () => DEFAULT_TIMEOUT_MS,
25
+ MeApi: () => MeApi,
26
+ MessagesApi: () => MessagesApi,
27
+ Sinatra: () => Sinatra,
28
+ SinatraError: () => SinatraError,
29
+ TasksApi: () => TasksApi,
30
+ TicketsApi: () => TicketsApi
31
+ });
32
+ module.exports = __toCommonJS(index_exports);
33
+
34
+ // src/generated/core/bodySerializer.gen.ts
35
+ var jsonBodySerializer = {
36
+ bodySerializer: (body) => JSON.stringify(body, (_key, value) => typeof value === "bigint" ? value.toString() : value)
37
+ };
38
+
39
+ // src/generated/core/serverSentEvents.gen.ts
40
+ function createSseClient({
41
+ onRequest,
42
+ onSseError,
43
+ onSseEvent,
44
+ responseTransformer,
45
+ responseValidator,
46
+ sseDefaultRetryDelay,
47
+ sseMaxRetryAttempts,
48
+ sseMaxRetryDelay,
49
+ sseSleepFn,
50
+ url,
51
+ ...options
52
+ }) {
53
+ let lastEventId;
54
+ const sleep2 = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
55
+ const createStream = async function* () {
56
+ let retryDelay = sseDefaultRetryDelay ?? 3e3;
57
+ let attempt = 0;
58
+ const signal = options.signal ?? new AbortController().signal;
59
+ while (true) {
60
+ if (signal.aborted) break;
61
+ attempt++;
62
+ const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers);
63
+ if (lastEventId !== void 0) {
64
+ headers.set("Last-Event-ID", lastEventId);
65
+ }
66
+ try {
67
+ const requestInit = {
68
+ redirect: "follow",
69
+ ...options,
70
+ body: options.serializedBody,
71
+ headers,
72
+ signal
73
+ };
74
+ let request = new Request(url, requestInit);
75
+ if (onRequest) {
76
+ request = await onRequest(url, requestInit);
77
+ }
78
+ const _fetch = options.fetch ?? globalThis.fetch;
79
+ const response = await _fetch(request);
80
+ if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`);
81
+ if (!response.body) throw new Error("No body in SSE response");
82
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
83
+ let buffer = "";
84
+ const abortHandler = () => {
85
+ try {
86
+ reader.cancel();
87
+ } catch {
88
+ }
89
+ };
90
+ signal.addEventListener("abort", abortHandler);
91
+ try {
92
+ while (true) {
93
+ const { done, value } = await reader.read();
94
+ if (done) break;
95
+ buffer += value;
96
+ buffer = buffer.replace(/\r\n?/g, "\n");
97
+ const chunks = buffer.split("\n\n");
98
+ buffer = chunks.pop() ?? "";
99
+ for (const chunk of chunks) {
100
+ const lines = chunk.split("\n");
101
+ const dataLines = [];
102
+ let eventName;
103
+ for (const line of lines) {
104
+ if (line.startsWith("data:")) {
105
+ dataLines.push(line.replace(/^data:\s*/, ""));
106
+ } else if (line.startsWith("event:")) {
107
+ eventName = line.replace(/^event:\s*/, "");
108
+ } else if (line.startsWith("id:")) {
109
+ lastEventId = line.replace(/^id:\s*/, "");
110
+ } else if (line.startsWith("retry:")) {
111
+ const parsed = Number.parseInt(line.replace(/^retry:\s*/, ""), 10);
112
+ if (!Number.isNaN(parsed)) {
113
+ retryDelay = parsed;
114
+ }
115
+ }
116
+ }
117
+ let data;
118
+ let parsedJson = false;
119
+ if (dataLines.length) {
120
+ const rawData = dataLines.join("\n");
121
+ try {
122
+ data = JSON.parse(rawData);
123
+ parsedJson = true;
124
+ } catch {
125
+ data = rawData;
126
+ }
127
+ }
128
+ if (parsedJson) {
129
+ if (responseValidator) {
130
+ await responseValidator(data);
131
+ }
132
+ if (responseTransformer) {
133
+ data = await responseTransformer(data);
134
+ }
135
+ }
136
+ onSseEvent?.({
137
+ data,
138
+ event: eventName,
139
+ id: lastEventId,
140
+ retry: retryDelay
141
+ });
142
+ if (dataLines.length) {
143
+ yield data;
144
+ }
145
+ }
146
+ }
147
+ } finally {
148
+ signal.removeEventListener("abort", abortHandler);
149
+ reader.releaseLock();
150
+ }
151
+ break;
152
+ } catch (error) {
153
+ onSseError?.(error);
154
+ if (sseMaxRetryAttempts !== void 0 && attempt >= sseMaxRetryAttempts) {
155
+ break;
156
+ }
157
+ const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 3e4);
158
+ await sleep2(backoff);
159
+ }
160
+ }
161
+ };
162
+ const stream = createStream();
163
+ return { stream };
164
+ }
165
+
166
+ // src/generated/core/pathSerializer.gen.ts
167
+ var separatorArrayExplode = (style) => {
168
+ switch (style) {
169
+ case "label":
170
+ return ".";
171
+ case "matrix":
172
+ return ";";
173
+ case "simple":
174
+ return ",";
175
+ default:
176
+ return "&";
177
+ }
178
+ };
179
+ var separatorArrayNoExplode = (style) => {
180
+ switch (style) {
181
+ case "form":
182
+ return ",";
183
+ case "pipeDelimited":
184
+ return "|";
185
+ case "spaceDelimited":
186
+ return "%20";
187
+ default:
188
+ return ",";
189
+ }
190
+ };
191
+ var separatorObjectExplode = (style) => {
192
+ switch (style) {
193
+ case "label":
194
+ return ".";
195
+ case "matrix":
196
+ return ";";
197
+ case "simple":
198
+ return ",";
199
+ default:
200
+ return "&";
201
+ }
202
+ };
203
+ var serializeArrayParam = ({
204
+ allowReserved,
205
+ explode,
206
+ name,
207
+ style,
208
+ value
209
+ }) => {
210
+ if (!explode) {
211
+ const joinedValues2 = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
212
+ switch (style) {
213
+ case "label":
214
+ return `.${joinedValues2}`;
215
+ case "matrix":
216
+ return `;${name}=${joinedValues2}`;
217
+ case "simple":
218
+ return joinedValues2;
219
+ default:
220
+ return `${name}=${joinedValues2}`;
221
+ }
222
+ }
223
+ const separator = separatorArrayExplode(style);
224
+ const joinedValues = value.map((v) => {
225
+ if (style === "label" || style === "simple") {
226
+ return allowReserved ? v : encodeURIComponent(v);
227
+ }
228
+ return serializePrimitiveParam({
229
+ allowReserved,
230
+ name,
231
+ value: v
232
+ });
233
+ }).join(separator);
234
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
235
+ };
236
+ var serializePrimitiveParam = ({
237
+ allowReserved,
238
+ name,
239
+ value
240
+ }) => {
241
+ if (value === void 0 || value === null) {
242
+ return "";
243
+ }
244
+ if (typeof value === "object") {
245
+ throw new Error(
246
+ "Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these."
247
+ );
248
+ }
249
+ return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
250
+ };
251
+ var serializeObjectParam = ({
252
+ allowReserved,
253
+ explode,
254
+ name,
255
+ style,
256
+ value,
257
+ valueOnly
258
+ }) => {
259
+ if (value instanceof Date) {
260
+ return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
261
+ }
262
+ if (style !== "deepObject" && !explode) {
263
+ let values = [];
264
+ Object.entries(value).forEach(([key, v]) => {
265
+ values = [...values, key, allowReserved ? v : encodeURIComponent(v)];
266
+ });
267
+ const joinedValues2 = values.join(",");
268
+ switch (style) {
269
+ case "form":
270
+ return `${name}=${joinedValues2}`;
271
+ case "label":
272
+ return `.${joinedValues2}`;
273
+ case "matrix":
274
+ return `;${name}=${joinedValues2}`;
275
+ default:
276
+ return joinedValues2;
277
+ }
278
+ }
279
+ const separator = separatorObjectExplode(style);
280
+ const joinedValues = Object.entries(value).map(
281
+ ([key, v]) => serializePrimitiveParam({
282
+ allowReserved,
283
+ name: style === "deepObject" ? `${name}[${key}]` : key,
284
+ value: v
285
+ })
286
+ ).join(separator);
287
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
288
+ };
289
+
290
+ // src/generated/core/utils.gen.ts
291
+ var PATH_PARAM_RE = /\{[^{}]+\}/g;
292
+ var defaultPathSerializer = ({ path, url: _url }) => {
293
+ let url = _url;
294
+ const matches = _url.match(PATH_PARAM_RE);
295
+ if (matches) {
296
+ for (const match of matches) {
297
+ let explode = false;
298
+ let name = match.substring(1, match.length - 1);
299
+ let style = "simple";
300
+ if (name.endsWith("*")) {
301
+ explode = true;
302
+ name = name.substring(0, name.length - 1);
303
+ }
304
+ if (name.startsWith(".")) {
305
+ name = name.substring(1);
306
+ style = "label";
307
+ } else if (name.startsWith(";")) {
308
+ name = name.substring(1);
309
+ style = "matrix";
310
+ }
311
+ const value = path[name];
312
+ if (value === void 0 || value === null) {
313
+ continue;
314
+ }
315
+ if (Array.isArray(value)) {
316
+ url = url.replace(match, serializeArrayParam({ explode, name, style, value }));
317
+ continue;
318
+ }
319
+ if (typeof value === "object") {
320
+ url = url.replace(
321
+ match,
322
+ serializeObjectParam({
323
+ explode,
324
+ name,
325
+ style,
326
+ value,
327
+ valueOnly: true
328
+ })
329
+ );
330
+ continue;
331
+ }
332
+ if (style === "matrix") {
333
+ url = url.replace(
334
+ match,
335
+ `;${serializePrimitiveParam({
336
+ name,
337
+ value
338
+ })}`
339
+ );
340
+ continue;
341
+ }
342
+ const replaceValue = encodeURIComponent(
343
+ style === "label" ? `.${value}` : value
344
+ );
345
+ url = url.replace(match, replaceValue);
346
+ }
347
+ }
348
+ return url;
349
+ };
350
+ var getUrl = ({
351
+ baseUrl,
352
+ path,
353
+ query,
354
+ querySerializer,
355
+ url: _url
356
+ }) => {
357
+ const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
358
+ let url = (baseUrl ?? "") + pathUrl;
359
+ if (path) {
360
+ url = defaultPathSerializer({ path, url });
361
+ }
362
+ let search = query ? querySerializer(query) : "";
363
+ if (search.startsWith("?")) {
364
+ search = search.substring(1);
365
+ }
366
+ if (search) {
367
+ url += `?${search}`;
368
+ }
369
+ return url;
370
+ };
371
+ function getValidRequestBody(options) {
372
+ const hasBody = options.body !== void 0;
373
+ const isSerializedBody = hasBody && options.bodySerializer;
374
+ if (isSerializedBody) {
375
+ if ("serializedBody" in options) {
376
+ const hasSerializedBody = options.serializedBody !== void 0 && options.serializedBody !== "";
377
+ return hasSerializedBody ? options.serializedBody : null;
378
+ }
379
+ return options.body !== "" ? options.body : null;
380
+ }
381
+ if (hasBody) {
382
+ return options.body;
383
+ }
384
+ return void 0;
385
+ }
386
+
387
+ // src/generated/core/auth.gen.ts
388
+ var getAuthToken = async (auth, callback) => {
389
+ const token = typeof callback === "function" ? await callback(auth) : callback;
390
+ if (!token) {
391
+ return;
392
+ }
393
+ if (auth.scheme === "bearer") {
394
+ return `Bearer ${token}`;
395
+ }
396
+ if (auth.scheme === "basic") {
397
+ return `Basic ${btoa(token)}`;
398
+ }
399
+ return token;
400
+ };
401
+
402
+ // src/generated/client/utils.gen.ts
403
+ var createQuerySerializer = ({
404
+ parameters = {},
405
+ ...args
406
+ } = {}) => {
407
+ const querySerializer = (queryParams) => {
408
+ const search = [];
409
+ if (queryParams && typeof queryParams === "object") {
410
+ for (const name in queryParams) {
411
+ const value = queryParams[name];
412
+ if (value === void 0 || value === null) {
413
+ continue;
414
+ }
415
+ const options = parameters[name] || args;
416
+ if (Array.isArray(value)) {
417
+ const serializedArray = serializeArrayParam({
418
+ allowReserved: options.allowReserved,
419
+ explode: true,
420
+ name,
421
+ style: "form",
422
+ value,
423
+ ...options.array
424
+ });
425
+ if (serializedArray) search.push(serializedArray);
426
+ } else if (typeof value === "object") {
427
+ const serializedObject = serializeObjectParam({
428
+ allowReserved: options.allowReserved,
429
+ explode: true,
430
+ name,
431
+ style: "deepObject",
432
+ value,
433
+ ...options.object
434
+ });
435
+ if (serializedObject) search.push(serializedObject);
436
+ } else {
437
+ const serializedPrimitive = serializePrimitiveParam({
438
+ allowReserved: options.allowReserved,
439
+ name,
440
+ value
441
+ });
442
+ if (serializedPrimitive) search.push(serializedPrimitive);
443
+ }
444
+ }
445
+ }
446
+ return search.join("&");
447
+ };
448
+ return querySerializer;
449
+ };
450
+ var getParseAs = (contentType) => {
451
+ if (!contentType) {
452
+ return "stream";
453
+ }
454
+ const cleanContent = contentType.split(";")[0]?.trim();
455
+ if (!cleanContent) {
456
+ return;
457
+ }
458
+ if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) {
459
+ return "json";
460
+ }
461
+ if (cleanContent === "multipart/form-data") {
462
+ return "formData";
463
+ }
464
+ if (["application/", "audio/", "image/", "video/"].some((type) => cleanContent.startsWith(type))) {
465
+ return "blob";
466
+ }
467
+ if (cleanContent.startsWith("text/")) {
468
+ return "text";
469
+ }
470
+ return;
471
+ };
472
+ var checkForExistence = (options, name) => {
473
+ if (!name) {
474
+ return false;
475
+ }
476
+ if (options.headers.has(name) || options.query?.[name] || options.headers.get("Cookie")?.includes(`${name}=`)) {
477
+ return true;
478
+ }
479
+ return false;
480
+ };
481
+ async function setAuthParams(options) {
482
+ for (const auth of options.security ?? []) {
483
+ if (checkForExistence(options, auth.name)) {
484
+ continue;
485
+ }
486
+ const token = await getAuthToken(auth, options.auth);
487
+ if (!token) {
488
+ continue;
489
+ }
490
+ const name = auth.name ?? "Authorization";
491
+ switch (auth.in) {
492
+ case "query":
493
+ if (!options.query) {
494
+ options.query = {};
495
+ }
496
+ options.query[name] = token;
497
+ break;
498
+ case "cookie":
499
+ options.headers.append("Cookie", `${name}=${token}`);
500
+ break;
501
+ case "header":
502
+ default:
503
+ options.headers.set(name, token);
504
+ break;
505
+ }
506
+ }
507
+ }
508
+ var buildUrl = (options) => getUrl({
509
+ baseUrl: options.baseUrl,
510
+ path: options.path,
511
+ query: options.query,
512
+ querySerializer: typeof options.querySerializer === "function" ? options.querySerializer : createQuerySerializer(options.querySerializer),
513
+ url: options.url
514
+ });
515
+ var mergeConfigs = (a, b) => {
516
+ const config = { ...a, ...b };
517
+ if (config.baseUrl?.endsWith("/")) {
518
+ config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
519
+ }
520
+ config.headers = mergeHeaders(a.headers, b.headers);
521
+ return config;
522
+ };
523
+ var headersEntries = (headers) => {
524
+ const entries = [];
525
+ headers.forEach((value, key) => {
526
+ entries.push([key, value]);
527
+ });
528
+ return entries;
529
+ };
530
+ var mergeHeaders = (...headers) => {
531
+ const mergedHeaders = new Headers();
532
+ for (const header of headers) {
533
+ if (!header) {
534
+ continue;
535
+ }
536
+ const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
537
+ for (const [key, value] of iterator) {
538
+ if (value === null) {
539
+ mergedHeaders.delete(key);
540
+ } else if (Array.isArray(value)) {
541
+ for (const v of value) {
542
+ mergedHeaders.append(key, v);
543
+ }
544
+ } else if (value !== void 0) {
545
+ mergedHeaders.set(
546
+ key,
547
+ typeof value === "object" ? JSON.stringify(value) : value
548
+ );
549
+ }
550
+ }
551
+ }
552
+ return mergedHeaders;
553
+ };
554
+ var Interceptors = class {
555
+ fns = [];
556
+ clear() {
557
+ this.fns = [];
558
+ }
559
+ eject(id) {
560
+ const index = this.getInterceptorIndex(id);
561
+ if (this.fns[index]) {
562
+ this.fns[index] = null;
563
+ }
564
+ }
565
+ exists(id) {
566
+ const index = this.getInterceptorIndex(id);
567
+ return Boolean(this.fns[index]);
568
+ }
569
+ getInterceptorIndex(id) {
570
+ if (typeof id === "number") {
571
+ return this.fns[id] ? id : -1;
572
+ }
573
+ return this.fns.indexOf(id);
574
+ }
575
+ update(id, fn) {
576
+ const index = this.getInterceptorIndex(id);
577
+ if (this.fns[index]) {
578
+ this.fns[index] = fn;
579
+ return id;
580
+ }
581
+ return false;
582
+ }
583
+ use(fn) {
584
+ this.fns.push(fn);
585
+ return this.fns.length - 1;
586
+ }
587
+ };
588
+ var createInterceptors = () => ({
589
+ error: new Interceptors(),
590
+ request: new Interceptors(),
591
+ response: new Interceptors()
592
+ });
593
+ var defaultQuerySerializer = createQuerySerializer({
594
+ allowReserved: false,
595
+ array: {
596
+ explode: true,
597
+ style: "form"
598
+ },
599
+ object: {
600
+ explode: true,
601
+ style: "deepObject"
602
+ }
603
+ });
604
+ var defaultHeaders = {
605
+ "Content-Type": "application/json"
606
+ };
607
+ var createConfig = (override = {}) => ({
608
+ ...jsonBodySerializer,
609
+ headers: defaultHeaders,
610
+ parseAs: "auto",
611
+ querySerializer: defaultQuerySerializer,
612
+ ...override
613
+ });
614
+
615
+ // src/generated/client/client.gen.ts
616
+ var createClient = (config = {}) => {
617
+ let _config = mergeConfigs(createConfig(), config);
618
+ const getConfig = () => ({ ..._config });
619
+ const setConfig = (config2) => {
620
+ _config = mergeConfigs(_config, config2);
621
+ return getConfig();
622
+ };
623
+ const interceptors = createInterceptors();
624
+ const beforeRequest = async (options) => {
625
+ const opts = {
626
+ ..._config,
627
+ ...options,
628
+ fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
629
+ headers: mergeHeaders(_config.headers, options.headers),
630
+ serializedBody: void 0
631
+ };
632
+ if (opts.security) {
633
+ await setAuthParams(opts);
634
+ }
635
+ if (opts.requestValidator) {
636
+ await opts.requestValidator(opts);
637
+ }
638
+ if (opts.body !== void 0 && opts.bodySerializer) {
639
+ opts.serializedBody = opts.bodySerializer(opts.body);
640
+ }
641
+ if (opts.body === void 0 || opts.serializedBody === "") {
642
+ opts.headers.delete("Content-Type");
643
+ }
644
+ const resolvedOpts = opts;
645
+ const url = buildUrl(resolvedOpts);
646
+ return { opts: resolvedOpts, url };
647
+ };
648
+ const request = async (options) => {
649
+ const throwOnError = options.throwOnError ?? _config.throwOnError;
650
+ const responseStyle = options.responseStyle ?? _config.responseStyle;
651
+ let request2;
652
+ let response;
653
+ try {
654
+ const { opts, url } = await beforeRequest(options);
655
+ const requestInit = {
656
+ redirect: "follow",
657
+ ...opts,
658
+ body: getValidRequestBody(opts)
659
+ };
660
+ request2 = new Request(url, requestInit);
661
+ for (const fn of interceptors.request.fns) {
662
+ if (fn) {
663
+ request2 = await fn(request2, opts);
664
+ }
665
+ }
666
+ const _fetch = opts.fetch;
667
+ response = await _fetch(request2);
668
+ for (const fn of interceptors.response.fns) {
669
+ if (fn) {
670
+ response = await fn(response, request2, opts);
671
+ }
672
+ }
673
+ const result = {
674
+ request: request2,
675
+ response
676
+ };
677
+ if (response.ok) {
678
+ const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json";
679
+ if (response.status === 204 || response.headers.get("Content-Length") === "0") {
680
+ let emptyData;
681
+ switch (parseAs) {
682
+ case "arrayBuffer":
683
+ case "blob":
684
+ case "text":
685
+ emptyData = await response[parseAs]();
686
+ break;
687
+ case "formData":
688
+ emptyData = new FormData();
689
+ break;
690
+ case "stream":
691
+ emptyData = response.body;
692
+ break;
693
+ case "json":
694
+ default:
695
+ emptyData = {};
696
+ break;
697
+ }
698
+ return opts.responseStyle === "data" ? emptyData : {
699
+ data: emptyData,
700
+ ...result
701
+ };
702
+ }
703
+ let data;
704
+ switch (parseAs) {
705
+ case "arrayBuffer":
706
+ case "blob":
707
+ case "formData":
708
+ case "text":
709
+ data = await response[parseAs]();
710
+ break;
711
+ case "json": {
712
+ const text = await response.text();
713
+ data = text ? JSON.parse(text) : {};
714
+ break;
715
+ }
716
+ case "stream":
717
+ return opts.responseStyle === "data" ? response.body : {
718
+ data: response.body,
719
+ ...result
720
+ };
721
+ }
722
+ if (parseAs === "json") {
723
+ if (opts.responseValidator) {
724
+ await opts.responseValidator(data);
725
+ }
726
+ if (opts.responseTransformer) {
727
+ data = await opts.responseTransformer(data);
728
+ }
729
+ }
730
+ return opts.responseStyle === "data" ? data : {
731
+ data,
732
+ ...result
733
+ };
734
+ }
735
+ const textError = await response.text();
736
+ let jsonError;
737
+ try {
738
+ jsonError = JSON.parse(textError);
739
+ } catch {
740
+ }
741
+ throw jsonError ?? textError;
742
+ } catch (error) {
743
+ let finalError = error;
744
+ for (const fn of interceptors.error.fns) {
745
+ if (fn) {
746
+ finalError = await fn(finalError, response, request2, options);
747
+ }
748
+ }
749
+ finalError = finalError || {};
750
+ if (throwOnError) {
751
+ throw finalError;
752
+ }
753
+ return responseStyle === "data" ? void 0 : {
754
+ error: finalError,
755
+ request: request2,
756
+ response
757
+ };
758
+ }
759
+ };
760
+ const makeMethodFn = (method) => (options) => request({ ...options, method });
761
+ const makeSseFn = (method) => async (options) => {
762
+ const { opts, url } = await beforeRequest(options);
763
+ return createSseClient({
764
+ ...opts,
765
+ body: opts.body,
766
+ method,
767
+ onRequest: async (url2, init) => {
768
+ let request2 = new Request(url2, init);
769
+ for (const fn of interceptors.request.fns) {
770
+ if (fn) {
771
+ request2 = await fn(request2, opts);
772
+ }
773
+ }
774
+ return request2;
775
+ },
776
+ serializedBody: getValidRequestBody(opts),
777
+ url
778
+ });
779
+ };
780
+ const _buildUrl = (options) => buildUrl({ ..._config, ...options });
781
+ return {
782
+ buildUrl: _buildUrl,
783
+ connect: makeMethodFn("CONNECT"),
784
+ delete: makeMethodFn("DELETE"),
785
+ get: makeMethodFn("GET"),
786
+ getConfig,
787
+ head: makeMethodFn("HEAD"),
788
+ interceptors,
789
+ options: makeMethodFn("OPTIONS"),
790
+ patch: makeMethodFn("PATCH"),
791
+ post: makeMethodFn("POST"),
792
+ put: makeMethodFn("PUT"),
793
+ request,
794
+ setConfig,
795
+ sse: {
796
+ connect: makeSseFn("CONNECT"),
797
+ delete: makeSseFn("DELETE"),
798
+ get: makeSseFn("GET"),
799
+ head: makeSseFn("HEAD"),
800
+ options: makeSseFn("OPTIONS"),
801
+ patch: makeSseFn("PATCH"),
802
+ post: makeSseFn("POST"),
803
+ put: makeSseFn("PUT"),
804
+ trace: makeSseFn("TRACE")
805
+ },
806
+ trace: makeMethodFn("TRACE")
807
+ };
808
+ };
809
+
810
+ // src/generated/client.gen.ts
811
+ var client = createClient(createConfig({ baseUrl: "https://api.sinatra.dev" }));
812
+
813
+ // src/generated/sdk.gen.ts
814
+ var meGet = (options) => (options?.client ?? client).get({
815
+ security: [{ scheme: "bearer", type: "http" }],
816
+ url: "/v1/me",
817
+ ...options
818
+ });
819
+ var meRevokeToken = (options) => (options?.client ?? client).delete({
820
+ security: [{ scheme: "bearer", type: "http" }],
821
+ url: "/v1/me/token",
822
+ ...options
823
+ });
824
+ var tasksList = (options) => (options.client ?? client).get({
825
+ security: [{ scheme: "bearer", type: "http" }],
826
+ url: "/v1/workspaces/{workspaceId}/tasks",
827
+ ...options
828
+ });
829
+ var tasksCreate = (options) => (options.client ?? client).post({
830
+ security: [{ scheme: "bearer", type: "http" }],
831
+ url: "/v1/workspaces/{workspaceId}/tasks",
832
+ ...options,
833
+ headers: {
834
+ "Content-Type": "application/json",
835
+ ...options.headers
836
+ }
837
+ });
838
+ var tasksGet = (options) => (options.client ?? client).get({
839
+ security: [{ scheme: "bearer", type: "http" }],
840
+ url: "/v1/workspaces/{workspaceId}/tasks/{taskId}",
841
+ ...options
842
+ });
843
+ var tasksStop = (options) => (options.client ?? client).post({
844
+ security: [{ scheme: "bearer", type: "http" }],
845
+ url: "/v1/workspaces/{workspaceId}/tasks/{taskId}/stop",
846
+ ...options
847
+ });
848
+ var messagesList = (options) => (options.client ?? client).get({
849
+ security: [{ scheme: "bearer", type: "http" }],
850
+ url: "/v1/workspaces/{workspaceId}/tasks/{taskId}/messages",
851
+ ...options
852
+ });
853
+ var messagesCreate = (options) => (options.client ?? client).post({
854
+ security: [{ scheme: "bearer", type: "http" }],
855
+ url: "/v1/workspaces/{workspaceId}/tasks/{taskId}/messages",
856
+ ...options,
857
+ headers: {
858
+ "Content-Type": "application/json",
859
+ ...options.headers
860
+ }
861
+ });
862
+ var ticketsSearch = (options) => (options.client ?? client).get({
863
+ security: [{ scheme: "bearer", type: "http" }],
864
+ url: "/v1/workspaces/{workspaceId}/tickets",
865
+ ...options
866
+ });
867
+ var ticketsDelegate = (options) => (options.client ?? client).post({
868
+ security: [{ scheme: "bearer", type: "http" }],
869
+ url: "/v1/workspaces/{workspaceId}/tickets/delegate",
870
+ ...options,
871
+ headers: {
872
+ "Content-Type": "application/json",
873
+ ...options.headers
874
+ }
875
+ });
876
+
877
+ // src/error.ts
878
+ var SinatraError = class extends Error {
879
+ name = "SinatraError";
880
+ /** The HTTP status, such as `409`. */
881
+ status;
882
+ /**
883
+ * The API's `error` code, such as `not_running`. `http_error` when the
884
+ * response had no code, for example an HTML page from a proxy.
885
+ */
886
+ code;
887
+ /** A sentence saying what went wrong, written to show to a person. */
888
+ reason;
889
+ /** The request's id, from the body or the `x-request-id` header. Share it with support. */
890
+ requestId;
891
+ /** The response body: the parsed JSON object, or the text when it wasn't JSON. */
892
+ body;
893
+ /** The response headers. */
894
+ headers;
895
+ constructor(status, body, headers) {
896
+ const fields = isRecord(body) ? body : {};
897
+ const code = typeof fields.error === "string" ? fields.error : "http_error";
898
+ const reason = typeof fields.reason === "string" ? fields.reason : void 0;
899
+ super(reason ? `${status} ${code}: ${reason}` : `${status} ${code}`);
900
+ this.status = status;
901
+ this.code = code;
902
+ this.reason = reason;
903
+ this.requestId = (typeof fields.requestId === "string" ? fields.requestId : void 0) ?? headers.get("x-request-id") ?? void 0;
904
+ this.body = body;
905
+ this.headers = headers;
906
+ }
907
+ };
908
+ function isRecord(value) {
909
+ return typeof value === "object" && value !== null && !Array.isArray(value);
910
+ }
911
+
912
+ // src/retry.ts
913
+ var MAX_RETRIES = 3;
914
+ var BACKOFF_MS = 500;
915
+ var MAX_RETRY_AFTER_MS = 6e4;
916
+ var MAX_TIMER_MS = 2 ** 31 - 1;
917
+ var RETRY_IDEMPOTENT = /* @__PURE__ */ new Set([429, 503]);
918
+ var RETRY_UNAVAILABLE = /* @__PURE__ */ new Set([503]);
919
+ var RETRY_NEVER = /* @__PURE__ */ new Set();
920
+ async function withRetries(retryOn, options, attempt) {
921
+ for (let retry = 0; ; retry++) {
922
+ const limit = attemptSignal(options);
923
+ let result;
924
+ try {
925
+ result = await attempt(limit.signal);
926
+ } finally {
927
+ limit.done();
928
+ }
929
+ const { response } = result;
930
+ if (!response) throw result.error;
931
+ if (response.ok) {
932
+ if ("error" in result) throw result.error;
933
+ return result.data;
934
+ }
935
+ if (retry < MAX_RETRIES && retryOn.has(response.status)) {
936
+ await sleep(retryDelayMs(response, retry), options.signal);
937
+ continue;
938
+ }
939
+ throw new SinatraError(response.status, result.error, response.headers);
940
+ }
941
+ }
942
+ function attemptSignal({ signal, timeout }) {
943
+ const controller = new AbortController();
944
+ const onAbort = () => controller.abort(signal?.reason);
945
+ if (signal?.aborted) onAbort();
946
+ else signal?.addEventListener("abort", onAbort, { once: true });
947
+ const timer = timeout && timeout > 0 && Number.isFinite(timeout) ? setTimeout(
948
+ () => controller.abort(new DOMException(`Request timed out after ${timeout}ms`, "TimeoutError")),
949
+ Math.min(timeout, MAX_TIMER_MS)
950
+ ) : void 0;
951
+ return {
952
+ signal: controller.signal,
953
+ done: () => {
954
+ clearTimeout(timer);
955
+ signal?.removeEventListener("abort", onAbort);
956
+ }
957
+ };
958
+ }
959
+ function retryDelayMs(response, retry) {
960
+ if (response.status === 429) {
961
+ const after = parseRetryAfter(response.headers.get("retry-after"));
962
+ if (after !== void 0) return Math.min(after, MAX_RETRY_AFTER_MS);
963
+ }
964
+ return BACKOFF_MS * 2 ** retry;
965
+ }
966
+ function parseRetryAfter(value) {
967
+ if (value === null || value.trim() === "") return void 0;
968
+ const seconds = Number(value);
969
+ if (Number.isFinite(seconds)) return Math.max(0, seconds * 1e3);
970
+ const date = Date.parse(value);
971
+ if (Number.isNaN(date)) return void 0;
972
+ return Math.max(0, date - Date.now());
973
+ }
974
+ function sleep(ms, signal) {
975
+ return new Promise((resolve, reject) => {
976
+ if (signal?.aborted) return reject(signal.reason);
977
+ const onAbort = () => {
978
+ clearTimeout(timer);
979
+ reject(signal?.reason);
980
+ };
981
+ const timer = setTimeout(() => {
982
+ signal?.removeEventListener("abort", onAbort);
983
+ resolve();
984
+ }, ms);
985
+ signal?.addEventListener("abort", onAbort, { once: true });
986
+ });
987
+ }
988
+
989
+ // src/index.ts
990
+ var DEFAULT_BASE_URL = "https://api.sinatra.dev";
991
+ var DEFAULT_TIMEOUT_MS = 6e4;
992
+ var Sinatra = class {
993
+ me;
994
+ tasks;
995
+ messages;
996
+ tickets;
997
+ constructor(options = {}) {
998
+ const token = options.token || envToken();
999
+ if (!token) {
1000
+ throw new Error("No Sinatra API token: pass { token } or set SINATRA_TOKEN.");
1001
+ }
1002
+ const client2 = createClient(
1003
+ createConfig({
1004
+ baseUrl: (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, ""),
1005
+ auth: token,
1006
+ throwOnError: false,
1007
+ ...options.fetch ? { fetch: options.fetch } : {}
1008
+ })
1009
+ );
1010
+ const ctx = { client: client2, timeout: options.timeout ?? DEFAULT_TIMEOUT_MS };
1011
+ this.me = new MeApi(ctx);
1012
+ this.tasks = new TasksApi(ctx);
1013
+ this.messages = new MessagesApi(ctx);
1014
+ this.tickets = new TicketsApi(ctx);
1015
+ }
1016
+ };
1017
+ function call(ctx, retryOn, options, attempt) {
1018
+ const limits = { signal: options.signal, timeout: options.timeout ?? ctx.timeout };
1019
+ return withRetries(retryOn, limits, (signal) => attempt(ctx.client, signal));
1020
+ }
1021
+ var MeApi = class {
1022
+ /** @internal */
1023
+ constructor(ctx) {
1024
+ this.ctx = ctx;
1025
+ }
1026
+ ctx;
1027
+ /** `me.get`: the user the token acts as, and their workspaces. */
1028
+ get(options = {}) {
1029
+ return call(this.ctx, RETRY_IDEMPOTENT, options, (client2, signal) => meGet({ client: client2, signal }));
1030
+ }
1031
+ /** `me.revokeToken`: revokes the token this client sends. Later requests get `401`. */
1032
+ async revokeToken(options = {}) {
1033
+ await call(this.ctx, RETRY_IDEMPOTENT, options, (client2, signal) => meRevokeToken({ client: client2, signal }));
1034
+ }
1035
+ };
1036
+ var TasksApi = class {
1037
+ /** @internal */
1038
+ constructor(ctx) {
1039
+ this.ctx = ctx;
1040
+ }
1041
+ ctx;
1042
+ /** `tasks.list`: one page of the workspace's tasks, most recently active first. */
1043
+ list(workspaceId, query = {}, options = {}) {
1044
+ return call(
1045
+ this.ctx,
1046
+ RETRY_IDEMPOTENT,
1047
+ options,
1048
+ (client2, signal) => tasksList({ client: client2, signal, path: { workspaceId }, query: defined(query) })
1049
+ );
1050
+ }
1051
+ /** Every task from `query.cursor` on (or from the start), following `nextCursor` page by page. */
1052
+ listAll(workspaceId, query = {}, options = {}) {
1053
+ return paginate(
1054
+ query.cursor,
1055
+ (cursor) => this.list(workspaceId, { ...query, cursor }, options),
1056
+ (page) => [page.tasks, page.nextCursor]
1057
+ );
1058
+ }
1059
+ /** `tasks.get`: one task, wherever it started. */
1060
+ get(workspaceId, taskId, options = {}) {
1061
+ return call(
1062
+ this.ctx,
1063
+ RETRY_IDEMPOTENT,
1064
+ options,
1065
+ (client2, signal) => tasksGet({ client: client2, signal, path: { workspaceId, taskId } })
1066
+ );
1067
+ }
1068
+ /**
1069
+ * `tasks.create`: starts a task. Answers once the task is made, not when it's done:
1070
+ * poll `tasks.get` and `messages.list` to follow it.
1071
+ */
1072
+ create(workspaceId, body, options = {}) {
1073
+ const key = options.idempotencyKey ?? crypto.randomUUID();
1074
+ return call(
1075
+ this.ctx,
1076
+ RETRY_IDEMPOTENT,
1077
+ options,
1078
+ (client2, signal) => tasksCreate({ client: client2, signal, path: { workspaceId }, body, headers: { "Idempotency-Key": key } })
1079
+ );
1080
+ }
1081
+ /** `tasks.stop`: stops the task's running turn. A task that isn't running is `409 not_running`. */
1082
+ stop(workspaceId, taskId, options = {}) {
1083
+ return call(
1084
+ this.ctx,
1085
+ RETRY_UNAVAILABLE,
1086
+ options,
1087
+ (client2, signal) => tasksStop({ client: client2, signal, path: { workspaceId, taskId } })
1088
+ );
1089
+ }
1090
+ };
1091
+ var MessagesApi = class {
1092
+ /** @internal */
1093
+ constructor(ctx) {
1094
+ this.ctx = ctx;
1095
+ }
1096
+ ctx;
1097
+ /** `messages.create`: sends a follow-up on a task started from the API, CLI, MCP or dashboard. */
1098
+ create(workspaceId, taskId, body, options = {}) {
1099
+ const key = options.idempotencyKey ?? crypto.randomUUID();
1100
+ return call(
1101
+ this.ctx,
1102
+ RETRY_IDEMPOTENT,
1103
+ options,
1104
+ (client2, signal) => messagesCreate({ client: client2, signal, path: { workspaceId, taskId }, body, headers: { "Idempotency-Key": key } })
1105
+ );
1106
+ }
1107
+ /**
1108
+ * `messages.list`: one page of the task's conversation, oldest first. To wait
1109
+ * for a reply, poll with `after` set to the `id` of the last entry you read.
1110
+ */
1111
+ list(workspaceId, taskId, query = {}, options = {}) {
1112
+ return call(
1113
+ this.ctx,
1114
+ RETRY_IDEMPOTENT,
1115
+ options,
1116
+ (client2, signal) => messagesList({ client: client2, signal, path: { workspaceId, taskId }, query: defined(query) })
1117
+ );
1118
+ }
1119
+ /** Every entry after `query.after` (or from the start), following `next` page by page. */
1120
+ listAll(workspaceId, taskId, query = {}, options = {}) {
1121
+ return paginate(
1122
+ query.after,
1123
+ (after) => this.list(workspaceId, taskId, { ...query, after }, options),
1124
+ (page) => [page.messages, page.next]
1125
+ );
1126
+ }
1127
+ };
1128
+ var TicketsApi = class {
1129
+ /** @internal */
1130
+ constructor(ctx) {
1131
+ this.ctx = ctx;
1132
+ }
1133
+ ctx;
1134
+ /** `tickets.search`: open Linear and GitHub issues you could delegate. */
1135
+ search(workspaceId, query = {}, options = {}) {
1136
+ return call(
1137
+ this.ctx,
1138
+ RETRY_IDEMPOTENT,
1139
+ options,
1140
+ (client2, signal) => ticketsSearch({ client: client2, signal, path: { workspaceId }, query: defined(query) })
1141
+ );
1142
+ }
1143
+ /**
1144
+ * `tickets.delegate`: hands Sinatra an existing issue as you. Not retried:
1145
+ * the operation takes no `Idempotency-Key`.
1146
+ */
1147
+ delegate(workspaceId, body, options = {}) {
1148
+ return call(
1149
+ this.ctx,
1150
+ RETRY_NEVER,
1151
+ options,
1152
+ (client2, signal) => ticketsDelegate({ client: client2, signal, path: { workspaceId }, body })
1153
+ );
1154
+ }
1155
+ };
1156
+ async function* paginate(start, fetchPage, split) {
1157
+ let cursor = start;
1158
+ do {
1159
+ const [items, next] = split(await fetchPage(cursor));
1160
+ yield* items;
1161
+ cursor = next ?? void 0;
1162
+ } while (cursor);
1163
+ }
1164
+ function defined(query) {
1165
+ return Object.fromEntries(Object.entries(query).filter(([, v]) => v !== void 0));
1166
+ }
1167
+ function envToken() {
1168
+ return typeof process === "undefined" ? void 0 : process.env.SINATRA_TOKEN || void 0;
1169
+ }
1170
+ //# sourceMappingURL=index.cjs.map