@anuma/sdk 1.0.0-next.20260224164627

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.mjs ADDED
@@ -0,0 +1,1632 @@
1
+ import {
2
+ BASE_URL,
3
+ createClientConfig
4
+ } from "./chunk-KDFGY4SK.mjs";
5
+
6
+ // src/client/core/bodySerializer.gen.ts
7
+ var jsonBodySerializer = {
8
+ bodySerializer: (body) => JSON.stringify(
9
+ body,
10
+ (_key, value) => typeof value === "bigint" ? value.toString() : value
11
+ )
12
+ };
13
+
14
+ // src/client/core/params.gen.ts
15
+ var extraPrefixesMap = {
16
+ $body_: "body",
17
+ $headers_: "headers",
18
+ $path_: "path",
19
+ $query_: "query"
20
+ };
21
+ var extraPrefixes = Object.entries(extraPrefixesMap);
22
+
23
+ // src/client/core/serverSentEvents.gen.ts
24
+ var createSseClient = ({
25
+ onRequest,
26
+ onSseError,
27
+ onSseEvent,
28
+ responseTransformer,
29
+ responseValidator,
30
+ sseDefaultRetryDelay,
31
+ sseMaxRetryAttempts,
32
+ sseMaxRetryDelay,
33
+ sseSleepFn,
34
+ url,
35
+ ...options
36
+ }) => {
37
+ let lastEventId;
38
+ const sleep = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
39
+ const createStream = async function* () {
40
+ let retryDelay = sseDefaultRetryDelay ?? 3e3;
41
+ let attempt = 0;
42
+ const signal = options.signal ?? new AbortController().signal;
43
+ while (true) {
44
+ if (signal.aborted) break;
45
+ attempt++;
46
+ const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers);
47
+ if (lastEventId !== void 0) {
48
+ headers.set("Last-Event-ID", lastEventId);
49
+ }
50
+ try {
51
+ const requestInit = {
52
+ redirect: "follow",
53
+ ...options,
54
+ body: options.serializedBody,
55
+ headers,
56
+ signal
57
+ };
58
+ let request = new Request(url, requestInit);
59
+ if (onRequest) {
60
+ request = await onRequest(url, requestInit);
61
+ }
62
+ const _fetch = options.fetch ?? globalThis.fetch;
63
+ const response = await _fetch(request);
64
+ if (!response.ok)
65
+ throw new Error(
66
+ `SSE failed: ${response.status} ${response.statusText}`
67
+ );
68
+ if (!response.body) throw new Error("No body in SSE response");
69
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
70
+ let buffer = "";
71
+ const abortHandler = () => {
72
+ try {
73
+ reader.cancel();
74
+ } catch {
75
+ }
76
+ };
77
+ signal.addEventListener("abort", abortHandler);
78
+ try {
79
+ while (true) {
80
+ const { done, value } = await reader.read();
81
+ if (done) break;
82
+ buffer += value;
83
+ const chunks = buffer.split("\n\n");
84
+ buffer = chunks.pop() ?? "";
85
+ for (const chunk of chunks) {
86
+ const lines = chunk.split("\n");
87
+ const dataLines = [];
88
+ let eventName;
89
+ for (const line of lines) {
90
+ if (line.startsWith("data:")) {
91
+ dataLines.push(line.replace(/^data:\s*/, ""));
92
+ } else if (line.startsWith("event:")) {
93
+ eventName = line.replace(/^event:\s*/, "");
94
+ } else if (line.startsWith("id:")) {
95
+ lastEventId = line.replace(/^id:\s*/, "");
96
+ } else if (line.startsWith("retry:")) {
97
+ const parsed = Number.parseInt(
98
+ line.replace(/^retry:\s*/, ""),
99
+ 10
100
+ );
101
+ if (!Number.isNaN(parsed)) {
102
+ retryDelay = parsed;
103
+ }
104
+ }
105
+ }
106
+ let data;
107
+ let parsedJson = false;
108
+ if (dataLines.length) {
109
+ const rawData = dataLines.join("\n");
110
+ try {
111
+ data = JSON.parse(rawData);
112
+ parsedJson = true;
113
+ } catch {
114
+ data = rawData;
115
+ }
116
+ }
117
+ if (parsedJson) {
118
+ if (responseValidator) {
119
+ await responseValidator(data);
120
+ }
121
+ if (responseTransformer) {
122
+ data = await responseTransformer(data);
123
+ }
124
+ }
125
+ onSseEvent?.({
126
+ data,
127
+ event: eventName,
128
+ id: lastEventId,
129
+ retry: retryDelay
130
+ });
131
+ if (dataLines.length) {
132
+ yield data;
133
+ }
134
+ }
135
+ }
136
+ } finally {
137
+ signal.removeEventListener("abort", abortHandler);
138
+ reader.releaseLock();
139
+ }
140
+ break;
141
+ } catch (error) {
142
+ onSseError?.(error);
143
+ if (sseMaxRetryAttempts !== void 0 && attempt >= sseMaxRetryAttempts) {
144
+ break;
145
+ }
146
+ const backoff = Math.min(
147
+ retryDelay * 2 ** (attempt - 1),
148
+ sseMaxRetryDelay ?? 3e4
149
+ );
150
+ await sleep(backoff);
151
+ }
152
+ }
153
+ };
154
+ const stream = createStream();
155
+ return { stream };
156
+ };
157
+
158
+ // src/client/core/pathSerializer.gen.ts
159
+ var separatorArrayExplode = (style) => {
160
+ switch (style) {
161
+ case "label":
162
+ return ".";
163
+ case "matrix":
164
+ return ";";
165
+ case "simple":
166
+ return ",";
167
+ default:
168
+ return "&";
169
+ }
170
+ };
171
+ var separatorArrayNoExplode = (style) => {
172
+ switch (style) {
173
+ case "form":
174
+ return ",";
175
+ case "pipeDelimited":
176
+ return "|";
177
+ case "spaceDelimited":
178
+ return "%20";
179
+ default:
180
+ return ",";
181
+ }
182
+ };
183
+ var separatorObjectExplode = (style) => {
184
+ switch (style) {
185
+ case "label":
186
+ return ".";
187
+ case "matrix":
188
+ return ";";
189
+ case "simple":
190
+ return ",";
191
+ default:
192
+ return "&";
193
+ }
194
+ };
195
+ var serializeArrayParam = ({
196
+ allowReserved,
197
+ explode,
198
+ name,
199
+ style,
200
+ value
201
+ }) => {
202
+ if (!explode) {
203
+ const joinedValues2 = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
204
+ switch (style) {
205
+ case "label":
206
+ return `.${joinedValues2}`;
207
+ case "matrix":
208
+ return `;${name}=${joinedValues2}`;
209
+ case "simple":
210
+ return joinedValues2;
211
+ default:
212
+ return `${name}=${joinedValues2}`;
213
+ }
214
+ }
215
+ const separator = separatorArrayExplode(style);
216
+ const joinedValues = value.map((v) => {
217
+ if (style === "label" || style === "simple") {
218
+ return allowReserved ? v : encodeURIComponent(v);
219
+ }
220
+ return serializePrimitiveParam({
221
+ allowReserved,
222
+ name,
223
+ value: v
224
+ });
225
+ }).join(separator);
226
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
227
+ };
228
+ var serializePrimitiveParam = ({
229
+ allowReserved,
230
+ name,
231
+ value
232
+ }) => {
233
+ if (value === void 0 || value === null) {
234
+ return "";
235
+ }
236
+ if (typeof value === "object") {
237
+ throw new Error(
238
+ "Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these."
239
+ );
240
+ }
241
+ return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
242
+ };
243
+ var serializeObjectParam = ({
244
+ allowReserved,
245
+ explode,
246
+ name,
247
+ style,
248
+ value,
249
+ valueOnly
250
+ }) => {
251
+ if (value instanceof Date) {
252
+ return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
253
+ }
254
+ if (style !== "deepObject" && !explode) {
255
+ let values = [];
256
+ Object.entries(value).forEach(([key, v]) => {
257
+ values = [
258
+ ...values,
259
+ key,
260
+ allowReserved ? v : encodeURIComponent(v)
261
+ ];
262
+ });
263
+ const joinedValues2 = values.join(",");
264
+ switch (style) {
265
+ case "form":
266
+ return `${name}=${joinedValues2}`;
267
+ case "label":
268
+ return `.${joinedValues2}`;
269
+ case "matrix":
270
+ return `;${name}=${joinedValues2}`;
271
+ default:
272
+ return joinedValues2;
273
+ }
274
+ }
275
+ const separator = separatorObjectExplode(style);
276
+ const joinedValues = Object.entries(value).map(
277
+ ([key, v]) => serializePrimitiveParam({
278
+ allowReserved,
279
+ name: style === "deepObject" ? `${name}[${key}]` : key,
280
+ value: v
281
+ })
282
+ ).join(separator);
283
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
284
+ };
285
+
286
+ // src/client/core/utils.gen.ts
287
+ function getValidRequestBody(options) {
288
+ const hasBody = options.body !== void 0;
289
+ const isSerializedBody = hasBody && options.bodySerializer;
290
+ if (isSerializedBody) {
291
+ if ("serializedBody" in options) {
292
+ const hasSerializedBody = options.serializedBody !== void 0 && options.serializedBody !== "";
293
+ return hasSerializedBody ? options.serializedBody : null;
294
+ }
295
+ return options.body !== "" ? options.body : null;
296
+ }
297
+ if (hasBody) {
298
+ return options.body;
299
+ }
300
+ return void 0;
301
+ }
302
+
303
+ // src/client/core/auth.gen.ts
304
+ var getAuthToken = async (auth, callback) => {
305
+ const token = typeof callback === "function" ? await callback(auth) : callback;
306
+ if (!token) {
307
+ return;
308
+ }
309
+ if (auth.scheme === "bearer") {
310
+ return `Bearer ${token}`;
311
+ }
312
+ if (auth.scheme === "basic") {
313
+ return `Basic ${btoa(token)}`;
314
+ }
315
+ return token;
316
+ };
317
+
318
+ // src/client/client/utils.gen.ts
319
+ var PATH_PARAM_RE = /\{[^{}]+\}/g;
320
+ var defaultPathSerializer = ({ path, url: _url }) => {
321
+ let url = _url;
322
+ const matches = _url.match(PATH_PARAM_RE);
323
+ if (matches) {
324
+ for (const match of matches) {
325
+ let explode = false;
326
+ let name = match.substring(1, match.length - 1);
327
+ let style = "simple";
328
+ if (name.endsWith("*")) {
329
+ explode = true;
330
+ name = name.substring(0, name.length - 1);
331
+ }
332
+ if (name.startsWith(".")) {
333
+ name = name.substring(1);
334
+ style = "label";
335
+ } else if (name.startsWith(";")) {
336
+ name = name.substring(1);
337
+ style = "matrix";
338
+ }
339
+ const value = path[name];
340
+ if (value === void 0 || value === null) {
341
+ continue;
342
+ }
343
+ if (Array.isArray(value)) {
344
+ url = url.replace(
345
+ match,
346
+ serializeArrayParam({ explode, name, style, value })
347
+ );
348
+ continue;
349
+ }
350
+ if (typeof value === "object") {
351
+ url = url.replace(
352
+ match,
353
+ serializeObjectParam({
354
+ explode,
355
+ name,
356
+ style,
357
+ value,
358
+ valueOnly: true
359
+ })
360
+ );
361
+ continue;
362
+ }
363
+ if (style === "matrix") {
364
+ url = url.replace(
365
+ match,
366
+ `;${serializePrimitiveParam({
367
+ name,
368
+ value
369
+ })}`
370
+ );
371
+ continue;
372
+ }
373
+ const replaceValue = encodeURIComponent(
374
+ style === "label" ? `.${value}` : value
375
+ );
376
+ url = url.replace(match, replaceValue);
377
+ }
378
+ }
379
+ return url;
380
+ };
381
+ var createQuerySerializer = ({
382
+ parameters = {},
383
+ ...args
384
+ } = {}) => {
385
+ const querySerializer = (queryParams) => {
386
+ const search = [];
387
+ if (queryParams && typeof queryParams === "object") {
388
+ for (const name in queryParams) {
389
+ const value = queryParams[name];
390
+ if (value === void 0 || value === null) {
391
+ continue;
392
+ }
393
+ const options = parameters[name] || args;
394
+ if (Array.isArray(value)) {
395
+ const serializedArray = serializeArrayParam({
396
+ allowReserved: options.allowReserved,
397
+ explode: true,
398
+ name,
399
+ style: "form",
400
+ value,
401
+ ...options.array
402
+ });
403
+ if (serializedArray) search.push(serializedArray);
404
+ } else if (typeof value === "object") {
405
+ const serializedObject = serializeObjectParam({
406
+ allowReserved: options.allowReserved,
407
+ explode: true,
408
+ name,
409
+ style: "deepObject",
410
+ value,
411
+ ...options.object
412
+ });
413
+ if (serializedObject) search.push(serializedObject);
414
+ } else {
415
+ const serializedPrimitive = serializePrimitiveParam({
416
+ allowReserved: options.allowReserved,
417
+ name,
418
+ value
419
+ });
420
+ if (serializedPrimitive) search.push(serializedPrimitive);
421
+ }
422
+ }
423
+ }
424
+ return search.join("&");
425
+ };
426
+ return querySerializer;
427
+ };
428
+ var getParseAs = (contentType) => {
429
+ if (!contentType) {
430
+ return "stream";
431
+ }
432
+ const cleanContent = contentType.split(";")[0]?.trim();
433
+ if (!cleanContent) {
434
+ return;
435
+ }
436
+ if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) {
437
+ return "json";
438
+ }
439
+ if (cleanContent === "multipart/form-data") {
440
+ return "formData";
441
+ }
442
+ if (["application/", "audio/", "image/", "video/"].some(
443
+ (type) => cleanContent.startsWith(type)
444
+ )) {
445
+ return "blob";
446
+ }
447
+ if (cleanContent.startsWith("text/")) {
448
+ return "text";
449
+ }
450
+ return;
451
+ };
452
+ var checkForExistence = (options, name) => {
453
+ if (!name) {
454
+ return false;
455
+ }
456
+ if (options.headers.has(name) || options.query?.[name] || options.headers.get("Cookie")?.includes(`${name}=`)) {
457
+ return true;
458
+ }
459
+ return false;
460
+ };
461
+ var setAuthParams = async ({
462
+ security,
463
+ ...options
464
+ }) => {
465
+ for (const auth of security) {
466
+ if (checkForExistence(options, auth.name)) {
467
+ continue;
468
+ }
469
+ const token = await getAuthToken(auth, options.auth);
470
+ if (!token) {
471
+ continue;
472
+ }
473
+ const name = auth.name ?? "Authorization";
474
+ switch (auth.in) {
475
+ case "query":
476
+ if (!options.query) {
477
+ options.query = {};
478
+ }
479
+ options.query[name] = token;
480
+ break;
481
+ case "cookie":
482
+ options.headers.append("Cookie", `${name}=${token}`);
483
+ break;
484
+ case "header":
485
+ default:
486
+ options.headers.set(name, token);
487
+ break;
488
+ }
489
+ }
490
+ };
491
+ var buildUrl = (options) => {
492
+ const url = getUrl({
493
+ baseUrl: options.baseUrl,
494
+ path: options.path,
495
+ query: options.query,
496
+ querySerializer: typeof options.querySerializer === "function" ? options.querySerializer : createQuerySerializer(options.querySerializer),
497
+ url: options.url
498
+ });
499
+ return url;
500
+ };
501
+ var getUrl = ({
502
+ baseUrl,
503
+ path,
504
+ query,
505
+ querySerializer,
506
+ url: _url
507
+ }) => {
508
+ const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
509
+ let url = (baseUrl ?? "") + pathUrl;
510
+ if (path) {
511
+ url = defaultPathSerializer({ path, url });
512
+ }
513
+ let search = query ? querySerializer(query) : "";
514
+ if (search.startsWith("?")) {
515
+ search = search.substring(1);
516
+ }
517
+ if (search) {
518
+ url += `?${search}`;
519
+ }
520
+ return url;
521
+ };
522
+ var mergeConfigs = (a, b) => {
523
+ const config = { ...a, ...b };
524
+ if (config.baseUrl?.endsWith("/")) {
525
+ config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
526
+ }
527
+ config.headers = mergeHeaders(a.headers, b.headers);
528
+ return config;
529
+ };
530
+ var headersEntries = (headers) => {
531
+ const entries = [];
532
+ headers.forEach((value, key) => {
533
+ entries.push([key, value]);
534
+ });
535
+ return entries;
536
+ };
537
+ var mergeHeaders = (...headers) => {
538
+ const mergedHeaders = new Headers();
539
+ for (const header of headers) {
540
+ if (!header || typeof header !== "object") {
541
+ continue;
542
+ }
543
+ const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
544
+ for (const [key, value] of iterator) {
545
+ if (value === null) {
546
+ mergedHeaders.delete(key);
547
+ } else if (Array.isArray(value)) {
548
+ for (const v of value) {
549
+ mergedHeaders.append(key, v);
550
+ }
551
+ } else if (value !== void 0) {
552
+ mergedHeaders.set(
553
+ key,
554
+ typeof value === "object" ? JSON.stringify(value) : value
555
+ );
556
+ }
557
+ }
558
+ }
559
+ return mergedHeaders;
560
+ };
561
+ var Interceptors = class {
562
+ constructor() {
563
+ this.fns = [];
564
+ }
565
+ clear() {
566
+ this.fns = [];
567
+ }
568
+ eject(id) {
569
+ const index = this.getInterceptorIndex(id);
570
+ if (this.fns[index]) {
571
+ this.fns[index] = null;
572
+ }
573
+ }
574
+ exists(id) {
575
+ const index = this.getInterceptorIndex(id);
576
+ return Boolean(this.fns[index]);
577
+ }
578
+ getInterceptorIndex(id) {
579
+ if (typeof id === "number") {
580
+ return this.fns[id] ? id : -1;
581
+ }
582
+ return this.fns.indexOf(id);
583
+ }
584
+ update(id, fn) {
585
+ const index = this.getInterceptorIndex(id);
586
+ if (this.fns[index]) {
587
+ this.fns[index] = fn;
588
+ return id;
589
+ }
590
+ return false;
591
+ }
592
+ use(fn) {
593
+ this.fns.push(fn);
594
+ return this.fns.length - 1;
595
+ }
596
+ };
597
+ var createInterceptors = () => ({
598
+ error: new Interceptors(),
599
+ request: new Interceptors(),
600
+ response: new Interceptors()
601
+ });
602
+ var defaultQuerySerializer = createQuerySerializer({
603
+ allowReserved: false,
604
+ array: {
605
+ explode: true,
606
+ style: "form"
607
+ },
608
+ object: {
609
+ explode: true,
610
+ style: "deepObject"
611
+ }
612
+ });
613
+ var defaultHeaders = {
614
+ "Content-Type": "application/json"
615
+ };
616
+ var createConfig = (override = {}) => ({
617
+ ...jsonBodySerializer,
618
+ headers: defaultHeaders,
619
+ parseAs: "auto",
620
+ querySerializer: defaultQuerySerializer,
621
+ ...override
622
+ });
623
+
624
+ // src/client/client/client.gen.ts
625
+ var createClient = (config = {}) => {
626
+ let _config = mergeConfigs(createConfig(), config);
627
+ const getConfig = () => ({ ..._config });
628
+ const setConfig = (config2) => {
629
+ _config = mergeConfigs(_config, config2);
630
+ return getConfig();
631
+ };
632
+ const interceptors = createInterceptors();
633
+ const beforeRequest = async (options) => {
634
+ const opts = {
635
+ ..._config,
636
+ ...options,
637
+ fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
638
+ headers: mergeHeaders(_config.headers, options.headers),
639
+ serializedBody: void 0
640
+ };
641
+ if (opts.security) {
642
+ await setAuthParams({
643
+ ...opts,
644
+ security: opts.security
645
+ });
646
+ }
647
+ if (opts.requestValidator) {
648
+ await opts.requestValidator(opts);
649
+ }
650
+ if (opts.body !== void 0 && opts.bodySerializer) {
651
+ opts.serializedBody = opts.bodySerializer(opts.body);
652
+ }
653
+ if (opts.body === void 0 || opts.serializedBody === "") {
654
+ opts.headers.delete("Content-Type");
655
+ }
656
+ const url = buildUrl(opts);
657
+ return { opts, url };
658
+ };
659
+ const request = async (options) => {
660
+ const { opts, url } = await beforeRequest(options);
661
+ for (const fn of interceptors.request.fns) {
662
+ if (fn) {
663
+ await fn(opts);
664
+ }
665
+ }
666
+ const _fetch = opts.fetch;
667
+ const requestInit = {
668
+ ...opts,
669
+ body: getValidRequestBody(opts)
670
+ };
671
+ let response = await _fetch(url, requestInit);
672
+ for (const fn of interceptors.response.fns) {
673
+ if (fn) {
674
+ response = await fn(response, opts);
675
+ }
676
+ }
677
+ const result = {
678
+ response
679
+ };
680
+ if (response.ok) {
681
+ const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json";
682
+ if (response.status === 204 || response.headers.get("Content-Length") === "0") {
683
+ let emptyData;
684
+ switch (parseAs) {
685
+ case "arrayBuffer":
686
+ case "blob":
687
+ case "text":
688
+ emptyData = await response[parseAs]();
689
+ break;
690
+ case "formData":
691
+ emptyData = new FormData();
692
+ break;
693
+ case "stream":
694
+ emptyData = response.body;
695
+ break;
696
+ case "json":
697
+ default:
698
+ emptyData = {};
699
+ break;
700
+ }
701
+ return {
702
+ data: emptyData,
703
+ ...result
704
+ };
705
+ }
706
+ let data;
707
+ switch (parseAs) {
708
+ case "arrayBuffer":
709
+ case "blob":
710
+ case "formData":
711
+ case "json":
712
+ case "text":
713
+ data = await response[parseAs]();
714
+ break;
715
+ case "stream":
716
+ return {
717
+ data: response.body,
718
+ ...result
719
+ };
720
+ }
721
+ if (parseAs === "json") {
722
+ if (opts.responseValidator) {
723
+ await opts.responseValidator(data);
724
+ }
725
+ if (opts.responseTransformer) {
726
+ data = await opts.responseTransformer(data);
727
+ }
728
+ }
729
+ return {
730
+ data,
731
+ ...result
732
+ };
733
+ }
734
+ const textError = await response.text();
735
+ let jsonError;
736
+ try {
737
+ jsonError = JSON.parse(textError);
738
+ } catch {
739
+ }
740
+ const error = jsonError ?? textError;
741
+ let finalError = error;
742
+ for (const fn of interceptors.error.fns) {
743
+ if (fn) {
744
+ finalError = await fn(error, response, opts);
745
+ }
746
+ }
747
+ finalError = finalError || {};
748
+ if (opts.throwOnError) {
749
+ throw finalError;
750
+ }
751
+ return {
752
+ error: finalError,
753
+ ...result
754
+ };
755
+ };
756
+ const makeMethodFn = (method) => (options) => request({ ...options, method });
757
+ const makeSseFn = (method) => async (options) => {
758
+ const { opts, url } = await beforeRequest(options);
759
+ return createSseClient({
760
+ ...opts,
761
+ body: opts.body,
762
+ headers: opts.headers,
763
+ method,
764
+ onRequest: async (url2, init) => {
765
+ let request2 = new Request(url2, init);
766
+ const requestInit = {
767
+ ...init,
768
+ method: init.method,
769
+ url: url2
770
+ };
771
+ for (const fn of interceptors.request.fns) {
772
+ if (fn) {
773
+ await fn(requestInit);
774
+ request2 = new Request(requestInit.url, requestInit);
775
+ }
776
+ }
777
+ return request2;
778
+ },
779
+ url
780
+ });
781
+ };
782
+ return {
783
+ buildUrl,
784
+ connect: makeMethodFn("CONNECT"),
785
+ delete: makeMethodFn("DELETE"),
786
+ get: makeMethodFn("GET"),
787
+ getConfig,
788
+ head: makeMethodFn("HEAD"),
789
+ interceptors,
790
+ options: makeMethodFn("OPTIONS"),
791
+ patch: makeMethodFn("PATCH"),
792
+ post: makeMethodFn("POST"),
793
+ put: makeMethodFn("PUT"),
794
+ request,
795
+ setConfig,
796
+ sse: {
797
+ connect: makeSseFn("CONNECT"),
798
+ delete: makeSseFn("DELETE"),
799
+ get: makeSseFn("GET"),
800
+ head: makeSseFn("HEAD"),
801
+ options: makeSseFn("OPTIONS"),
802
+ patch: makeSseFn("PATCH"),
803
+ post: makeSseFn("POST"),
804
+ put: makeSseFn("PUT"),
805
+ trace: makeSseFn("TRACE")
806
+ },
807
+ trace: makeMethodFn("TRACE")
808
+ };
809
+ };
810
+
811
+ // src/client/client.gen.ts
812
+ var client = createClient(createClientConfig(createConfig()));
813
+
814
+ // src/client/sdk.gen.ts
815
+ var postApiV1AdminAddCredits = (options) => {
816
+ return (options.client ?? client).post({
817
+ url: "/api/v1/admin/add-credits",
818
+ ...options,
819
+ headers: {
820
+ "Content-Type": "application/json",
821
+ ...options.headers
822
+ }
823
+ });
824
+ };
825
+ var getApiV1AdminApps = (options) => {
826
+ return (options.client ?? client).get({
827
+ url: "/api/v1/admin/apps",
828
+ ...options
829
+ });
830
+ };
831
+ var postApiV1AdminApps = (options) => {
832
+ return (options.client ?? client).post({
833
+ url: "/api/v1/admin/apps",
834
+ ...options,
835
+ headers: {
836
+ "Content-Type": "application/json",
837
+ ...options.headers
838
+ }
839
+ });
840
+ };
841
+ var getApiV1AdminAppsByAppIdApiKeys = (options) => {
842
+ return (options.client ?? client).get({
843
+ url: "/api/v1/admin/apps/{app_id}/api-keys",
844
+ ...options
845
+ });
846
+ };
847
+ var postApiV1AdminAppsByAppIdApiKeys = (options) => {
848
+ return (options.client ?? client).post({
849
+ url: "/api/v1/admin/apps/{app_id}/api-keys",
850
+ ...options,
851
+ headers: {
852
+ "Content-Type": "application/json",
853
+ ...options.headers
854
+ }
855
+ });
856
+ };
857
+ var deleteApiV1AdminAppsByAppIdApiKeysById = (options) => {
858
+ return (options.client ?? client).delete({
859
+ url: "/api/v1/admin/apps/{app_id}/api-keys/{id}",
860
+ ...options
861
+ });
862
+ };
863
+ var getApiV1AdminAppsByAppIdApiKeysById = (options) => {
864
+ return (options.client ?? client).get({
865
+ url: "/api/v1/admin/apps/{app_id}/api-keys/{id}",
866
+ ...options
867
+ });
868
+ };
869
+ var putApiV1AdminAppsByAppIdApiKeysById = (options) => {
870
+ return (options.client ?? client).put({
871
+ url: "/api/v1/admin/apps/{app_id}/api-keys/{id}",
872
+ ...options,
873
+ headers: {
874
+ "Content-Type": "application/json",
875
+ ...options.headers
876
+ }
877
+ });
878
+ };
879
+ var deleteApiV1AdminAppsById = (options) => {
880
+ return (options.client ?? client).delete({
881
+ url: "/api/v1/admin/apps/{id}",
882
+ ...options
883
+ });
884
+ };
885
+ var getApiV1AdminAppsById = (options) => {
886
+ return (options.client ?? client).get({
887
+ url: "/api/v1/admin/apps/{id}",
888
+ ...options
889
+ });
890
+ };
891
+ var putApiV1AdminAppsById = (options) => {
892
+ return (options.client ?? client).put({
893
+ url: "/api/v1/admin/apps/{id}",
894
+ ...options,
895
+ headers: {
896
+ "Content-Type": "application/json",
897
+ ...options.headers
898
+ }
899
+ });
900
+ };
901
+ var postApiV1AdminSeedApps = (options) => {
902
+ return (options.client ?? client).post({
903
+ url: "/api/v1/admin/seed-apps",
904
+ ...options,
905
+ headers: {
906
+ "Content-Type": "application/json",
907
+ ...options.headers
908
+ }
909
+ });
910
+ };
911
+ var postApiV1AdminSubscriptionTier = (options) => {
912
+ return (options.client ?? client).post({
913
+ url: "/api/v1/admin/subscription-tier",
914
+ ...options,
915
+ headers: {
916
+ "Content-Type": "application/json",
917
+ ...options.headers
918
+ }
919
+ });
920
+ };
921
+ var postApiV1ChatCompletions = (options) => {
922
+ return (options.client ?? client).post({
923
+ url: "/api/v1/chat/completions",
924
+ ...options,
925
+ headers: {
926
+ "Content-Type": "application/json",
927
+ ...options.headers
928
+ }
929
+ });
930
+ };
931
+ var getApiV1Config = (options) => {
932
+ return (options?.client ?? client).get({
933
+ url: "/api/v1/config",
934
+ ...options
935
+ });
936
+ };
937
+ var getApiV1CreditsBalance = (options) => {
938
+ return (options?.client ?? client).get({
939
+ url: "/api/v1/credits/balance",
940
+ ...options
941
+ });
942
+ };
943
+ var postApiV1CreditsClaimDaily = (options) => {
944
+ return (options?.client ?? client).post({
945
+ url: "/api/v1/credits/claim-daily",
946
+ ...options
947
+ });
948
+ };
949
+ var getApiV1CreditsPacks = (options) => {
950
+ return (options?.client ?? client).get({
951
+ url: "/api/v1/credits/packs",
952
+ ...options
953
+ });
954
+ };
955
+ var postApiV1CreditsPurchase = (options) => {
956
+ return (options.client ?? client).post({
957
+ url: "/api/v1/credits/purchase",
958
+ ...options,
959
+ headers: {
960
+ "Content-Type": "application/json",
961
+ ...options.headers
962
+ }
963
+ });
964
+ };
965
+ var postApiV1CreditsSyncSnag = (options) => {
966
+ return (options?.client ?? client).post({
967
+ url: "/api/v1/credits/sync-snag",
968
+ ...options
969
+ });
970
+ };
971
+ var getApiV1DocsSwaggerJson = (options) => {
972
+ return (options?.client ?? client).get({
973
+ url: "/api/v1/docs/swagger.json",
974
+ ...options
975
+ });
976
+ };
977
+ var postApiV1Embeddings = (options) => {
978
+ return (options.client ?? client).post({
979
+ url: "/api/v1/embeddings",
980
+ ...options,
981
+ headers: {
982
+ "Content-Type": "application/json",
983
+ ...options.headers
984
+ }
985
+ });
986
+ };
987
+ var getApiV1Models = (options) => {
988
+ return (options?.client ?? client).get({
989
+ url: "/api/v1/models",
990
+ ...options
991
+ });
992
+ };
993
+ var postApiV1Responses = (options) => {
994
+ return (options.client ?? client).post({
995
+ url: "/api/v1/responses",
996
+ ...options,
997
+ headers: {
998
+ "Content-Type": "application/json",
999
+ ...options.headers
1000
+ }
1001
+ });
1002
+ };
1003
+ var postApiV1SubscriptionsCancel = (options) => {
1004
+ return (options?.client ?? client).post({
1005
+ url: "/api/v1/subscriptions/cancel",
1006
+ ...options
1007
+ });
1008
+ };
1009
+ var postApiV1SubscriptionsCreateCheckoutSession = (options) => {
1010
+ return (options.client ?? client).post({
1011
+ url: "/api/v1/subscriptions/create-checkout-session",
1012
+ ...options,
1013
+ headers: {
1014
+ "Content-Type": "application/json",
1015
+ ...options.headers
1016
+ }
1017
+ });
1018
+ };
1019
+ var postApiV1SubscriptionsCustomerPortal = (options) => {
1020
+ return (options.client ?? client).post({
1021
+ url: "/api/v1/subscriptions/customer-portal",
1022
+ ...options,
1023
+ headers: {
1024
+ "Content-Type": "application/json",
1025
+ ...options.headers
1026
+ }
1027
+ });
1028
+ };
1029
+ var getApiV1SubscriptionsPlans = (options) => {
1030
+ return (options?.client ?? client).get({
1031
+ url: "/api/v1/subscriptions/plans",
1032
+ ...options
1033
+ });
1034
+ };
1035
+ var postApiV1SubscriptionsRenew = (options) => {
1036
+ return (options?.client ?? client).post({
1037
+ url: "/api/v1/subscriptions/renew",
1038
+ ...options
1039
+ });
1040
+ };
1041
+ var getApiV1SubscriptionsStatus = (options) => {
1042
+ return (options?.client ?? client).get({
1043
+ url: "/api/v1/subscriptions/status",
1044
+ ...options
1045
+ });
1046
+ };
1047
+ var postApiV1SubscriptionsWebhook = (options) => {
1048
+ return (options.client ?? client).post({
1049
+ url: "/api/v1/subscriptions/webhook",
1050
+ ...options,
1051
+ headers: {
1052
+ "Content-Type": "application/json",
1053
+ ...options.headers
1054
+ }
1055
+ });
1056
+ };
1057
+ var getApiV1Tasks = (options) => {
1058
+ return (options?.client ?? client).get({
1059
+ url: "/api/v1/tasks",
1060
+ ...options
1061
+ });
1062
+ };
1063
+ var getApiV1Tools = (options) => {
1064
+ return (options?.client ?? client).get({
1065
+ url: "/api/v1/tools",
1066
+ ...options
1067
+ });
1068
+ };
1069
+ var postAuthOauthByProviderExchange = (options) => {
1070
+ return (options.client ?? client).post({
1071
+ url: "/auth/oauth/{provider}/exchange",
1072
+ ...options,
1073
+ headers: {
1074
+ "Content-Type": "application/json",
1075
+ ...options.headers
1076
+ }
1077
+ });
1078
+ };
1079
+ var postAuthOauthByProviderRefresh = (options) => {
1080
+ return (options.client ?? client).post({
1081
+ url: "/auth/oauth/{provider}/refresh",
1082
+ ...options,
1083
+ headers: {
1084
+ "Content-Type": "application/json",
1085
+ ...options.headers
1086
+ }
1087
+ });
1088
+ };
1089
+ var postAuthOauthByProviderRevoke = (options) => {
1090
+ return (options.client ?? client).post({
1091
+ url: "/auth/oauth/{provider}/revoke",
1092
+ ...options,
1093
+ headers: {
1094
+ "Content-Type": "application/json",
1095
+ ...options.headers
1096
+ }
1097
+ });
1098
+ };
1099
+ var getHealth = (options) => {
1100
+ return (options?.client ?? client).get({
1101
+ url: "/health",
1102
+ ...options
1103
+ });
1104
+ };
1105
+
1106
+ // src/lib/memoryRetrieval/chunking.ts
1107
+ var DEFAULT_CHUNK_SIZE = 400;
1108
+ var DEFAULT_CHUNK_OVERLAP = 50;
1109
+ var DEFAULT_MIN_CHUNK_SIZE = 50;
1110
+ function splitIntoSentences(text) {
1111
+ const sentenceRegex = /[.!?]+[\s"')}\]]*(?=\s|$)/g;
1112
+ const sentences = [];
1113
+ let lastIndex = 0;
1114
+ let match;
1115
+ while ((match = sentenceRegex.exec(text)) !== null) {
1116
+ const endIndex = match.index + match[0].length;
1117
+ const sentence = text.slice(lastIndex, endIndex).trim();
1118
+ if (sentence) {
1119
+ sentences.push(sentence);
1120
+ }
1121
+ lastIndex = endIndex;
1122
+ }
1123
+ const remaining = text.slice(lastIndex).trim();
1124
+ if (remaining) {
1125
+ sentences.push(remaining);
1126
+ }
1127
+ return sentences;
1128
+ }
1129
+ function chunkText(text, options) {
1130
+ const {
1131
+ chunkSize = DEFAULT_CHUNK_SIZE,
1132
+ chunkOverlap: requestedOverlap = DEFAULT_CHUNK_OVERLAP,
1133
+ minChunkSize = DEFAULT_MIN_CHUNK_SIZE
1134
+ } = options ?? {};
1135
+ const chunkOverlap = Math.min(requestedOverlap, chunkSize - 1);
1136
+ if (text.length <= chunkSize) {
1137
+ return [
1138
+ {
1139
+ text: text.trim(),
1140
+ startOffset: 0,
1141
+ endOffset: text.length
1142
+ }
1143
+ ];
1144
+ }
1145
+ const sentences = splitIntoSentences(text);
1146
+ const chunks = [];
1147
+ let currentChunkSentences = [];
1148
+ let currentChunkStart = 0;
1149
+ let currentOffset = 0;
1150
+ for (let i = 0; i < sentences.length; i++) {
1151
+ const sentence = sentences[i];
1152
+ let sentenceStart = text.indexOf(sentence, currentOffset);
1153
+ if (sentenceStart === -1) {
1154
+ sentenceStart = currentOffset;
1155
+ }
1156
+ const sentenceEnd = sentenceStart + sentence.length;
1157
+ if (sentence.length > chunkSize) {
1158
+ if (currentChunkSentences.length > 0) {
1159
+ const chunkText2 = currentChunkSentences.join(" ");
1160
+ chunks.push({
1161
+ text: chunkText2,
1162
+ startOffset: currentChunkStart,
1163
+ endOffset: currentOffset
1164
+ });
1165
+ currentChunkSentences = [];
1166
+ }
1167
+ for (let j = 0; j < sentence.length; j += chunkSize - chunkOverlap) {
1168
+ const chunkEnd = Math.min(j + chunkSize, sentence.length);
1169
+ const chunk = sentence.slice(j, chunkEnd);
1170
+ if (chunk.length >= minChunkSize) {
1171
+ chunks.push({
1172
+ text: chunk,
1173
+ startOffset: sentenceStart + j,
1174
+ endOffset: sentenceStart + chunkEnd
1175
+ });
1176
+ }
1177
+ }
1178
+ currentChunkStart = sentenceEnd;
1179
+ currentOffset = sentenceEnd;
1180
+ continue;
1181
+ }
1182
+ const currentText = currentChunkSentences.join(" ");
1183
+ const potentialLength = currentText.length + (currentText ? 1 : 0) + sentence.length;
1184
+ if (potentialLength > chunkSize && currentChunkSentences.length > 0) {
1185
+ chunks.push({
1186
+ text: currentText,
1187
+ startOffset: currentChunkStart,
1188
+ endOffset: currentOffset
1189
+ });
1190
+ const overlapSentences = [];
1191
+ let overlapLength = 0;
1192
+ for (let j = currentChunkSentences.length - 1; j >= 0 && overlapLength < chunkOverlap; j--) {
1193
+ overlapSentences.unshift(currentChunkSentences[j]);
1194
+ overlapLength += currentChunkSentences[j].length + 1;
1195
+ }
1196
+ if (overlapSentences.length > 0) {
1197
+ currentChunkSentences = [...overlapSentences, sentence];
1198
+ const overlapText = overlapSentences[0];
1199
+ const overlapStart = text.lastIndexOf(overlapText, currentOffset);
1200
+ currentChunkStart = overlapStart === -1 ? sentenceStart : overlapStart;
1201
+ } else {
1202
+ currentChunkSentences = [sentence];
1203
+ currentChunkStart = sentenceStart;
1204
+ }
1205
+ } else {
1206
+ if (currentChunkSentences.length === 0) {
1207
+ currentChunkStart = sentenceStart;
1208
+ }
1209
+ currentChunkSentences.push(sentence);
1210
+ }
1211
+ currentOffset = sentenceEnd;
1212
+ }
1213
+ if (currentChunkSentences.length > 0) {
1214
+ const chunkText2 = currentChunkSentences.join(" ");
1215
+ if (chunkText2.length >= minChunkSize) {
1216
+ chunks.push({
1217
+ text: chunkText2,
1218
+ startOffset: currentChunkStart,
1219
+ endOffset: text.length
1220
+ });
1221
+ }
1222
+ }
1223
+ if (chunks.length === 0) {
1224
+ const trimmedText = text.trim();
1225
+ if (trimmedText.length > 0) {
1226
+ return [
1227
+ {
1228
+ text: trimmedText,
1229
+ startOffset: 0,
1230
+ endOffset: text.length
1231
+ }
1232
+ ];
1233
+ }
1234
+ }
1235
+ return chunks;
1236
+ }
1237
+ function shouldChunkMessage(content, chunkSize = DEFAULT_CHUNK_SIZE) {
1238
+ return content.length > chunkSize;
1239
+ }
1240
+
1241
+ // src/lib/db/chat/operations.ts
1242
+ import { Q } from "@nozbe/watermelondb";
1243
+ import { v7 as uuidv72 } from "uuid";
1244
+
1245
+ // src/lib/db/chat/types.ts
1246
+ import { v7 as uuidv7 } from "uuid";
1247
+
1248
+ // src/lib/memoryRetrieval/constants.ts
1249
+ var DEFAULT_API_EMBEDDING_MODEL = "fireworks/accounts/fireworks/models/qwen3-embedding-8b";
1250
+
1251
+ // src/lib/memoryRetrieval/embeddings.ts
1252
+ async function generateEmbedding(text, options) {
1253
+ const { baseUrl = BASE_URL, getToken, apiKey, model } = options;
1254
+ let headers;
1255
+ if (apiKey) {
1256
+ headers = { "X-API-Key": apiKey };
1257
+ } else if (getToken) {
1258
+ const token = await getToken();
1259
+ if (!token) {
1260
+ throw new Error("No token available for embedding generation");
1261
+ }
1262
+ headers = { Authorization: `Bearer ${token}` };
1263
+ } else {
1264
+ throw new Error("Either apiKey or getToken must be provided");
1265
+ }
1266
+ const response = await postApiV1Embeddings({
1267
+ baseUrl,
1268
+ body: {
1269
+ input: text,
1270
+ model: model ?? DEFAULT_API_EMBEDDING_MODEL
1271
+ },
1272
+ headers
1273
+ });
1274
+ if (response.error) {
1275
+ throw new Error(
1276
+ typeof response.error === "object" && response.error && "error" in response.error ? response.error.error : "API embedding failed"
1277
+ );
1278
+ }
1279
+ if (!response.data?.data?.[0]?.embedding) {
1280
+ throw new Error("No embedding returned from API");
1281
+ }
1282
+ return response.data.data[0].embedding;
1283
+ }
1284
+ async function generateEmbeddings(texts, options) {
1285
+ if (texts.length === 0) return [];
1286
+ const { baseUrl = BASE_URL, getToken, apiKey, model } = options;
1287
+ let headers;
1288
+ if (apiKey) {
1289
+ headers = { "X-API-Key": apiKey };
1290
+ } else if (getToken) {
1291
+ const token = await getToken();
1292
+ if (!token) {
1293
+ throw new Error("No token available for embedding generation");
1294
+ }
1295
+ headers = { Authorization: `Bearer ${token}` };
1296
+ } else {
1297
+ throw new Error("Either apiKey or getToken must be provided");
1298
+ }
1299
+ const response = await postApiV1Embeddings({
1300
+ baseUrl,
1301
+ body: {
1302
+ input: texts,
1303
+ model: model ?? DEFAULT_API_EMBEDDING_MODEL
1304
+ },
1305
+ headers
1306
+ });
1307
+ if (response.error) {
1308
+ throw new Error(
1309
+ typeof response.error === "object" && response.error && "error" in response.error ? response.error.error : "API embedding failed"
1310
+ );
1311
+ }
1312
+ if (!response.data?.data) {
1313
+ throw new Error("No embeddings returned from API");
1314
+ }
1315
+ return response.data.data.map((item) => item.embedding ?? []);
1316
+ }
1317
+
1318
+ // src/lib/tools/serverTools.ts
1319
+ var DEFAULT_CACHE_EXPIRATION_MS = 24 * 60 * 60 * 1e3;
1320
+ var SERVER_TOOLS_CACHE_KEY = "sdk_server_tools_cache";
1321
+ var CACHE_VERSION = "1.3";
1322
+ var MIN_CONTENT_LENGTH_FOR_TOOLS = 5;
1323
+ function isNewToolFormat(tool) {
1324
+ return "schema" in tool && tool.schema !== void 0;
1325
+ }
1326
+ function isNewResponseFormat(response) {
1327
+ return "checksum" in response && "tools" in response && typeof response.checksum === "string";
1328
+ }
1329
+ function convertServerToolsResponse(response) {
1330
+ let toolsMap;
1331
+ let checksum;
1332
+ if (isNewResponseFormat(response)) {
1333
+ toolsMap = response.tools;
1334
+ checksum = response.checksum;
1335
+ } else {
1336
+ toolsMap = response;
1337
+ }
1338
+ const tools = Object.values(toolsMap).map((tool) => {
1339
+ if (isNewToolFormat(tool)) {
1340
+ return {
1341
+ type: "function",
1342
+ name: tool.schema.name,
1343
+ description: tool.schema.description,
1344
+ parameters: tool.schema.parameters,
1345
+ ...tool.embedding && { embedding: tool.embedding }
1346
+ };
1347
+ }
1348
+ return {
1349
+ type: "function",
1350
+ name: tool.name,
1351
+ description: tool.description,
1352
+ parameters: tool.parameters
1353
+ };
1354
+ });
1355
+ return { tools, checksum };
1356
+ }
1357
+ function toCompletionsFormat(tool) {
1358
+ return {
1359
+ type: "function",
1360
+ function: {
1361
+ name: tool.name,
1362
+ description: tool.description,
1363
+ parameters: tool.parameters
1364
+ }
1365
+ };
1366
+ }
1367
+ function toResponsesFormat(tool) {
1368
+ return {
1369
+ type: "function",
1370
+ name: tool.name,
1371
+ description: tool.description,
1372
+ parameters: tool.parameters
1373
+ };
1374
+ }
1375
+ function getCachedServerTools() {
1376
+ if (typeof window === "undefined") return null;
1377
+ try {
1378
+ const cached = localStorage.getItem(SERVER_TOOLS_CACHE_KEY);
1379
+ if (!cached) return null;
1380
+ const parsed = JSON.parse(cached);
1381
+ if (parsed.version !== CACHE_VERSION) {
1382
+ clearServerToolsCache();
1383
+ return null;
1384
+ }
1385
+ return parsed;
1386
+ } catch {
1387
+ return null;
1388
+ }
1389
+ }
1390
+ function isCacheExpired(cache, expirationMs = DEFAULT_CACHE_EXPIRATION_MS) {
1391
+ if (!cache) return true;
1392
+ return Date.now() - cache.timestamp > expirationMs;
1393
+ }
1394
+ function cacheServerTools(tools, checksum) {
1395
+ if (typeof window === "undefined") return;
1396
+ const cacheData = {
1397
+ tools,
1398
+ timestamp: Date.now(),
1399
+ version: CACHE_VERSION,
1400
+ ...checksum && { checksum }
1401
+ };
1402
+ try {
1403
+ localStorage.setItem(SERVER_TOOLS_CACHE_KEY, JSON.stringify(cacheData));
1404
+ } catch (error) {
1405
+ console.warn("[serverTools] Failed to cache tools:", error);
1406
+ }
1407
+ }
1408
+ function clearServerToolsCache() {
1409
+ if (typeof window === "undefined") return;
1410
+ localStorage.removeItem(SERVER_TOOLS_CACHE_KEY);
1411
+ }
1412
+ async function fetchServerToolsFromApi(baseUrl, token) {
1413
+ const response = await fetch(`${baseUrl}/api/v1/tools`, {
1414
+ method: "GET",
1415
+ headers: {
1416
+ Authorization: `Bearer ${token}`,
1417
+ "Content-Type": "application/json"
1418
+ }
1419
+ });
1420
+ if (!response.ok) {
1421
+ throw new Error(`Failed to fetch server tools: ${response.status}`);
1422
+ }
1423
+ const data = await response.json();
1424
+ return convertServerToolsResponse(data);
1425
+ }
1426
+ async function getServerTools(options) {
1427
+ const {
1428
+ baseUrl,
1429
+ cacheExpirationMs = DEFAULT_CACHE_EXPIRATION_MS,
1430
+ forceRefresh = false,
1431
+ getToken,
1432
+ apiKey
1433
+ } = options;
1434
+ const cached = getCachedServerTools();
1435
+ const cacheValid = !isCacheExpired(cached, cacheExpirationMs);
1436
+ if (cached && cacheValid && !forceRefresh) {
1437
+ return cached.tools;
1438
+ }
1439
+ try {
1440
+ const { BASE_URL: BASE_URL2 } = await import("./clientConfig-RMDOT5YM.mjs");
1441
+ const effectiveBaseUrl = baseUrl ?? BASE_URL2;
1442
+ if (apiKey) {
1443
+ const response = await fetch(`${effectiveBaseUrl}/api/v1/tools`, {
1444
+ method: "GET",
1445
+ headers: {
1446
+ "X-API-Key": apiKey,
1447
+ "Content-Type": "application/json"
1448
+ }
1449
+ });
1450
+ if (!response.ok) {
1451
+ throw new Error(`Failed to fetch server tools: ${response.status}`);
1452
+ }
1453
+ const data = await response.json();
1454
+ const { tools: tools2, checksum: checksum2 } = convertServerToolsResponse(data);
1455
+ cacheServerTools(tools2, checksum2);
1456
+ return tools2;
1457
+ }
1458
+ if (!getToken) {
1459
+ console.warn("[serverTools] No auth method available for fetching tools");
1460
+ return cached?.tools ?? [];
1461
+ }
1462
+ const token = await getToken();
1463
+ if (!token) {
1464
+ console.warn("[serverTools] No auth token available for fetching tools");
1465
+ return cached?.tools ?? [];
1466
+ }
1467
+ const { tools, checksum } = await fetchServerToolsFromApi(effectiveBaseUrl, token);
1468
+ cacheServerTools(tools, checksum);
1469
+ return tools;
1470
+ } catch (error) {
1471
+ console.error("[serverTools] Failed to fetch server tools:", error);
1472
+ if (cached?.tools) {
1473
+ console.warn("[serverTools] Using stale cached tools due to fetch error");
1474
+ return cached.tools;
1475
+ }
1476
+ return [];
1477
+ }
1478
+ }
1479
+ function cosineSimilarity(a, b) {
1480
+ if (a.length !== b.length) {
1481
+ throw new Error("Vectors must have the same length");
1482
+ }
1483
+ let dotProduct = 0;
1484
+ let normA = 0;
1485
+ let normB = 0;
1486
+ for (let i = 0; i < a.length; i++) {
1487
+ dotProduct += a[i] * b[i];
1488
+ normA += a[i] * a[i];
1489
+ normB += b[i] * b[i];
1490
+ }
1491
+ const denominator = Math.sqrt(normA) * Math.sqrt(normB);
1492
+ if (denominator === 0) {
1493
+ return 0;
1494
+ }
1495
+ return dotProduct / denominator;
1496
+ }
1497
+ var DEFAULT_TOOL_MATCH_OPTIONS = {
1498
+ limit: 10,
1499
+ minSimilarity: 0.3
1500
+ };
1501
+ function findMatchingTools(promptEmbeddings, tools, options) {
1502
+ const { limit, minSimilarity } = {
1503
+ ...DEFAULT_TOOL_MATCH_OPTIONS,
1504
+ ...options
1505
+ };
1506
+ if (!promptEmbeddings || promptEmbeddings.length === 0) {
1507
+ return [];
1508
+ }
1509
+ if (!tools || tools.length === 0) {
1510
+ return [];
1511
+ }
1512
+ const embeddings = Array.isArray(promptEmbeddings[0]) ? promptEmbeddings : [promptEmbeddings];
1513
+ const results = [];
1514
+ for (const tool of tools) {
1515
+ if (!tool.embedding || tool.embedding.length === 0) {
1516
+ continue;
1517
+ }
1518
+ try {
1519
+ let maxSimilarity = -Infinity;
1520
+ for (const embedding of embeddings) {
1521
+ const similarity = cosineSimilarity(embedding, tool.embedding);
1522
+ if (similarity > maxSimilarity) {
1523
+ maxSimilarity = similarity;
1524
+ }
1525
+ }
1526
+ if (maxSimilarity >= minSimilarity) {
1527
+ results.push({ tool, similarity: maxSimilarity });
1528
+ }
1529
+ } catch {
1530
+ continue;
1531
+ }
1532
+ }
1533
+ return results.sort((a, b) => b.similarity - a.similarity).slice(0, limit);
1534
+ }
1535
+ async function selectServerSideTools(options) {
1536
+ const {
1537
+ prompt,
1538
+ getToken,
1539
+ apiKey,
1540
+ baseUrl,
1541
+ cacheExpirationMs,
1542
+ forceRefresh,
1543
+ embeddingModel,
1544
+ limit,
1545
+ minSimilarity,
1546
+ apiType = "responses"
1547
+ } = options;
1548
+ if (!getToken && !apiKey) {
1549
+ throw new Error("Either getToken or apiKey must be provided");
1550
+ }
1551
+ if (!prompt || prompt.trim().length < MIN_CONTENT_LENGTH_FOR_TOOLS) {
1552
+ return [];
1553
+ }
1554
+ const tools = await getServerTools({
1555
+ getToken,
1556
+ apiKey,
1557
+ baseUrl,
1558
+ cacheExpirationMs,
1559
+ forceRefresh
1560
+ });
1561
+ if (tools.length === 0) {
1562
+ return [];
1563
+ }
1564
+ const embeddingOptions = {
1565
+ getToken,
1566
+ apiKey,
1567
+ baseUrl,
1568
+ model: embeddingModel
1569
+ };
1570
+ let promptEmbeddings;
1571
+ if (shouldChunkMessage(prompt, DEFAULT_CHUNK_SIZE)) {
1572
+ const chunks = chunkText(prompt);
1573
+ promptEmbeddings = await generateEmbeddings(
1574
+ chunks.map((c) => c.text),
1575
+ embeddingOptions
1576
+ );
1577
+ } else {
1578
+ promptEmbeddings = await generateEmbedding(prompt, embeddingOptions);
1579
+ }
1580
+ const matchOptions = {};
1581
+ if (limit !== void 0) matchOptions.limit = limit;
1582
+ if (minSimilarity !== void 0) matchOptions.minSimilarity = minSimilarity;
1583
+ const matches = findMatchingTools(promptEmbeddings, tools, matchOptions);
1584
+ if (matches.length === 0) {
1585
+ return [];
1586
+ }
1587
+ const matchedTools = matches.map((m) => m.tool);
1588
+ if (apiType === "completions") {
1589
+ return matchedTools.map((t) => toCompletionsFormat(t));
1590
+ }
1591
+ return matchedTools.map(toResponsesFormat);
1592
+ }
1593
+ export {
1594
+ deleteApiV1AdminAppsByAppIdApiKeysById,
1595
+ deleteApiV1AdminAppsById,
1596
+ getApiV1AdminApps,
1597
+ getApiV1AdminAppsByAppIdApiKeys,
1598
+ getApiV1AdminAppsByAppIdApiKeysById,
1599
+ getApiV1AdminAppsById,
1600
+ getApiV1Config,
1601
+ getApiV1CreditsBalance,
1602
+ getApiV1CreditsPacks,
1603
+ getApiV1DocsSwaggerJson,
1604
+ getApiV1Models,
1605
+ getApiV1SubscriptionsPlans,
1606
+ getApiV1SubscriptionsStatus,
1607
+ getApiV1Tasks,
1608
+ getApiV1Tools,
1609
+ getHealth,
1610
+ postApiV1AdminAddCredits,
1611
+ postApiV1AdminApps,
1612
+ postApiV1AdminAppsByAppIdApiKeys,
1613
+ postApiV1AdminSeedApps,
1614
+ postApiV1AdminSubscriptionTier,
1615
+ postApiV1ChatCompletions,
1616
+ postApiV1CreditsClaimDaily,
1617
+ postApiV1CreditsPurchase,
1618
+ postApiV1CreditsSyncSnag,
1619
+ postApiV1Embeddings,
1620
+ postApiV1Responses,
1621
+ postApiV1SubscriptionsCancel,
1622
+ postApiV1SubscriptionsCreateCheckoutSession,
1623
+ postApiV1SubscriptionsCustomerPortal,
1624
+ postApiV1SubscriptionsRenew,
1625
+ postApiV1SubscriptionsWebhook,
1626
+ postAuthOauthByProviderExchange,
1627
+ postAuthOauthByProviderRefresh,
1628
+ postAuthOauthByProviderRevoke,
1629
+ putApiV1AdminAppsByAppIdApiKeysById,
1630
+ putApiV1AdminAppsById,
1631
+ selectServerSideTools
1632
+ };