@reverbia/sdk 1.0.0-next.20251208112742 → 1.0.0-next.20251209090511

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.
@@ -3,8 +3,141 @@ import { useCallback, useEffect, useRef, useState } from "react";
3
3
 
4
4
  // src/clientConfig.ts
5
5
  var BASE_URL = "https://ai-portal-dev.zetachain.com";
6
+ var createClientConfig = (config) => ({
7
+ ...config,
8
+ baseUrl: BASE_URL
9
+ });
10
+
11
+ // src/lib/chat/useChat/utils.ts
12
+ var VALIDATION_ERROR_MESSAGES = {
13
+ messages_required: "messages are required to call sendMessage.",
14
+ model_required: "model is required to call sendMessage.",
15
+ token_getter_required: "Token getter function is required.",
16
+ token_unavailable: "No access token available."
17
+ };
18
+ function validateMessages(messages) {
19
+ if (!messages?.length) {
20
+ return {
21
+ valid: false,
22
+ error: "messages_required",
23
+ message: VALIDATION_ERROR_MESSAGES.messages_required
24
+ };
25
+ }
26
+ return { valid: true };
27
+ }
28
+ function validateModel(model) {
29
+ if (!model) {
30
+ return {
31
+ valid: false,
32
+ error: "model_required",
33
+ message: VALIDATION_ERROR_MESSAGES.model_required
34
+ };
35
+ }
36
+ return { valid: true };
37
+ }
38
+ function validateTokenGetter(getToken) {
39
+ if (!getToken) {
40
+ return {
41
+ valid: false,
42
+ error: "token_getter_required",
43
+ message: VALIDATION_ERROR_MESSAGES.token_getter_required
44
+ };
45
+ }
46
+ return { valid: true };
47
+ }
48
+ function validateToken(token) {
49
+ if (!token) {
50
+ return {
51
+ valid: false,
52
+ error: "token_unavailable",
53
+ message: VALIDATION_ERROR_MESSAGES.token_unavailable
54
+ };
55
+ }
56
+ return { valid: true };
57
+ }
58
+ function createStreamAccumulator() {
59
+ return {
60
+ content: "",
61
+ completionId: "",
62
+ completionModel: "",
63
+ usage: {},
64
+ finishReason: void 0
65
+ };
66
+ }
67
+ function buildCompletionResponse(accumulator) {
68
+ return {
69
+ id: accumulator.completionId,
70
+ model: accumulator.completionModel,
71
+ choices: [
72
+ {
73
+ index: 0,
74
+ message: {
75
+ role: "assistant",
76
+ content: [{ type: "text", text: accumulator.content }]
77
+ },
78
+ finish_reason: accumulator.finishReason
79
+ }
80
+ ],
81
+ usage: Object.keys(accumulator.usage).length > 0 ? accumulator.usage : void 0
82
+ };
83
+ }
84
+ function createErrorResult(message, onError) {
85
+ if (onError) {
86
+ onError(new Error(message));
87
+ }
88
+ return { data: null, error: message };
89
+ }
90
+ function handleError(err, onError) {
91
+ const errorMsg = err instanceof Error ? err.message : "Failed to send message.";
92
+ const errorObj = err instanceof Error ? err : new Error(errorMsg);
93
+ if (onError) {
94
+ onError(errorObj);
95
+ }
96
+ return { data: null, error: errorMsg };
97
+ }
98
+ function parseSSEDataLine(line) {
99
+ if (!line.startsWith("data: ")) {
100
+ return null;
101
+ }
102
+ const data = line.substring(6).trim();
103
+ if (data === "[DONE]") {
104
+ return null;
105
+ }
106
+ try {
107
+ return JSON.parse(data);
108
+ } catch {
109
+ return null;
110
+ }
111
+ }
6
112
 
7
113
  // src/expo/useChat.ts
