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