114
+ function processSSELines(lines, accumulator, onData, globalOnData) {
115
+ for (const line of lines) {
116
+ const chunk = parseSSEDataLine(line);
117
+ if (!chunk) continue;
118
+ if (chunk.id && !accumulator.completionId) {
119
+ accumulator.completionId = chunk.id;
120
+ }
121
+ if (chunk.model && !accumulator.completionModel) {
122
+ accumulator.completionModel = chunk.model;
123
+ }
124
+ if (chunk.usage) {
125
+ accumulator.usage = { ...accumulator.usage, ...chunk.usage };
126
+ }
127
+ if (chunk.choices?.[0]) {
128
+ const choice = chunk.choices[0];
129
+ if (choice.delta?.content) {
130
+ const content = choice.delta.content;
131
+ accumulator.content += content;
132
+ if (onData) onData(content);
133
+ if (globalOnData) globalOnData(content);
134
+ }
135
+ if (choice.finish_reason) {
136
+ accumulator.finishReason = choice.finish_reason;
137
+ }
138
+ }
139
+ }
140
+ }
8
141
  function useChat(options) {
9
142
  const {
10
143
  getToken,
@@ -35,20 +168,17 @@ function useChat(options) {
35
168
  model,
36
169
  onData
37
170
  }) => {
38
- if (!messages?.length) {
39
- const errorMsg = "messages are required to call sendMessage.";
40
- if (onError) onError(new Error(errorMsg));
41
- return { data: null, error: errorMsg };
171
+ const messagesValidation = validateMessages(messages);
172
+ if (!messagesValidation.valid) {
173
+ return createErrorResult(messagesValidation.message, onError);
42
174
  }
43
- if (!model) {
44
- const errorMsg = "model is required to call sendMessage.";
45
- if (onError) onError(new Error(errorMsg));
46
- return { data: null, error: errorMsg };
175
+ const modelValidation = validateModel(model);
176
+ if (!modelValidation.valid) {
177
+ return createErrorResult(modelValidation.message, onError);
47
178
  }
48
- if (!getToken) {
49
- const errorMsg = "Token getter function is required.";
50
- if (onError) onError(new Error(errorMsg));
51
- return { data: null, error: errorMsg };
179
+ const tokenGetterValidation = validateTokenGetter(getToken);
180
+ if (!tokenGetterValidation.valid) {
181
+ return createErrorResult(tokenGetterValidation.message, onError);
52
182
  }
53
183
  if (abortControllerRef.current) {
54
184
  abortControllerRef.current.abort();
@@ -58,20 +188,15 @@ function useChat(options) {
58
188
  setIsLoading(true);
59
189
  try {
60
190
  const token = await getToken();
61
- if (!token) {
62
- const errorMsg = "No access token available.";
191
+ const tokenValidation = validateToken(token);
192
+ if (!tokenValidation.valid) {
63
193
  setIsLoading(false);
64
- if (onError) onError(new Error(errorMsg));
65
- return { data: null, error: errorMsg };
194
+ return createErrorResult(tokenValidation.message, onError);
66
195
  }
67
196
  const result = await new Promise((resolve) => {
68
197
  const xhr = new XMLHttpRequest();
69
198
  const url = `${baseUrl}/api/v1/chat/completions`;
70
- let accumulatedContent = "";
71
- let completionId = "";
72
- let completionModel = "";
73
- let accumulatedUsage = {};
74
- let finishReason;
199
+ const accumulator = createStreamAccumulator();
75
200
  let lastProcessedIndex = 0;
76
201
  let incompleteLineBuffer = "";
77
202
  const abortHandler = () => {
@@ -91,93 +216,21 @@ function useChat(options) {
91
216
  if (!newData.endsWith("\n") && lines.length > 0) {
92
217
  incompleteLineBuffer = lines.pop() || "";
93
218
  }
94
- for (const line of lines) {
95
- if (line.startsWith("data: ")) {
96
- const data = line.substring(6).trim();
97
- if (data === "[DONE]") continue;
98
- try {
99
- const chunk = JSON.parse(data);
100
- if (chunk.id && !completionId) {
101
- completionId = chunk.id;
102
- }
103
- if (chunk.model && !completionModel) {
104
- completionModel = chunk.model;
105
- }
106
- if (chunk.usage) {
107
- accumulatedUsage = { ...accumulatedUsage, ...chunk.usage };
108
- }
109
- if (chunk.choices?.[0]) {
110
- const choice = chunk.choices[0];
111
- if (choice.delta?.content) {
112
- const content = choice.delta.content;
113
- accumulatedContent += content;
114
- if (onData) onData(content);
115
- if (globalOnData) globalOnData(content);
116
- }
117
- if (choice.finish_reason) {
118
- finishReason = choice.finish_reason;
119
- }
120
- }
121
- } catch {
122
- }
123
- }
124
- }
219
+ processSSELines(lines, accumulator, onData, globalOnData);
125
220
  };
126
221
  xhr.onload = () => {
127
222
  abortController.signal.removeEventListener("abort", abortHandler);
128
223
  if (incompleteLineBuffer) {
129
- const line = incompleteLineBuffer.trim();
130
- if (line.startsWith("data: ")) {
131
- const data = line.substring(6).trim();
132
- if (data !== "[DONE]") {
133
- try {
134
- const chunk = JSON.parse(data);
135
- if (chunk.id && !completionId) {
136
- completionId = chunk.id;
137
- }
138
- if (chunk.model && !completionModel) {
139
- completionModel = chunk.model;
140
- }
141
- if (chunk.usage) {
142
- accumulatedUsage = {
143
- ...accumulatedUsage,
144
- ...chunk.usage
145
- };
146
- }
147
- if (chunk.choices?.[0]) {
148
- const choice = chunk.choices[0];
149
- if (choice.delta?.content) {
150
- const content = choice.delta.content;
151
- accumulatedContent += content;
152
- if (onData) onData(content);
153
- if (globalOnData) globalOnData(content);
154
- }
155
- if (choice.finish_reason) {
156
- finishReason = choice.finish_reason;
157
- }
158
- }
159
- } catch {
160
- }
161
- }
162
- }
224
+ processSSELines(
225
+ [incompleteLineBuffer.trim()],
226
+ accumulator,
227
+ onData,
228
+ globalOnData
229
+ );
163
230
  incompleteLineBuffer = "";
164
231
  }
165
232
  if (xhr.status >= 200 && xhr.status < 300) {
166
- const completion = {
167
- id: completionId,
168
- model: completionModel,
169
- choices: [
170
- {
171
- index: 0,
172
- message: {
173
- role: "assistant",
174
- content: [{ type: "text", text: accumulatedContent }]
175
- },
176
- finish_reason: finishReason
177
- }
178
- ],
179
- usage: Object.keys(accumulatedUsage).length > 0 ? accumulatedUsage : void 0
180
- };
233
+ const completion = buildCompletionResponse(accumulator);
181
234
  setIsLoading(false);
182
235
  if (onFinish) onFinish(completion);
183
236
  resolve({ data: completion, error: null });
@@ -210,27 +263,927 @@ function useChat(options) {
210
263
  });
211
264
  return result;
212
265
  } catch (err) {
213
- const errorMsg = err instanceof Error ? err.message : "Failed to send message.";
214
- const errorObj = err instanceof Error ? err : new Error(errorMsg);
215
266
  setIsLoading(false);
267
+ return handleError(err, onError);
268
+ } finally {
269
+ if (abortControllerRef.current === abortController) {
270
+ abortControllerRef.current = null;
271
+ }
272
+ }
273
+ },
274
+ [getToken, baseUrl, globalOnData, onFinish, onError]
275
+ );
276
+ return {
277
+ isLoading,
278
+ sendMessage,
279
+ stop
280
+ };
281
+ }
282
+
283
+ // src/react/useImageGeneration.ts
284
+ import { useCallback as useCallback2, useEffect as useEffect2, useRef as useRef2, useState as useState2 } from "react";
285
+
286
+ // src/client/core/bodySerializer.gen.ts
287
+ var jsonBodySerializer = {
288
+ bodySerializer: (body) => JSON.stringify(
289
+ body,
290
+ (_key, value) => typeof value === "bigint" ? value.toString() : value
291
+ )
292
+ };
293
+
294
+ // src/client/core/params.gen.ts
295
+ var extraPrefixesMap = {
296
+ $body_: "body",
297
+ $headers_: "headers",
298
+ $path_: "path",
299
+ $query_: "query"
300
+ };
301
+ var extraPrefixes = Object.entries(extraPrefixesMap);
302
+
303
+ // src/client/core/serverSentEvents.gen.ts
304
+ var createSseClient = ({
305
+ onRequest,
306
+ onSseError,
307
+ onSseEvent,
308
+ responseTransformer,
309
+ responseValidator,
310
+ sseDefaultRetryDelay,
311
+ sseMaxRetryAttempts,
312
+ sseMaxRetryDelay,
313
+ sseSleepFn,
314
+ url,
315
+ ...options
316
+ }) => {
317
+ let lastEventId;
318
+ const sleep = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
319
+ const createStream = async function* () {
320
+ let retryDelay = sseDefaultRetryDelay ?? 3e3;
321
+ let attempt = 0;
322
+ const signal = options.signal ?? new AbortController().signal;
323
+ while (true) {
324
+ if (signal.aborted) break;
325
+ attempt++;
326
+ const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers);
327
+ if (lastEventId !== void 0) {
328
+ headers.set("Last-Event-ID", lastEventId);
329
+ }
330
+ try {
331
+ const requestInit = {
332
+ redirect: "follow",
333
+ ...options,
334
+ body: options.serializedBody,
335
+ headers,
336
+ signal
337
+ };
338
+ let request = new Request(url, requestInit);
339
+ if (onRequest) {
340
+ request = await onRequest(url, requestInit);
341
+ }
342
+ const _fetch = options.fetch ?? globalThis.fetch;
343
+ const response = await _fetch(request);
344
+ if (!response.ok)
345
+ throw new Error(
346
+ `SSE failed: ${response.status} ${response.statusText}`
347
+ );
348
+ if (!response.body) throw new Error("No body in SSE response");
349
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
350
+ let buffer = "";
351
+ const abortHandler = () => {
352
+ try {
353
+ reader.cancel();
354
+ } catch {
355
+ }
356
+ };
357
+ signal.addEventListener("abort", abortHandler);
358
+ try {
359
+ while (true) {
360
+ const { done, value } = await reader.read();
361
+ if (done) break;
362
+ buffer += value;
363
+ const chunks = buffer.split("\n\n");
364
+ buffer = chunks.pop() ?? "";
365
+ for (const chunk of chunks) {
366
+ const lines = chunk.split("\n");
367
+ const dataLines = [];
368
+ let eventName;
369
+ for (const line of lines) {
370
+ if (line.startsWith("data:")) {
371
+ dataLines.push(line.replace(/^data:\s*/, ""));
372
+ } else if (line.startsWith("event:")) {
373
+ eventName = line.replace(/^event:\s*/, "");
374
+ } else if (line.startsWith("id:")) {
375
+ lastEventId = line.replace(/^id:\s*/, "");
376
+ } else if (line.startsWith("retry:")) {
377
+ const parsed = Number.parseInt(
378
+ line.replace(/^retry:\s*/, ""),
379
+ 10
380
+ );
381
+ if (!Number.isNaN(parsed)) {
382
+ retryDelay = parsed;
383
+ }
384
+ }
385
+ }
386
+ let data;
387
+ let parsedJson = false;
388
+ if (dataLines.length) {
389
+ const rawData = dataLines.join("\n");
390
+ try {
391
+ data = JSON.parse(rawData);
392
+ parsedJson = true;
393
+ } catch {
394
+ data = rawData;
395
+ }
396
+ }
397
+ if (parsedJson) {
398
+ if (responseValidator) {
399
+ await responseValidator(data);
400
+ }
401
+ if (responseTransformer) {
402
+ data = await responseTransformer(data);
403
+ }
404
+ }
405
+ onSseEvent?.({
406
+ data,
407
+ event: eventName,
408
+ id: lastEventId,
409
+ retry: retryDelay
410
+ });
411
+ if (dataLines.length) {
412
+ yield data;
413
+ }
414
+ }
415
+ }
416
+ } finally {
417
+ signal.removeEventListener("abort", abortHandler);
418
+ reader.releaseLock();
419
+ }
420
+ break;
421
+ } catch (error) {
422
+ onSseError?.(error);
423
+ if (sseMaxRetryAttempts !== void 0 && attempt >= sseMaxRetryAttempts) {
424
+ break;
425
+ }
426
+ const backoff = Math.min(
427
+ retryDelay * 2 ** (attempt - 1),
428
+ sseMaxRetryDelay ?? 3e4
429
+ );
430
+ await sleep(backoff);
431
+ }
432
+ }
433
+ };
434
+ const stream = createStream();
435
+ return { stream };
436
+ };
437
+
438
+ // src/client/core/pathSerializer.gen.ts
439
+ var separatorArrayExplode = (style) => {
440
+ switch (style) {
441
+ case "label":
442
+ return ".";
443
+ case "matrix":
444
+ return ";";
445
+ case "simple":
446
+ return ",";
447
+ default:
448
+ return "&";
449
+ }
450
+ };
451
+ var separatorArrayNoExplode = (style) => {
452
+ switch (style) {
453
+ case "form":
454
+ return ",";
455
+ case "pipeDelimited":
456
+ return "|";
457
+ case "spaceDelimited":
458
+ return "%20";
459
+ default:
460
+ return ",";
461
+ }
462
+ };
463
+ var separatorObjectExplode = (style) => {
464
+ switch (style) {
465
+ case "label":
466
+ return ".";
467
+ case "matrix":
468
+ return ";";
469
+ case "simple":
470
+ return ",";
471
+ default:
472
+ return "&";
473
+ }
474
+ };
475
+ var serializeArrayParam = ({
476
+ allowReserved,
477
+ explode,
478
+ name,
479
+ style,
480
+ value
481
+ }) => {
482
+ if (!explode) {
483
+ const joinedValues2 = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
484
+ switch (style) {
485
+ case "label":
486
+ return `.${joinedValues2}`;
487
+ case "matrix":
488
+ return `;${name}=${joinedValues2}`;
489
+ case "simple":
490
+ return joinedValues2;
491
+ default:
492
+ return `${name}=${joinedValues2}`;
493
+ }
494
+ }
495
+ const separator = separatorArrayExplode(style);
496
+ const joinedValues = value.map((v) => {
497
+ if (style === "label" || style === "simple") {
498
+ return allowReserved ? v : encodeURIComponent(v);
499
+ }
500
+ return serializePrimitiveParam({
501
+ allowReserved,
502
+ name,
503
+ value: v
504
+ });
505
+ }).join(separator);
506
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
507
+ };
508
+ var serializePrimitiveParam = ({
509
+ allowReserved,
510
+ name,
511
+ value
512
+ }) => {
513
+ if (value === void 0 || value === null) {
514
+ return "";
515
+ }
516
+ if (typeof value === "object") {
517
+ throw new Error(
518
+ "Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these."
519
+ );
520
+ }
521
+ return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
522
+ };
523
+ var serializeObjectParam = ({
524
+ allowReserved,
525
+ explode,
526
+ name,
527
+ style,
528
+ value,
529
+ valueOnly
530
+ }) => {
531
+ if (value instanceof Date) {
532
+ return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
533
+ }
534
+ if (style !== "deepObject" && !explode) {
535
+ let values = [];
536
+ Object.entries(value).forEach(([key, v]) => {
537
+ values = [
538
+ ...values,
539
+ key,
540
+ allowReserved ? v : encodeURIComponent(v)
541
+ ];
542
+ });
543
+ const joinedValues2 = values.join(",");
544
+ switch (style) {
545
+ case "form":
546
+ return `${name}=${joinedValues2}`;
547
+ case "label":
548
+ return `.${joinedValues2}`;
549
+ case "matrix":
550
+ return `;${name}=${joinedValues2}`;
551
+ default:
552
+ return joinedValues2;
553
+ }
554
+ }
555
+ const separator = separatorObjectExplode(style);
556
+ const joinedValues = Object.entries(value).map(
557
+ ([key, v]) => serializePrimitiveParam({
558
+ allowReserved,
559
+ name: style === "deepObject" ? `${name}[${key}]` : key,
560
+ value: v
561
+ })
562
+ ).join(separator);
563
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
564
+ };
565
+
566
+ // src/client/core/utils.gen.ts
567
+ function getValidRequestBody(options) {
568
+ const hasBody = options.body !== void 0;
569
+ const isSerializedBody = hasBody && options.bodySerializer;
570
+ if (isSerializedBody) {
571
+ if ("serializedBody" in options) {
572
+ const hasSerializedBody = options.serializedBody !== void 0 && options.serializedBody !== "";
573
+ return hasSerializedBody ? options.serializedBody : null;
574
+ }
575
+ return options.body !== "" ? options.body : null;
576
+ }
577
+ if (hasBody) {
578
+ return options.body;
579
+ }
580
+ return void 0;
581
+ }
582
+
583
+ // src/client/core/auth.gen.ts
584
+ var getAuthToken = async (auth, callback) => {
585
+ const token = typeof callback === "function" ? await callback(auth) : callback;
586
+ if (!token) {
587
+ return;
588
+ }
589
+ if (auth.scheme === "bearer") {
590
+ return `Bearer ${token}`;
591
+ }
592
+ if (auth.scheme === "basic") {
593
+ return `Basic ${btoa(token)}`;
594
+ }
595
+ return token;
596
+ };
597
+
598
+ // src/client/client/utils.gen.ts
599
+ var PATH_PARAM_RE = /\{[^{}]+\}/g;
600
+ var defaultPathSerializer = ({ path, url: _url }) => {
601
+ let url = _url;
602
+ const matches = _url.match(PATH_PARAM_RE);
603
+ if (matches) {
604
+ for (const match of matches) {
605
+ let explode = false;
606
+ let name = match.substring(1, match.length - 1);
607
+ let style = "simple";
608
+ if (name.endsWith("*")) {
609
+ explode = true;
610
+ name = name.substring(0, name.length - 1);
611
+ }
612
+ if (name.startsWith(".")) {
613
+ name = name.substring(1);
614
+ style = "label";
615
+ } else if (name.startsWith(";")) {
616
+ name = name.substring(1);
617
+ style = "matrix";
618
+ }
619
+ const value = path[name];
620
+ if (value === void 0 || value === null) {
621
+ continue;
622
+ }
623
+ if (Array.isArray(value)) {
624
+ url = url.replace(
625
+ match,
626
+ serializeArrayParam({ explode, name, style, value })
627
+ );
628
+ continue;
629
+ }
630
+ if (typeof value === "object") {
631
+ url = url.replace(
632
+ match,
633
+ serializeObjectParam({
634
+ explode,
635
+ name,
636
+ style,
637
+ value,
638
+ valueOnly: true
639
+ })
640
+ );
641
+ continue;
642
+ }
643
+ if (style === "matrix") {
644
+ url = url.replace(
645
+ match,
646
+ `;${serializePrimitiveParam({
647
+ name,
648
+ value
649
+ })}`
650
+ );
651
+ continue;
652
+ }
653
+ const replaceValue = encodeURIComponent(
654
+ style === "label" ? `.${value}` : value
655
+ );
656
+ url = url.replace(match, replaceValue);
657
+ }
658
+ }
659
+ return url;
660
+ };
661
+ var createQuerySerializer = ({
662
+ parameters = {},
663
+ ...args
664
+ } = {}) => {
665
+ const querySerializer = (queryParams) => {
666
+ const search = [];
667
+ if (queryParams && typeof queryParams === "object") {
668
+ for (const name in queryParams) {
669
+ const value = queryParams[name];
670
+ if (value === void 0 || value === null) {
671
+ continue;
672
+ }
673
+ const options = parameters[name] || args;
674
+ if (Array.isArray(value)) {
675
+ const serializedArray = serializeArrayParam({
676
+ allowReserved: options.allowReserved,
677
+ explode: true,
678
+ name,
679
+ style: "form",
680
+ value,
681
+ ...options.array
682
+ });
683
+ if (serializedArray) search.push(serializedArray);
684
+ } else if (typeof value === "object") {
685
+ const serializedObject = serializeObjectParam({
686
+ allowReserved: options.allowReserved,
687
+ explode: true,
688
+ name,
689
+ style: "deepObject",
690
+ value,
691
+ ...options.object
692
+ });
693
+ if (serializedObject) search.push(serializedObject);
694
+ } else {
695
+ const serializedPrimitive = serializePrimitiveParam({
696
+ allowReserved: options.allowReserved,
697
+ name,
698
+ value
699
+ });
700
+ if (serializedPrimitive) search.push(serializedPrimitive);
701
+ }
702
+ }
703
+ }
704
+ return search.join("&");
705
+ };
706
+ return querySerializer;
707
+ };
708
+ var getParseAs = (contentType) => {
709
+ if (!contentType) {
710
+ return "stream";
711
+ }
712
+ const cleanContent = contentType.split(";")[0]?.trim();
713
+ if (!cleanContent) {
714
+ return;
715
+ }
716
+ if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) {
717
+ return "json";
718
+ }
719
+ if (cleanContent === "multipart/form-data") {
720
+ return "formData";
721
+ }
722
+ if (["application/", "audio/", "image/", "video/"].some(
723
+ (type) => cleanContent.startsWith(type)
724
+ )) {
725
+ return "blob";
726
+ }
727
+ if (cleanContent.startsWith("text/")) {
728
+ return "text";
729
+ }
730
+ return;
731
+ };
732
+ var checkForExistence = (options, name) => {
733
+ if (!name) {
734
+ return false;
735
+ }
736
+ if (options.headers.has(name) || options.query?.[name] || options.headers.get("Cookie")?.includes(`${name}=`)) {
737
+ return true;
738
+ }
739
+ return false;
740
+ };
741
+ var setAuthParams = async ({
742
+ security,
743
+ ...options
744
+ }) => {
745
+ for (const auth of security) {
746
+ if (checkForExistence(options, auth.name)) {
747
+ continue;
748
+ }
749
+ const token = await getAuthToken(auth, options.auth);
750
+ if (!token) {
751
+ continue;
752
+ }
753
+ const name = auth.name ?? "Authorization";
754
+ switch (auth.in) {
755
+ case "query":
756
+ if (!options.query) {
757
+ options.query = {};
758
+ }
759
+ options.query[name] = token;
760
+ break;
761
+ case "cookie":
762
+ options.headers.append("Cookie", `${name}=${token}`);
763
+ break;
764
+ case "header":
765
+ default:
766
+ options.headers.set(name, token);
767
+ break;
768
+ }
769
+ }
770
+ };
771
+ var buildUrl = (options) => {
772
+ const url = getUrl({
773
+ baseUrl: options.baseUrl,
774
+ path: options.path,
775
+ query: options.query,
776
+ querySerializer: typeof options.querySerializer === "function" ? options.querySerializer : createQuerySerializer(options.querySerializer),
777
+ url: options.url
778
+ });
779
+ return url;
780
+ };
781
+ var getUrl = ({
782
+ baseUrl,
783
+ path,
784
+ query,
785
+ querySerializer,
786
+ url: _url
787
+ }) => {
788
+ const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
789
+ let url = (baseUrl ?? "") + pathUrl;
790
+ if (path) {
791
+ url = defaultPathSerializer({ path, url });
792
+ }
793
+ let search = query ? querySerializer(query) : "";
794
+ if (search.startsWith("?")) {
795
+ search = search.substring(1);
796
+ }
797
+ if (search) {
798
+ url += `?${search}`;
799
+ }
800
+ return url;
801
+ };
802
+ var mergeConfigs = (a, b) => {
803
+ const config = { ...a, ...b };
804
+ if (config.baseUrl?.endsWith("/")) {
805
+ config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
806
+ }
807
+ config.headers = mergeHeaders(a.headers, b.headers);
808
+ return config;
809
+ };
810
+ var headersEntries = (headers) => {
811
+ const entries = [];
812
+ headers.forEach((value, key) => {
813
+ entries.push([key, value]);
814
+ });
815
+ return entries;
816
+ };
817
+ var mergeHeaders = (...headers) => {
818
+ const mergedHeaders = new Headers();
819
+ for (const header of headers) {
820
+ if (!header || typeof header !== "object") {
821
+ continue;
822
+ }
823
+ const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
824
+ for (const [key, value] of iterator) {
825
+ if (value === null) {
826
+ mergedHeaders.delete(key);
827
+ } else if (Array.isArray(value)) {
828
+ for (const v of value) {
829
+ mergedHeaders.append(key, v);
830
+ }
831
+ } else if (value !== void 0) {
832
+ mergedHeaders.set(
833
+ key,
834
+ typeof value === "object" ? JSON.stringify(value) : value
835
+ );
836
+ }
837
+ }
838
+ }
839
+ return mergedHeaders;
840
+ };
841
+ var Interceptors = class {
842
+ constructor() {
843
+ this.fns = [];
844
+ }
845
+ clear() {
846
+ this.fns = [];
847
+ }
848
+ eject(id) {
849
+ const index = this.getInterceptorIndex(id);
850
+ if (this.fns[index]) {
851
+ this.fns[index] = null;
852
+ }
853
+ }
854
+ exists(id) {
855
+ const index = this.getInterceptorIndex(id);
856
+ return Boolean(this.fns[index]);
857
+ }
858
+ getInterceptorIndex(id) {
859
+ if (typeof id === "number") {
860
+ return this.fns[id] ? id : -1;
861
+ }
862
+ return this.fns.indexOf(id);
863
+ }
864
+ update(id, fn) {
865
+ const index = this.getInterceptorIndex(id);
866
+ if (this.fns[index]) {
867
+ this.fns[index] = fn;
868
+ return id;
869
+ }
870
+ return false;
871
+ }
872
+ use(fn) {
873
+ this.fns.push(fn);
874
+ return this.fns.length - 1;
875
+ }
876
+ };
877
+ var createInterceptors = () => ({
878
+ error: new Interceptors(),
879
+ request: new Interceptors(),
880
+ response: new Interceptors()
881
+ });
882
+ var defaultQuerySerializer = createQuerySerializer({
883
+ allowReserved: false,
884
+ array: {
885
+ explode: true,
886
+ style: "form"
887
+ },
888
+ object: {
889
+ explode: true,
890
+ style: "deepObject"
891
+ }
892
+ });
893
+ var defaultHeaders = {
894
+ "Content-Type": "application/json"
895
+ };
896
+ var createConfig = (override = {}) => ({
897
+ ...jsonBodySerializer,
898
+ headers: defaultHeaders,
899
+ parseAs: "auto",
900
+ querySerializer: defaultQuerySerializer,
901
+ ...override
902
+ });
903
+
904
+ // src/client/client/client.gen.ts
905
+ var createClient = (config = {}) => {
906
+ let _config = mergeConfigs(createConfig(), config);
907
+ const getConfig = () => ({ ..._config });
908
+ const setConfig = (config2) => {
909
+ _config = mergeConfigs(_config, config2);
910
+ return getConfig();
911
+ };
912
+ const interceptors = createInterceptors();
913
+ const beforeRequest = async (options) => {
914
+ const opts = {
915
+ ..._config,
916
+ ...options,
917
+ fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
918
+ headers: mergeHeaders(_config.headers, options.headers),
919
+ serializedBody: void 0
920
+ };
921
+ if (opts.security) {
922
+ await setAuthParams({
923
+ ...opts,
924
+ security: opts.security
925
+ });
926
+ }
927
+ if (opts.requestValidator) {
928
+ await opts.requestValidator(opts);
929
+ }
930
+ if (opts.body !== void 0 && opts.bodySerializer) {
931
+ opts.serializedBody = opts.bodySerializer(opts.body);
932
+ }
933
+ if (opts.body === void 0 || opts.serializedBody === "") {
934
+ opts.headers.delete("Content-Type");
935
+ }
936
+ const url = buildUrl(opts);
937
+ return { opts, url };
938
+ };
939
+ const request = async (options) => {
940
+ const { opts, url } = await beforeRequest(options);
941
+ for (const fn of interceptors.request.fns) {
942
+ if (fn) {
943
+ await fn(opts);
944
+ }
945
+ }
946
+ const _fetch = opts.fetch;
947
+ const requestInit = {
948
+ ...opts,
949
+ body: getValidRequestBody(opts)
950
+ };
951
+ let response = await _fetch(url, requestInit);
952
+ for (const fn of interceptors.response.fns) {
953
+ if (fn) {
954
+ response = await fn(response, opts);
955
+ }
956
+ }
957
+ const result = {
958
+ response
959
+ };
960
+ if (response.ok) {
961
+ const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json";
962
+ if (response.status === 204 || response.headers.get("Content-Length") === "0") {
963
+ let emptyData;
964
+ switch (parseAs) {
965
+ case "arrayBuffer":
966
+ case "blob":
967
+ case "text":
968
+ emptyData = await response[parseAs]();
969
+ break;
970
+ case "formData":
971
+ emptyData = new FormData();
972
+ break;
973
+ case "stream":
974
+ emptyData = response.body;
975
+ break;
976
+ case "json":
977
+ default:
978
+ emptyData = {};
979
+ break;
980
+ }
981
+ return {
982
+ data: emptyData,
983
+ ...result
984
+ };
985
+ }
986
+ let data;
987
+ switch (parseAs) {
988
+ case "arrayBuffer":
989
+ case "blob":
990
+ case "formData":
991
+ case "json":
992
+ case "text":
993
+ data = await response[parseAs]();
994
+ break;
995
+ case "stream":
996
+ return {
997
+ data: response.body,
998
+ ...result
999
+ };
1000
+ }
1001
+ if (parseAs === "json") {
1002
+ if (opts.responseValidator) {
1003
+ await opts.responseValidator(data);
1004
+ }
1005
+ if (opts.responseTransformer) {
1006
+ data = await opts.responseTransformer(data);
1007
+ }
1008
+ }
1009
+ return {
1010
+ data,
1011
+ ...result
1012
+ };
1013
+ }
1014
+ const textError = await response.text();
1015
+ let jsonError;
1016
+ try {
1017
+ jsonError = JSON.parse(textError);
1018
+ } catch {
1019
+ }
1020
+ const error = jsonError ?? textError;
1021
+ let finalError = error;
1022
+ for (const fn of interceptors.error.fns) {
1023
+ if (fn) {
1024
+ finalError = await fn(error, response, opts);
1025
+ }
1026
+ }
1027
+ finalError = finalError || {};
1028
+ if (opts.throwOnError) {
1029
+ throw finalError;
1030
+ }
1031
+ return {
1032
+ error: finalError,
1033
+ ...result
1034
+ };
1035
+ };
1036
+ const makeMethodFn = (method) => (options) => request({ ...options, method });
1037
+ const makeSseFn = (method) => async (options) => {
1038
+ const { opts, url } = await beforeRequest(options);
1039
+ return createSseClient({
1040
+ ...opts,
1041
+ body: opts.body,
1042
+ headers: opts.headers,
1043
+ method,
1044
+ onRequest: async (url2, init) => {
1045
+ let request2 = new Request(url2, init);
1046
+ const requestInit = {
1047
+ ...init,
1048
+ method: init.method,
1049
+ url: url2
1050
+ };
1051
+ for (const fn of interceptors.request.fns) {
1052
+ if (fn) {
1053
+ await fn(requestInit);
1054
+ request2 = new Request(requestInit.url, requestInit);
1055
+ }
1056
+ }
1057
+ return request2;
1058
+ },
1059
+ url
1060
+ });
1061
+ };
1062
+ return {
1063
+ buildUrl,
1064
+ connect: makeMethodFn("CONNECT"),
1065
+ delete: makeMethodFn("DELETE"),
1066
+ get: makeMethodFn("GET"),
1067
+ getConfig,
1068
+ head: makeMethodFn("HEAD"),
1069
+ interceptors,
1070
+ options: makeMethodFn("OPTIONS"),
1071
+ patch: makeMethodFn("PATCH"),
1072
+ post: makeMethodFn("POST"),
1073
+ put: makeMethodFn("PUT"),
1074
+ request,
1075
+ setConfig,
1076
+ sse: {
1077
+ connect: makeSseFn("CONNECT"),
1078
+ delete: makeSseFn("DELETE"),
1079
+ get: makeSseFn("GET"),
1080
+ head: makeSseFn("HEAD"),
1081
+ options: makeSseFn("OPTIONS"),
1082
+ patch: makeSseFn("PATCH"),
1083
+ post: makeSseFn("POST"),
1084
+ put: makeSseFn("PUT"),
1085
+ trace: makeSseFn("TRACE")
1086
+ },
1087
+ trace: makeMethodFn("TRACE")
1088
+ };
1089
+ };
1090
+
1091
+ // src/client/client.gen.ts
1092
+ var client = createClient(createClientConfig(createConfig()));
1093
+
1094
+ // src/client/sdk.gen.ts
1095
+ var postApiV1ImagesGenerations = (options) => {
1096
+ return (options.client ?? client).post({
1097
+ url: "/api/v1/images/generations",
1098
+ ...options,
1099
+ headers: {
1100
+ "Content-Type": "application/json",
1101
+ ...options.headers
1102
+ }
1103
+ });
1104
+ };
1105
+
1106
+ // src/react/useImageGeneration.ts
1107
+ function useImageGeneration(options = {}) {
1108
+ const { getToken, baseUrl = BASE_URL, onFinish, onError } = options;
1109
+ const [isLoading, setIsLoading] = useState2(false);
1110
+ const abortControllerRef = useRef2(null);
1111
+ useEffect2(() => {
1112
+ return () => {
1113
+ if (abortControllerRef.current) {
1114
+ abortControllerRef.current.abort();
1115
+ abortControllerRef.current = null;
1116
+ }
1117
+ };
1118
+ }, []);
1119
+ const stop = useCallback2(() => {
1120
+ if (abortControllerRef.current) {
1121
+ abortControllerRef.current.abort();
1122
+ abortControllerRef.current = null;
1123
+ }
1124
+ }, []);
1125
+ const generateImage = useCallback2(
1126
+ async (args) => {
1127
+ if (abortControllerRef.current) {
1128
+ abortControllerRef.current.abort();
1129
+ }
1130
+ const abortController = new AbortController();
1131
+ abortControllerRef.current = abortController;
1132
+ setIsLoading(true);
1133
+ try {
1134
+ if (!getToken) {
1135
+ throw new Error("Token getter function is required.");
1136
+ }
1137
+ const token = await getToken();
1138
+ if (!token) {
1139
+ throw new Error("No access token available.");
1140
+ }
1141
+ const response = await postApiV1ImagesGenerations({
1142
+ baseUrl,
1143
+ body: args,
1144
+ headers: {
1145
+ Authorization: `Bearer ${token}`
1146
+ },
1147
+ signal: abortController.signal
1148
+ });
1149
+ if (response.error) {
1150
+ const errorMsg = response.error.error || "Failed to generate image";
1151
+ throw new Error(errorMsg);
1152
+ }
1153
+ if (!response.data) {
1154
+ throw new Error("No data received from image generation API");
1155
+ }
1156
+ const result = response.data;
1157
+ if (onFinish) {
1158
+ onFinish(result);
1159
+ }
1160
+ return { data: result, error: null };
1161
+ } catch (err) {
1162
+ if (err instanceof Error && err.name === "AbortError") {
1163
+ return { data: null, error: "Request aborted" };
1164
+ }
1165
+ const errorMsg = err instanceof Error ? err.message : "Failed to generate image.";
1166
+ const errorObj = err instanceof Error ? err : new Error(errorMsg);
216
1167
  if (onError) {
217
1168
  onError(errorObj);
218
1169
  }
219
1170
  return { data: null, error: errorMsg };
220
1171
  } finally {
221
1172
  if (abortControllerRef.current === abortController) {
1173
+ setIsLoading(false);
222
1174
  abortControllerRef.current = null;
223
1175
  }
224
1176
  }
225
1177
  },
226
- [getToken, baseUrl, globalOnData, onFinish, onError]
1178
+ [getToken, baseUrl, onFinish, onError]
227
1179
  );
228
1180
  return {
229
1181
  isLoading,
230
- sendMessage,
1182
+ generateImage,
231
1183
  stop
232
1184
  };
233
1185
  }
234
1186
  export {
235
- useChat
1187
+ useChat,
1188
+ useImageGeneration
236
1189
  };