@fuserstudio/sdk 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js ADDED
@@ -0,0 +1,1453 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
2
+ //#region src/errors.ts
3
+ /** Every error the SDK throws. Subclasses say what went wrong. */
4
+ var FuserError = class extends Error {
5
+ name = "FuserError";
6
+ tool;
7
+ status;
8
+ code;
9
+ reason;
10
+ issues;
11
+ requestId;
12
+ retryAfterMs;
13
+ body;
14
+ constructor(message, details) {
15
+ super(message, { cause: details.cause });
16
+ this.tool = details.tool;
17
+ this.status = details.status;
18
+ this.code = details.code;
19
+ this.reason = details.reason;
20
+ this.issues = details.issues;
21
+ this.requestId = details.requestId;
22
+ this.retryAfterMs = details.retryAfterMs;
23
+ this.body = details.body;
24
+ }
25
+ };
26
+ var BadRequestError = class extends FuserError {
27
+ name = "BadRequestError";
28
+ };
29
+ var AuthenticationError = class extends FuserError {
30
+ name = "AuthenticationError";
31
+ };
32
+ var PermissionDeniedError = class extends FuserError {
33
+ name = "PermissionDeniedError";
34
+ };
35
+ var NotFoundError = class extends FuserError {
36
+ name = "NotFoundError";
37
+ };
38
+ var ConflictError = class extends FuserError {
39
+ name = "ConflictError";
40
+ };
41
+ var RateLimitError = class extends FuserError {
42
+ name = "RateLimitError";
43
+ };
44
+ var InternalServerError = class extends FuserError {
45
+ name = "InternalServerError";
46
+ };
47
+ var ConnectionError = class extends FuserError {
48
+ name = "ConnectionError";
49
+ };
50
+ var TimeoutError = class extends FuserError {
51
+ name = "TimeoutError";
52
+ };
53
+ /** `run.start(...).wait()` on a run Fuser refused to start. */
54
+ var RunRefusedError = class extends FuserError {
55
+ name = "RunRefusedError";
56
+ };
57
+ const BY_STATUS = {
58
+ 400: BadRequestError,
59
+ 401: AuthenticationError,
60
+ 403: PermissionDeniedError,
61
+ 404: NotFoundError,
62
+ 409: ConflictError,
63
+ 429: RateLimitError
64
+ };
65
+ function errorFromResponse(tool, response, body) {
66
+ const parsed = body && typeof body === "object" ? body : {};
67
+ const Kind = BY_STATUS[response.status] ?? (response.status >= 500 ? InternalServerError : FuserError);
68
+ const retryAfter = Number(response.headers.get("retry-after"));
69
+ const message = parsed.message ?? `${tool} failed with HTTP ${String(response.status)}.`;
70
+ const issues = parsed.issues?.map((issue) => issue.path ? `${issue.path}: ${issue.message}` : issue.message).join("; ");
71
+ return new Kind(issues ? `${message}: ${issues}` : message, {
72
+ tool,
73
+ status: response.status,
74
+ code: parsed.code,
75
+ reason: parsed.reason,
76
+ issues: parsed.issues,
77
+ requestId: response.headers.get("x-request-id") ?? void 0,
78
+ retryAfterMs: retryAfter > 0 ? retryAfter * 1e3 : void 0,
79
+ body
80
+ });
81
+ }
82
+ //#endregion
83
+ //#region src/generated/core/bodySerializer.gen.ts
84
+ const jsonBodySerializer = { bodySerializer: (body) => JSON.stringify(body, (_key, value) => typeof value === "bigint" ? value.toString() : value) };
85
+ Object.entries({
86
+ $body_: "body",
87
+ $headers_: "headers",
88
+ $path_: "path",
89
+ $query_: "query"
90
+ });
91
+ //#endregion
92
+ //#region src/generated/core/serverSentEvents.gen.ts
93
+ function createSseClient({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }) {
94
+ let lastEventId;
95
+ const sleep = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
96
+ const createStream = async function* () {
97
+ let retryDelay = sseDefaultRetryDelay ?? 3e3;
98
+ let attempt = 0;
99
+ const signal = options.signal ?? new AbortController().signal;
100
+ while (true) {
101
+ if (signal.aborted) break;
102
+ attempt++;
103
+ const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers);
104
+ if (lastEventId !== void 0) headers.set("Last-Event-ID", lastEventId);
105
+ try {
106
+ const requestInit = {
107
+ redirect: "follow",
108
+ ...options,
109
+ body: options.serializedBody,
110
+ headers,
111
+ signal
112
+ };
113
+ let request = new Request(url, requestInit);
114
+ if (onRequest) request = await onRequest(url, requestInit);
115
+ const response = await (options.fetch ?? globalThis.fetch)(request);
116
+ if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`);
117
+ if (!response.body) throw new Error("No body in SSE response");
118
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
119
+ let buffer = "";
120
+ const abortHandler = () => {
121
+ try {
122
+ reader.cancel();
123
+ } catch {}
124
+ };
125
+ signal.addEventListener("abort", abortHandler);
126
+ try {
127
+ while (true) {
128
+ const { done, value } = await reader.read();
129
+ if (done) break;
130
+ buffer += value;
131
+ buffer = buffer.replace(/\r\n?/g, "\n");
132
+ const chunks = buffer.split("\n\n");
133
+ buffer = chunks.pop() ?? "";
134
+ for (const chunk of chunks) {
135
+ const lines = chunk.split("\n");
136
+ const dataLines = [];
137
+ let eventName;
138
+ for (const line of lines) if (line.startsWith("data:")) dataLines.push(line.replace(/^data:\s*/, ""));
139
+ else if (line.startsWith("event:")) eventName = line.replace(/^event:\s*/, "");
140
+ else if (line.startsWith("id:")) lastEventId = line.replace(/^id:\s*/, "");
141
+ else if (line.startsWith("retry:")) {
142
+ const parsed = Number.parseInt(line.replace(/^retry:\s*/, ""), 10);
143
+ if (!Number.isNaN(parsed)) retryDelay = parsed;
144
+ }
145
+ let data;
146
+ let parsedJson = false;
147
+ if (dataLines.length) {
148
+ const rawData = dataLines.join("\n");
149
+ try {
150
+ data = JSON.parse(rawData);
151
+ parsedJson = true;
152
+ } catch {
153
+ data = rawData;
154
+ }
155
+ }
156
+ if (parsedJson) {
157
+ if (responseValidator) await responseValidator(data);
158
+ if (responseTransformer) data = await responseTransformer(data);
159
+ }
160
+ onSseEvent?.({
161
+ data,
162
+ event: eventName,
163
+ id: lastEventId,
164
+ retry: retryDelay
165
+ });
166
+ if (dataLines.length) yield data;
167
+ }
168
+ }
169
+ } finally {
170
+ signal.removeEventListener("abort", abortHandler);
171
+ reader.releaseLock();
172
+ }
173
+ break;
174
+ } catch (error) {
175
+ onSseError?.(error);
176
+ if (sseMaxRetryAttempts !== void 0 && attempt >= sseMaxRetryAttempts) break;
177
+ const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 3e4);
178
+ await sleep(backoff);
179
+ }
180
+ }
181
+ };
182
+ return { stream: createStream() };
183
+ }
184
+ //#endregion
185
+ //#region src/generated/core/pathSerializer.gen.ts
186
+ const separatorArrayExplode = (style) => {
187
+ switch (style) {
188
+ case "label": return ".";
189
+ case "matrix": return ";";
190
+ case "simple": return ",";
191
+ default: return "&";
192
+ }
193
+ };
194
+ const separatorArrayNoExplode = (style) => {
195
+ switch (style) {
196
+ case "form": return ",";
197
+ case "pipeDelimited": return "|";
198
+ case "spaceDelimited": return "%20";
199
+ default: return ",";
200
+ }
201
+ };
202
+ const separatorObjectExplode = (style) => {
203
+ switch (style) {
204
+ case "label": return ".";
205
+ case "matrix": return ";";
206
+ case "simple": return ",";
207
+ default: return "&";
208
+ }
209
+ };
210
+ const serializeArrayParam = ({ allowReserved, explode, name, style, value }) => {
211
+ if (!explode) {
212
+ const joinedValues = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
213
+ switch (style) {
214
+ case "label": return `.${joinedValues}`;
215
+ case "matrix": return `;${name}=${joinedValues}`;
216
+ case "simple": return joinedValues;
217
+ default: return `${name}=${joinedValues}`;
218
+ }
219
+ }
220
+ const separator = separatorArrayExplode(style);
221
+ const joinedValues = value.map((v) => {
222
+ if (style === "label" || style === "simple") return allowReserved ? v : encodeURIComponent(v);
223
+ return serializePrimitiveParam({
224
+ allowReserved,
225
+ name,
226
+ value: v
227
+ });
228
+ }).join(separator);
229
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
230
+ };
231
+ const serializePrimitiveParam = ({ allowReserved, name, value }) => {
232
+ if (value === void 0 || value === null) return "";
233
+ if (typeof value === "object") throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");
234
+ return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
235
+ };
236
+ const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly }) => {
237
+ if (value instanceof Date) return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
238
+ if (style !== "deepObject" && !explode) {
239
+ let values = [];
240
+ Object.entries(value).forEach(([key, v]) => {
241
+ values = [
242
+ ...values,
243
+ key,
244
+ allowReserved ? v : encodeURIComponent(v)
245
+ ];
246
+ });
247
+ const joinedValues = values.join(",");
248
+ switch (style) {
249
+ case "form": return `${name}=${joinedValues}`;
250
+ case "label": return `.${joinedValues}`;
251
+ case "matrix": return `;${name}=${joinedValues}`;
252
+ default: return joinedValues;
253
+ }
254
+ }
255
+ const separator = separatorObjectExplode(style);
256
+ const joinedValues = Object.entries(value).map(([key, v]) => serializePrimitiveParam({
257
+ allowReserved,
258
+ name: style === "deepObject" ? `${name}[${key}]` : key,
259
+ value: v
260
+ })).join(separator);
261
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
262
+ };
263
+ //#endregion
264
+ //#region src/generated/core/utils.gen.ts
265
+ const PATH_PARAM_RE = /\{[^{}]+\}/g;
266
+ const defaultPathSerializer = ({ path, url: _url }) => {
267
+ let url = _url;
268
+ const matches = _url.match(PATH_PARAM_RE);
269
+ if (matches) for (const match of matches) {
270
+ let explode = false;
271
+ let name = match.substring(1, match.length - 1);
272
+ let style = "simple";
273
+ if (name.endsWith("*")) {
274
+ explode = true;
275
+ name = name.substring(0, name.length - 1);
276
+ }
277
+ if (name.startsWith(".")) {
278
+ name = name.substring(1);
279
+ style = "label";
280
+ } else if (name.startsWith(";")) {
281
+ name = name.substring(1);
282
+ style = "matrix";
283
+ }
284
+ const value = path[name];
285
+ if (value === void 0 || value === null) continue;
286
+ if (Array.isArray(value)) {
287
+ url = url.replace(match, serializeArrayParam({
288
+ explode,
289
+ name,
290
+ style,
291
+ value
292
+ }));
293
+ continue;
294
+ }
295
+ if (typeof value === "object") {
296
+ url = url.replace(match, serializeObjectParam({
297
+ explode,
298
+ name,
299
+ style,
300
+ value,
301
+ valueOnly: true
302
+ }));
303
+ continue;
304
+ }
305
+ if (style === "matrix") {
306
+ url = url.replace(match, `;${serializePrimitiveParam({
307
+ name,
308
+ value
309
+ })}`);
310
+ continue;
311
+ }
312
+ const replaceValue = encodeURIComponent(style === "label" ? `.${value}` : value);
313
+ url = url.replace(match, replaceValue);
314
+ }
315
+ return url;
316
+ };
317
+ const getUrl = ({ baseUrl, path, query, querySerializer, url: _url }) => {
318
+ const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
319
+ let url = (baseUrl ?? "") + pathUrl;
320
+ if (path) url = defaultPathSerializer({
321
+ path,
322
+ url
323
+ });
324
+ let search = query ? querySerializer(query) : "";
325
+ if (search.startsWith("?")) search = search.substring(1);
326
+ if (search) url += `?${search}`;
327
+ return url;
328
+ };
329
+ function getValidRequestBody(options) {
330
+ const hasBody = options.body !== void 0;
331
+ if (hasBody && options.bodySerializer) {
332
+ if ("serializedBody" in options) return options.serializedBody !== void 0 && options.serializedBody !== "" ? options.serializedBody : null;
333
+ return options.body !== "" ? options.body : null;
334
+ }
335
+ if (hasBody) return options.body;
336
+ }
337
+ //#endregion
338
+ //#region src/generated/core/auth.gen.ts
339
+ const getAuthToken = async (auth, callback) => {
340
+ const token = typeof callback === "function" ? await callback(auth) : callback;
341
+ if (!token) return;
342
+ if (auth.scheme === "bearer") return `Bearer ${token}`;
343
+ if (auth.scheme === "basic") return `Basic ${btoa(token)}`;
344
+ return token;
345
+ };
346
+ //#endregion
347
+ //#region src/generated/client/utils.gen.ts
348
+ const createQuerySerializer = ({ parameters = {}, ...args } = {}) => {
349
+ const querySerializer = (queryParams) => {
350
+ const search = [];
351
+ if (queryParams && typeof queryParams === "object") for (const name in queryParams) {
352
+ const value = queryParams[name];
353
+ if (value === void 0 || value === null) continue;
354
+ const options = parameters[name] || args;
355
+ if (Array.isArray(value)) {
356
+ const serializedArray = serializeArrayParam({
357
+ allowReserved: options.allowReserved,
358
+ explode: true,
359
+ name,
360
+ style: "form",
361
+ value,
362
+ ...options.array
363
+ });
364
+ if (serializedArray) search.push(serializedArray);
365
+ } else if (typeof value === "object") {
366
+ const serializedObject = serializeObjectParam({
367
+ allowReserved: options.allowReserved,
368
+ explode: true,
369
+ name,
370
+ style: "deepObject",
371
+ value,
372
+ ...options.object
373
+ });
374
+ if (serializedObject) search.push(serializedObject);
375
+ } else {
376
+ const serializedPrimitive = serializePrimitiveParam({
377
+ allowReserved: options.allowReserved,
378
+ name,
379
+ value
380
+ });
381
+ if (serializedPrimitive) search.push(serializedPrimitive);
382
+ }
383
+ }
384
+ return search.join("&");
385
+ };
386
+ return querySerializer;
387
+ };
388
+ /**
389
+ * Infers parseAs value from provided Content-Type header.
390
+ */
391
+ const getParseAs = (contentType) => {
392
+ if (!contentType) return "stream";
393
+ const cleanContent = contentType.split(";")[0]?.trim();
394
+ if (!cleanContent) return;
395
+ if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) return "json";
396
+ if (cleanContent === "multipart/form-data") return "formData";
397
+ if ([
398
+ "application/",
399
+ "audio/",
400
+ "image/",
401
+ "video/"
402
+ ].some((type) => cleanContent.startsWith(type))) return "blob";
403
+ if (cleanContent.startsWith("text/")) return "text";
404
+ };
405
+ const checkForExistence = (options, name) => {
406
+ if (!name) return false;
407
+ if (options.headers.has(name) || options.query?.[name] || options.headers.get("Cookie")?.includes(`${name}=`)) return true;
408
+ return false;
409
+ };
410
+ async function setAuthParams(options) {
411
+ for (const auth of options.security ?? []) {
412
+ if (checkForExistence(options, auth.name)) continue;
413
+ const token = await getAuthToken(auth, options.auth);
414
+ if (!token) continue;
415
+ const name = auth.name ?? "Authorization";
416
+ switch (auth.in) {
417
+ case "query":
418
+ if (!options.query) options.query = {};
419
+ options.query[name] = token;
420
+ break;
421
+ case "cookie":
422
+ options.headers.append("Cookie", `${name}=${token}`);
423
+ break;
424
+ default: options.headers.set(name, token);
425
+ }
426
+ }
427
+ }
428
+ const buildUrl = (options) => getUrl({
429
+ baseUrl: options.baseUrl,
430
+ path: options.path,
431
+ query: options.query,
432
+ querySerializer: typeof options.querySerializer === "function" ? options.querySerializer : createQuerySerializer(options.querySerializer),
433
+ url: options.url
434
+ });
435
+ const mergeConfigs = (a, b) => {
436
+ const config = {
437
+ ...a,
438
+ ...b
439
+ };
440
+ if (config.baseUrl?.endsWith("/")) config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
441
+ config.headers = mergeHeaders(a.headers, b.headers);
442
+ return config;
443
+ };
444
+ const headersEntries = (headers) => {
445
+ const entries = [];
446
+ headers.forEach((value, key) => {
447
+ entries.push([key, value]);
448
+ });
449
+ return entries;
450
+ };
451
+ const mergeHeaders = (...headers) => {
452
+ const mergedHeaders = new Headers();
453
+ for (const header of headers) {
454
+ if (!header) continue;
455
+ const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
456
+ for (const [key, value] of iterator) if (value === null) mergedHeaders.delete(key);
457
+ else if (Array.isArray(value)) for (const v of value) mergedHeaders.append(key, v);
458
+ else if (value !== void 0) mergedHeaders.set(key, typeof value === "object" ? JSON.stringify(value) : value);
459
+ }
460
+ return mergedHeaders;
461
+ };
462
+ var Interceptors = class {
463
+ fns = [];
464
+ clear() {
465
+ this.fns = [];
466
+ }
467
+ eject(id) {
468
+ const index = this.getInterceptorIndex(id);
469
+ if (this.fns[index]) this.fns[index] = null;
470
+ }
471
+ exists(id) {
472
+ const index = this.getInterceptorIndex(id);
473
+ return Boolean(this.fns[index]);
474
+ }
475
+ getInterceptorIndex(id) {
476
+ if (typeof id === "number") return this.fns[id] ? id : -1;
477
+ return this.fns.indexOf(id);
478
+ }
479
+ update(id, fn) {
480
+ const index = this.getInterceptorIndex(id);
481
+ if (this.fns[index]) {
482
+ this.fns[index] = fn;
483
+ return id;
484
+ }
485
+ return false;
486
+ }
487
+ use(fn) {
488
+ this.fns.push(fn);
489
+ return this.fns.length - 1;
490
+ }
491
+ };
492
+ const createInterceptors = () => ({
493
+ error: new Interceptors(),
494
+ request: new Interceptors(),
495
+ response: new Interceptors()
496
+ });
497
+ const defaultQuerySerializer = createQuerySerializer({
498
+ allowReserved: false,
499
+ array: {
500
+ explode: true,
501
+ style: "form"
502
+ },
503
+ object: {
504
+ explode: true,
505
+ style: "deepObject"
506
+ }
507
+ });
508
+ const defaultHeaders = { "Content-Type": "application/json" };
509
+ const createConfig = (override = {}) => ({
510
+ ...jsonBodySerializer,
511
+ headers: defaultHeaders,
512
+ parseAs: "auto",
513
+ querySerializer: defaultQuerySerializer,
514
+ ...override
515
+ });
516
+ //#endregion
517
+ //#region src/generated/client/client.gen.ts
518
+ const createClient = (config = {}) => {
519
+ let _config = mergeConfigs(createConfig(), config);
520
+ const getConfig = () => ({ ..._config });
521
+ const setConfig = (config) => {
522
+ _config = mergeConfigs(_config, config);
523
+ return getConfig();
524
+ };
525
+ const interceptors = createInterceptors();
526
+ const beforeRequest = async (options) => {
527
+ const opts = {
528
+ ..._config,
529
+ ...options,
530
+ fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
531
+ headers: mergeHeaders(_config.headers, options.headers),
532
+ serializedBody: void 0
533
+ };
534
+ if (opts.security) await setAuthParams(opts);
535
+ if (opts.requestValidator) await opts.requestValidator(opts);
536
+ if (opts.body !== void 0 && opts.bodySerializer) opts.serializedBody = opts.bodySerializer(opts.body);
537
+ if (opts.body === void 0 || opts.serializedBody === "") opts.headers.delete("Content-Type");
538
+ const resolvedOpts = opts;
539
+ return {
540
+ opts: resolvedOpts,
541
+ url: buildUrl(resolvedOpts)
542
+ };
543
+ };
544
+ const request = async (options) => {
545
+ const throwOnError = options.throwOnError ?? _config.throwOnError;
546
+ const responseStyle = options.responseStyle ?? _config.responseStyle;
547
+ let request;
548
+ let response;
549
+ try {
550
+ const { opts, url } = await beforeRequest(options);
551
+ const requestInit = {
552
+ redirect: "follow",
553
+ ...opts,
554
+ body: getValidRequestBody(opts)
555
+ };
556
+ request = new Request(url, requestInit);
557
+ for (const fn of interceptors.request.fns) if (fn) request = await fn(request, opts);
558
+ const _fetch = opts.fetch;
559
+ response = await _fetch(request);
560
+ for (const fn of interceptors.response.fns) if (fn) response = await fn(response, request, opts);
561
+ const result = {
562
+ request,
563
+ response
564
+ };
565
+ if (response.ok) {
566
+ const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json";
567
+ if (response.status === 204 || response.headers.get("Content-Length") === "0") {
568
+ let emptyData;
569
+ switch (parseAs) {
570
+ case "arrayBuffer":
571
+ case "blob":
572
+ case "text":
573
+ emptyData = await response[parseAs]();
574
+ break;
575
+ case "formData":
576
+ emptyData = new FormData();
577
+ break;
578
+ case "stream":
579
+ emptyData = response.body;
580
+ break;
581
+ default: emptyData = {};
582
+ }
583
+ return opts.responseStyle === "data" ? emptyData : {
584
+ data: emptyData,
585
+ ...result
586
+ };
587
+ }
588
+ let data;
589
+ switch (parseAs) {
590
+ case "arrayBuffer":
591
+ case "blob":
592
+ case "formData":
593
+ case "text":
594
+ data = await response[parseAs]();
595
+ break;
596
+ case "json": {
597
+ const text = await response.text();
598
+ data = text ? JSON.parse(text) : {};
599
+ break;
600
+ }
601
+ case "stream": return opts.responseStyle === "data" ? response.body : {
602
+ data: response.body,
603
+ ...result
604
+ };
605
+ }
606
+ if (parseAs === "json") {
607
+ if (opts.responseValidator) await opts.responseValidator(data);
608
+ if (opts.responseTransformer) data = await opts.responseTransformer(data);
609
+ }
610
+ return opts.responseStyle === "data" ? data : {
611
+ data,
612
+ ...result
613
+ };
614
+ }
615
+ const textError = await response.text();
616
+ let jsonError;
617
+ try {
618
+ jsonError = JSON.parse(textError);
619
+ } catch {}
620
+ throw jsonError ?? textError;
621
+ } catch (error) {
622
+ let finalError = error;
623
+ for (const fn of interceptors.error.fns) if (fn) finalError = await fn(finalError, response, request, options);
624
+ finalError = finalError || {};
625
+ if (throwOnError) throw finalError;
626
+ return responseStyle === "data" ? void 0 : {
627
+ error: finalError,
628
+ request,
629
+ response
630
+ };
631
+ }
632
+ };
633
+ const makeMethodFn = (method) => (options) => request({
634
+ ...options,
635
+ method
636
+ });
637
+ const makeSseFn = (method) => async (options) => {
638
+ const { opts, url } = await beforeRequest(options);
639
+ return createSseClient({
640
+ ...opts,
641
+ body: opts.body,
642
+ method,
643
+ onRequest: async (url, init) => {
644
+ let request = new Request(url, init);
645
+ for (const fn of interceptors.request.fns) if (fn) request = await fn(request, opts);
646
+ return request;
647
+ },
648
+ serializedBody: getValidRequestBody(opts),
649
+ url
650
+ });
651
+ };
652
+ const _buildUrl = (options) => buildUrl({
653
+ ..._config,
654
+ ...options
655
+ });
656
+ return {
657
+ buildUrl: _buildUrl,
658
+ connect: makeMethodFn("CONNECT"),
659
+ delete: makeMethodFn("DELETE"),
660
+ get: makeMethodFn("GET"),
661
+ getConfig,
662
+ head: makeMethodFn("HEAD"),
663
+ interceptors,
664
+ options: makeMethodFn("OPTIONS"),
665
+ patch: makeMethodFn("PATCH"),
666
+ post: makeMethodFn("POST"),
667
+ put: makeMethodFn("PUT"),
668
+ request,
669
+ setConfig,
670
+ sse: {
671
+ connect: makeSseFn("CONNECT"),
672
+ delete: makeSseFn("DELETE"),
673
+ get: makeSseFn("GET"),
674
+ head: makeSseFn("HEAD"),
675
+ options: makeSseFn("OPTIONS"),
676
+ patch: makeSseFn("PATCH"),
677
+ post: makeSseFn("POST"),
678
+ put: makeSseFn("PUT"),
679
+ trace: makeSseFn("TRACE")
680
+ },
681
+ trace: makeMethodFn("TRACE")
682
+ };
683
+ };
684
+ //#endregion
685
+ //#region src/generated/client.gen.ts
686
+ const client = createClient(createConfig({ baseUrl: "https://api.fuser.studio" }));
687
+ //#endregion
688
+ //#region src/generated/sdk.gen.ts
689
+ var sdk_gen_exports = /* @__PURE__ */ __exportAll({
690
+ accountGet: () => accountGet,
691
+ canvasArrange: () => canvasArrange,
692
+ canvasEdit: () => canvasEdit,
693
+ canvasGet: () => canvasGet,
694
+ canvasList: () => canvasList,
695
+ catalogSearch: () => catalogSearch,
696
+ mediaExport: () => mediaExport,
697
+ mediaImport: () => mediaImport,
698
+ mediaSearch: () => mediaSearch,
699
+ mediaView: () => mediaView,
700
+ runCancel: () => runCancel,
701
+ runGet: () => runGet,
702
+ runStart: () => runStart,
703
+ toolBuild: () => toolBuild,
704
+ toolSearch: () => toolSearch,
705
+ uploadFinish: () => uploadFinish,
706
+ uploadStart: () => uploadStart
707
+ });
708
+ /**
709
+ * List canvases
710
+ *
711
+ * Canvases you can open, most recently edited first, with a link to each. Reuse one only when the user points to it; put new work on a new canvas, and never present results that were already there as new.
712
+ */
713
+ const canvasList = (options) => (options?.client ?? client).get({
714
+ security: [{
715
+ name: "x-api-key",
716
+ type: "apiKey"
717
+ }, {
718
+ scheme: "bearer",
719
+ type: "http"
720
+ }],
721
+ url: "/v1/canvas_list",
722
+ ...options
723
+ });
724
+ /**
725
+ * Read a canvas
726
+ *
727
+ * A compact view of a canvas: a summary, then pages of nodes (id, type, label, socket keys, literal values, result links) and their edges. On a big canvas, find nodes with search or read specific ones with nodeIds instead of paging through everything.
728
+ */
729
+ const canvasGet = (options) => (options.client ?? client).get({
730
+ security: [{
731
+ name: "x-api-key",
732
+ type: "apiKey"
733
+ }, {
734
+ scheme: "bearer",
735
+ type: "http"
736
+ }],
737
+ url: "/v1/canvas_get",
738
+ ...options
739
+ });
740
+ /**
741
+ * Edit a canvas
742
+ *
743
+ * Apply a graph diff to a canvas all at once: add nodes and edges, change inputs, disconnect edges, delete nodes. Every change lands or none does. Keep each edit to about 30 new nodes; build a bigger canvas one section per edit, so a mistake costs one small resend.
744
+ */
745
+ const canvasEdit = (options) => (options.client ?? client).post({
746
+ security: [{
747
+ name: "x-api-key",
748
+ type: "apiKey"
749
+ }, {
750
+ scheme: "bearer",
751
+ type: "http"
752
+ }],
753
+ url: "/v1/canvas_edit",
754
+ ...options,
755
+ headers: {
756
+ "Content-Type": "application/json",
757
+ ...options.headers
758
+ }
759
+ });
760
+ /**
761
+ * Arrange nodes on a canvas
762
+ *
763
+ * Lay out existing nodes with Fuser's layout instead of working out positions. Without layout it tidies them along their wiring, inputs to the left of what they feed; with layout it puts them in a row, column or grid in nodeIds order. Without an origin the block stays where the nodes are and slides clear of the nodes around it. Use it when the user asks to rearrange, line up or tidy nodes, or after resizing nodes that now overlap. It changes positions only.
764
+ */
765
+ const canvasArrange = (options) => (options.client ?? client).post({
766
+ security: [{
767
+ name: "x-api-key",
768
+ type: "apiKey"
769
+ }, {
770
+ scheme: "bearer",
771
+ type: "http"
772
+ }],
773
+ url: "/v1/canvas_arrange",
774
+ ...options,
775
+ headers: {
776
+ "Content-Type": "application/json",
777
+ ...options.headers
778
+ }
779
+ });
780
+ /**
781
+ * Find node types
782
+ *
783
+ * Node types a canvas_edit diff may use, with what each is good at, its input ids and its output socket. Call it with no query first: it returns the recommended node for each common job. Search only when none of them fits.
784
+ */
785
+ const catalogSearch = (options) => (options?.client ?? client).get({
786
+ security: [{
787
+ name: "x-api-key",
788
+ type: "apiKey"
789
+ }, {
790
+ scheme: "bearer",
791
+ type: "http"
792
+ }],
793
+ url: "/v1/catalog_search",
794
+ ...options
795
+ });
796
+ /**
797
+ * Run a canvas
798
+ *
799
+ * Run the whole canvas or named nodes. Prices the run first and refuses it when it costs more than maxCredits; dryRun returns only the price. Starts a run once per idempotencyKey; check on it with run_get, not by calling run_start again.
800
+ */
801
+ const runStart = (options) => (options.client ?? client).post({
802
+ security: [{
803
+ name: "x-api-key",
804
+ type: "apiKey"
805
+ }, {
806
+ scheme: "bearer",
807
+ type: "http"
808
+ }],
809
+ url: "/v1/run_start",
810
+ ...options,
811
+ headers: {
812
+ "Content-Type": "application/json",
813
+ ...options.headers
814
+ }
815
+ });
816
+ /**
817
+ * Check a run
818
+ *
819
+ * Status of a run you started, per node, with links to each node's results.
820
+ */
821
+ const runGet = (options) => (options.client ?? client).get({
822
+ security: [{
823
+ name: "x-api-key",
824
+ type: "apiKey"
825
+ }, {
826
+ scheme: "bearer",
827
+ type: "http"
828
+ }],
829
+ url: "/v1/run_get",
830
+ ...options
831
+ });
832
+ /**
833
+ * Cancel a run
834
+ *
835
+ * Stop a run you started. Nodes already finished keep their results.
836
+ */
837
+ const runCancel = (options) => (options.client ?? client).post({
838
+ security: [{
839
+ name: "x-api-key",
840
+ type: "apiKey"
841
+ }, {
842
+ scheme: "bearer",
843
+ type: "http"
844
+ }],
845
+ url: "/v1/run_cancel",
846
+ ...options,
847
+ headers: {
848
+ "Content-Type": "application/json",
849
+ ...options.headers
850
+ }
851
+ });
852
+ /**
853
+ * Import an image or video
854
+ *
855
+ * Copy an image or video from a public URL into the canvas's assets and get a Fuser link for it. Use it before putting a web link on the canvas: it says straight away when the link can't be fetched, and the copy won't expire. For a file on the user's machine use upload_start.
856
+ */
857
+ const mediaImport = (options) => (options.client ?? client).post({
858
+ security: [{
859
+ name: "x-api-key",
860
+ type: "apiKey"
861
+ }, {
862
+ scheme: "bearer",
863
+ type: "http"
864
+ }],
865
+ url: "/v1/media_import",
866
+ ...options,
867
+ headers: {
868
+ "Content-Type": "application/json",
869
+ ...options.headers
870
+ }
871
+ });
872
+ /**
873
+ * Upload files
874
+ *
875
+ * Step 1 of putting files from the user's machine on a canvas, for agents that run commands on that machine (Claude Code, Codex, an IDE). List the files (up to 50): each comes back with a link to PUT it to, or done if Fuser already has it. Then call upload_finish with uploadId. In a chat app use upload_box instead; a cloud code sandbox can't reach these links.
876
+ */
877
+ const uploadStart = (options) => (options.client ?? client).post({
878
+ security: [{
879
+ name: "x-api-key",
880
+ type: "apiKey"
881
+ }, {
882
+ scheme: "bearer",
883
+ type: "http"
884
+ }],
885
+ url: "/v1/upload_start",
886
+ ...options,
887
+ headers: {
888
+ "Content-Type": "application/json",
889
+ ...options.headers
890
+ }
891
+ });
892
+ /**
893
+ * Finish uploading files
894
+ *
895
+ * Step 2: returns a link for every file that arrived, to use as an ImageNode or VideoNode input, and says why for any that did not. For files the user is adding on the upload page, call it after they say they are done.
896
+ */
897
+ const uploadFinish = (options) => (options.client ?? client).post({
898
+ security: [{
899
+ name: "x-api-key",
900
+ type: "apiKey"
901
+ }, {
902
+ scheme: "bearer",
903
+ type: "http"
904
+ }],
905
+ url: "/v1/upload_finish",
906
+ ...options,
907
+ headers: {
908
+ "Content-Type": "application/json",
909
+ ...options.headers
910
+ }
911
+ });
912
+ /**
913
+ * Look at media
914
+ *
915
+ * See Fuser images and 3D models as small previews, and the first frame of a video, with facts such as size, length and transparency. Look at results before describing or judging them.
916
+ */
917
+ const mediaView = (options) => (options.client ?? client).post({
918
+ security: [{
919
+ name: "x-api-key",
920
+ type: "apiKey"
921
+ }, {
922
+ scheme: "bearer",
923
+ type: "http"
924
+ }],
925
+ url: "/v1/media_view",
926
+ ...options,
927
+ headers: {
928
+ "Content-Type": "application/json",
929
+ ...options.headers
930
+ }
931
+ });
932
+ /**
933
+ * Find your media
934
+ *
935
+ * Search the images, videos, audio and 3D files you made or uploaded, by meaning ("the coral reef image", "a dog running on a beach") or by similarity to one you have. Without query or similarTo it lists the newest first. Look at matches with media_view.
936
+ */
937
+ const mediaSearch = (options) => (options.client ?? client).post({
938
+ security: [{
939
+ name: "x-api-key",
940
+ type: "apiKey"
941
+ }, {
942
+ scheme: "bearer",
943
+ type: "http"
944
+ }],
945
+ url: "/v1/media_search",
946
+ ...options,
947
+ headers: {
948
+ "Content-Type": "application/json",
949
+ ...options.headers
950
+ }
951
+ });
952
+ /**
953
+ * Download media as a zip
954
+ *
955
+ * A link that downloads a canvas's results as one zip file, for when the user wants their files ('download everything', 'send me the images as a zip'). Give the user the link; it works for an hour. It changes nothing on the canvas.
956
+ */
957
+ const mediaExport = (options) => (options.client ?? client).post({
958
+ security: [{
959
+ name: "x-api-key",
960
+ type: "apiKey"
961
+ }, {
962
+ scheme: "bearer",
963
+ type: "http"
964
+ }],
965
+ url: "/v1/media_export",
966
+ ...options,
967
+ headers: {
968
+ "Content-Type": "application/json",
969
+ ...options.headers
970
+ }
971
+ });
972
+ /**
973
+ * Read your account
974
+ *
975
+ * Who you are, your personal credits and plan, and each workspace you belong to with your role, its plan, the team's credits and your monthly spend limit there. Runs on a workspace canvas spend that workspace's credits if you belong to it; runs on a personal canvas, or a workspace canvas shared with you from outside, spend yours.
976
+ */
977
+ const accountGet = (options) => (options?.client ?? client).get({
978
+ security: [{
979
+ name: "x-api-key",
980
+ type: "apiKey"
981
+ }, {
982
+ scheme: "bearer",
983
+ type: "http"
984
+ }],
985
+ url: "/v1/account_get",
986
+ ...options
987
+ });
988
+ /**
989
+ * Find a saved tool
990
+ *
991
+ * Search the canvas's tool library (tools you or your workspace built) and Fuser's featured tools by title and description. Place a match with tool_build toolId. Only worth it when a tool for the job likely exists; building a new one with tool_build prompt is fine too.
992
+ */
993
+ const toolSearch = (options) => (options.client ?? client).get({
994
+ security: [{
995
+ name: "x-api-key",
996
+ type: "apiKey"
997
+ }, {
998
+ scheme: "bearer",
999
+ type: "http"
1000
+ }],
1001
+ url: "/v1/tool_search",
1002
+ ...options
1003
+ });
1004
+ /**
1005
+ * Build a tool
1006
+ *
1007
+ * Turn a Tool node (type UtilityNode, added with canvas_edit) into a working tool: describe it in prompt and Fuser writes its code, or place a saved one with toolId. Tools do what generators can't: join, cut, trim or speed up videos, mix audio, crop, grid, filter, measure and convert between images, video, audio, 3D models, text and JSON (not PDF, ZIP or other files). Call it again with a prompt to change a built tool, or with neither to check on a build. Once built, wire its input sockets and set its controls with canvas_edit, then run it like any node; free tools cost nothing to run.
1008
+ */
1009
+ const toolBuild = (options) => (options.client ?? client).post({
1010
+ security: [{
1011
+ name: "x-api-key",
1012
+ type: "apiKey"
1013
+ }, {
1014
+ scheme: "bearer",
1015
+ type: "http"
1016
+ }],
1017
+ url: "/v1/tool_build",
1018
+ ...options,
1019
+ headers: {
1020
+ "Content-Type": "application/json",
1021
+ ...options.headers
1022
+ }
1023
+ });
1024
+ //#endregion
1025
+ //#region src/pages.ts
1026
+ /**
1027
+ * A paged list: await it for the first page, or `for await` it for every
1028
+ * item on every page.
1029
+ */
1030
+ var PagePromise = class {
1031
+ #first;
1032
+ #load;
1033
+ #items;
1034
+ constructor(load, items) {
1035
+ this.#load = load;
1036
+ this.#items = items;
1037
+ }
1038
+ #firstPage() {
1039
+ this.#first ??= this.#load();
1040
+ return this.#first;
1041
+ }
1042
+ then(onfulfilled, onrejected) {
1043
+ return this.#firstPage().then(onfulfilled, onrejected);
1044
+ }
1045
+ async *pages() {
1046
+ let page = await this.#firstPage();
1047
+ yield page;
1048
+ while (page.nextCursor) {
1049
+ page = await this.#load(page.nextCursor);
1050
+ yield page;
1051
+ }
1052
+ }
1053
+ async *[Symbol.asyncIterator]() {
1054
+ for await (const page of this.pages()) yield* this.#items(page);
1055
+ }
1056
+ /** Every item on every page. */
1057
+ async all() {
1058
+ const items = [];
1059
+ for await (const item of this) items.push(item);
1060
+ return items;
1061
+ }
1062
+ };
1063
+ //#endregion
1064
+ //#region src/fuser.ts
1065
+ const OPERATIONS = {
1066
+ accountGet: {
1067
+ in: "query",
1068
+ retry: "transient"
1069
+ },
1070
+ canvasArrange: {
1071
+ in: "body",
1072
+ retry: (args) => args.expectedRevision === void 0 ? "transient" : "rate-limit"
1073
+ },
1074
+ canvasEdit: {
1075
+ in: "body",
1076
+ retry: "transient"
1077
+ },
1078
+ canvasGet: {
1079
+ in: "query",
1080
+ retry: "transient"
1081
+ },
1082
+ canvasList: {
1083
+ in: "query",
1084
+ retry: "transient"
1085
+ },
1086
+ catalogSearch: {
1087
+ in: "query",
1088
+ retry: "transient"
1089
+ },
1090
+ mediaExport: {
1091
+ in: "body",
1092
+ retry: "transient"
1093
+ },
1094
+ mediaImport: {
1095
+ in: "body",
1096
+ retry: "rate-limit"
1097
+ },
1098
+ mediaSearch: {
1099
+ in: "body",
1100
+ retry: "transient"
1101
+ },
1102
+ mediaView: {
1103
+ in: "body",
1104
+ retry: "transient"
1105
+ },
1106
+ runCancel: {
1107
+ in: "body",
1108
+ retry: "transient"
1109
+ },
1110
+ runGet: {
1111
+ in: "query",
1112
+ retry: "transient"
1113
+ },
1114
+ runStart: {
1115
+ in: "body",
1116
+ retry: "transient"
1117
+ },
1118
+ toolBuild: {
1119
+ in: "body",
1120
+ retry: (args) => args.prompt || args.toolId ? "rate-limit" : "transient"
1121
+ },
1122
+ toolSearch: {
1123
+ in: "query",
1124
+ retry: "transient"
1125
+ },
1126
+ uploadFinish: {
1127
+ in: "body",
1128
+ retry: "transient"
1129
+ },
1130
+ uploadStart: {
1131
+ in: "body",
1132
+ retry: "transient"
1133
+ }
1134
+ };
1135
+ const RETRYABLE_STATUSES = /* @__PURE__ */ new Set([
1136
+ 408,
1137
+ 429,
1138
+ 500,
1139
+ 502,
1140
+ 503,
1141
+ 504
1142
+ ]);
1143
+ /** upload_start takes at most this many files. */
1144
+ const MAX_UPLOAD_FILES = 50;
1145
+ /** The server holds a waiting call open at most this long. */
1146
+ const MAX_WAIT_SECONDS = 45;
1147
+ /** Runs answer sooner: the server waits at most this long on a run. */
1148
+ const RUN_WAIT_SECONDS = 10;
1149
+ /** A longer Retry-After is the caller's call, not ours to sleep through. */
1150
+ const MAX_RETRY_DELAY_MS = 6e4;
1151
+ var StartedCall = class {
1152
+ started;
1153
+ constructor(started) {
1154
+ this.started = started;
1155
+ }
1156
+ then(onfulfilled, onrejected) {
1157
+ return this.started.then(onfulfilled, onrejected);
1158
+ }
1159
+ };
1160
+ /** `run.start()`: await for the start result, or `.wait()` for the finished run. */
1161
+ var RunCall = class extends StartedCall {
1162
+ #wait;
1163
+ constructor(started, wait) {
1164
+ super(started);
1165
+ this.#wait = wait;
1166
+ }
1167
+ /** The run once it stops running. Throws if it was refused or only priced. */
1168
+ async wait(options) {
1169
+ const timeoutMs = options?.timeoutMs ?? 18e5;
1170
+ const startedAt = Date.now();
1171
+ const result = await deadline(timeoutMs, options?.signal, "The run is still starting.", "run_start").guard(this.started);
1172
+ if (result.status === "refused") throw new RunRefusedError(result.error, {
1173
+ tool: "run_start",
1174
+ reason: result.reason,
1175
+ body: result
1176
+ });
1177
+ if (result.status === "quoted") throw new FuserError("A dry run only prices the run; nothing to wait for.", {
1178
+ tool: "run_start",
1179
+ body: result
1180
+ });
1181
+ if (result.run && result.run.status !== "running") return result.run;
1182
+ return this.#wait(result.runId, {
1183
+ signal: options?.signal,
1184
+ timeoutMs: Math.max(timeoutMs - (Date.now() - startedAt), 1)
1185
+ });
1186
+ }
1187
+ };
1188
+ /** `tool.build()`: await for its state now, or `.wait()` until it's built. */
1189
+ var ToolBuildCall = class extends StartedCall {
1190
+ #check;
1191
+ constructor(started, check) {
1192
+ super(started);
1193
+ this.#check = check;
1194
+ }
1195
+ /** The tool once its build stops; check `status` for built or failed. */
1196
+ async wait(options) {
1197
+ const scope = deadline(options?.timeoutMs ?? 6e5, options?.signal, "The tool is still building.", "tool_build");
1198
+ let state = await scope.guard(this.started);
1199
+ while (state.status === "building") {
1200
+ options?.signal?.throwIfAborted();
1201
+ if (scope.expired()) throw scope.timeout();
1202
+ state = await scope.guard(this.#check(scope.signal));
1203
+ }
1204
+ return state;
1205
+ }
1206
+ };
1207
+ const toCamel = (name) => name.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
1208
+ const toSnake = (key) => key.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
1209
+ const sleep = (ms, signal) => new Promise((resolve, reject) => {
1210
+ if (signal?.aborted) {
1211
+ reject(signal.reason);
1212
+ return;
1213
+ }
1214
+ const onAbort = () => {
1215
+ clearTimeout(timer);
1216
+ reject(signal?.reason);
1217
+ };
1218
+ const timer = setTimeout(() => {
1219
+ signal?.removeEventListener("abort", onAbort);
1220
+ resolve();
1221
+ }, ms);
1222
+ signal?.addEventListener("abort", onAbort, { once: true });
1223
+ });
1224
+ function base64(bytes) {
1225
+ let binary = "";
1226
+ for (const byte of bytes) binary += String.fromCharCode(byte);
1227
+ return btoa(binary);
1228
+ }
1229
+ const withSignal = (signal, other) => signal ? AbortSignal.any([signal, other]) : other;
1230
+ const mergeSignals = (first, second) => first && second ? AbortSignal.any([first, second]) : first ?? second;
1231
+ /** One deadline for a whole wait: every poll and retry shares its signal. */
1232
+ function deadline(timeoutMs, signal, message, tool) {
1233
+ const timer = AbortSignal.timeout(timeoutMs);
1234
+ const expired = () => timer.aborted && !signal?.aborted;
1235
+ const timeout = (cause) => new TimeoutError(message, {
1236
+ tool,
1237
+ cause
1238
+ });
1239
+ return {
1240
+ signal: withSignal(signal, timer),
1241
+ expired,
1242
+ timeout,
1243
+ /** `work`, or a timeout or abort as soon as either fires, whichever is first. */
1244
+ async guard(work) {
1245
+ const combined = withSignal(signal, timer);
1246
+ let stop = () => {};
1247
+ const stopped = new Promise((_, reject) => {
1248
+ stop = () => reject(expired() ? timeout() : signal?.reason ?? timeout());
1249
+ if (combined.aborted) stop();
1250
+ else combined.addEventListener("abort", stop, { once: true });
1251
+ });
1252
+ stopped.catch(() => void 0);
1253
+ try {
1254
+ return await Promise.race([work, stopped]);
1255
+ } catch (error) {
1256
+ throw expired() && !(error instanceof TimeoutError) ? timeout(error) : error;
1257
+ } finally {
1258
+ combined.removeEventListener("abort", stop);
1259
+ }
1260
+ }
1261
+ };
1262
+ }
1263
+ /**
1264
+ * The Fuser API. Each tool is a method named after it: `canvas_edit` is
1265
+ * `fuser.canvas.edit()`, with the same arguments and result as the MCP tool.
1266
+ */
1267
+ var Fuser = class {
1268
+ client;
1269
+ #fetch;
1270
+ #timeoutMs;
1271
+ #maxRetries;
1272
+ account = { get: (_args, options) => this.#request("accountGet", void 0, options) };
1273
+ canvas = {
1274
+ /** Await for a page, or `for await` for every canvas. */
1275
+ list: (args, options) => this.#pages("canvasList", args ?? {}, (page) => page.canvases, options),
1276
+ /** Await for a page, or `for await` for every node. */
1277
+ get: (args, options) => this.#pages("canvasGet", args, (page) => page.nodes, options),
1278
+ /** `idempotencyKey` defaults to a new one per call. */
1279
+ edit: (args, options) => this.#request("canvasEdit", args, options),
1280
+ arrange: (args, options) => this.#request("canvasArrange", args, options)
1281
+ };
1282
+ catalog = { search: (args, options) => this.#request("catalogSearch", args ?? {}, options) };
1283
+ run = {
1284
+ /** `idempotencyKey` defaults to a new one per call. Add `.wait()` to wait. */
1285
+ start: (args, options) => new RunCall(this.#request("runStart", args, options), (runId, waitOptions) => this.#waitForRun({
1286
+ canvasId: args.canvasId,
1287
+ runId
1288
+ }, {
1289
+ ...waitOptions,
1290
+ signal: mergeSignals(options?.signal, waitOptions?.signal)
1291
+ })),
1292
+ get: (args, options) => this.#request("runGet", args, options),
1293
+ cancel: (args, options) => this.#request("runCancel", args, options),
1294
+ /** Checks a run until it stops running. */
1295
+ wait: (args, options) => this.#waitForRun(args, options)
1296
+ };
1297
+ media = {
1298
+ export: (args, options) => this.#request("mediaExport", args, options),
1299
+ import: (args, options) => this.#request("mediaImport", args, options),
1300
+ /** Await for a page, or `for await` for every match. */
1301
+ search: (args, options) => this.#pages("mediaSearch", args, (page) => page.assets, options),
1302
+ view: (args, options) => this.#request("mediaView", args, options)
1303
+ };
1304
+ upload = {
1305
+ start: (args, options) => this.#request("uploadStart", args, options),
1306
+ finish: (args, options) => this.#request("uploadFinish", args, options),
1307
+ /** Hashes, starts, sends and finishes in one call. */
1308
+ files: (canvasId, files, options) => this.#uploadFiles(canvasId, files, options)
1309
+ };
1310
+ tool = {
1311
+ search: (args, options) => this.#request("toolSearch", args, options),
1312
+ /** Add `.wait()` to wait until it's built. */
1313
+ build: (args, options) => {
1314
+ const { canvasId, nodeId } = args;
1315
+ return new ToolBuildCall(this.#request("toolBuild", args, options), (signal) => this.#request("toolBuild", {
1316
+ canvasId,
1317
+ nodeId,
1318
+ waitSeconds: MAX_WAIT_SECONDS
1319
+ }, {
1320
+ ...options,
1321
+ ...signal ? { signal: withSignal(options?.signal, signal) } : {}
1322
+ }));
1323
+ }
1324
+ };
1325
+ constructor(options = {}) {
1326
+ const apiKey = options.apiKey ?? globalThis.process?.env?.FUSER_API_KEY;
1327
+ if ("document" in globalThis && "window" in globalThis && !options.dangerouslyAllowBrowser) throw new FuserError("A Fuser API key acts as you, so keep it on a server. Pass dangerouslyAllowBrowser to use it in a browser anyway.", { tool: "client" });
1328
+ this.#fetch = options.fetch ?? globalThis.fetch.bind(globalThis);
1329
+ this.#timeoutMs = options.timeoutMs ?? 6e4;
1330
+ this.#maxRetries = options.maxRetries ?? 2;
1331
+ this.client = createClient({
1332
+ baseUrl: options.baseUrl ?? "https://api.fuser.studio",
1333
+ fetch: this.#fetch,
1334
+ auth: (scheme) => scheme.scheme === "bearer" ? apiKey : void 0
1335
+ });
1336
+ const { beforeSend, afterSend } = options;
1337
+ if (beforeSend) this.client.interceptors.request.use(async (request) => await beforeSend(request) ?? request);
1338
+ if (afterSend) this.client.interceptors.response.use(async (response, request) => {
1339
+ await afterSend(response, request);
1340
+ return response;
1341
+ });
1342
+ }
1343
+ /** Calls a tool by its MCP name, with the exact arguments an agent sent. */
1344
+ call(name, args, options) {
1345
+ return this.#request(toCamel(name), args, options);
1346
+ }
1347
+ #pages(key, args, items, options) {
1348
+ return new PagePromise(async (cursor) => await this.#request(key, {
1349
+ ...args,
1350
+ cursor: cursor ?? args.cursor
1351
+ }, options), items);
1352
+ }
1353
+ async #waitForRun(args, options) {
1354
+ const scope = deadline(options?.timeoutMs ?? 18e5, options?.signal, `Run ${args.runId} is still running.`, "run_get");
1355
+ for (;;) {
1356
+ const summary = await scope.guard(this.run.get({
1357
+ ...args,
1358
+ waitSeconds: RUN_WAIT_SECONDS
1359
+ }, { signal: scope.signal }));
1360
+ if (summary.status !== "running") return summary;
1361
+ options?.signal?.throwIfAborted();
1362
+ if (scope.expired()) throw scope.timeout();
1363
+ }
1364
+ }
1365
+ async #uploadFiles(canvasId, inputs, options) {
1366
+ const uploaded = [];
1367
+ for (let start = 0; start < inputs.length; start += MAX_UPLOAD_FILES) uploaded.push(...await this.#uploadBatch(canvasId, inputs.slice(start, start + MAX_UPLOAD_FILES), options));
1368
+ return uploaded;
1369
+ }
1370
+ async #uploadBatch(canvasId, inputs, options) {
1371
+ const prepared = await Promise.all(inputs.map(async (input) => {
1372
+ const bytes = input.data instanceof Blob ? new Uint8Array(await input.data.arrayBuffer()) : new Uint8Array(input.data);
1373
+ const contentType = input.contentType || (input.data instanceof Blob ? input.data.type : "");
1374
+ if (!contentType) throw new FuserError(`${input.fileName} needs a contentType.`, { tool: "upload_start" });
1375
+ const digest = await crypto.subtle.digest("SHA-256", bytes);
1376
+ return {
1377
+ bytes,
1378
+ file: {
1379
+ fileName: input.fileName,
1380
+ contentType,
1381
+ size: bytes.byteLength,
1382
+ sha256: base64(new Uint8Array(digest))
1383
+ }
1384
+ };
1385
+ }));
1386
+ const started = await this.upload.start({
1387
+ canvasId,
1388
+ files: prepared.map((item) => item.file)
1389
+ }, options);
1390
+ const sent = /* @__PURE__ */ new Set();
1391
+ const putErrors = [];
1392
+ await Promise.all(started.files.map(async (file, index) => {
1393
+ if (file.status === "done" || sent.has(file.url)) return;
1394
+ sent.add(file.url);
1395
+ const timeout = AbortSignal.timeout(options?.timeoutMs ?? this.#timeoutMs);
1396
+ try {
1397
+ const response = await this.#fetch(file.url, {
1398
+ method: file.method,
1399
+ headers: file.headers,
1400
+ body: prepared[index].bytes,
1401
+ signal: withSignal(options?.signal, timeout)
1402
+ });
1403
+ if (!response.ok && response.status !== 412) putErrors[index] = `Uploading ${file.fileName} failed (HTTP ${String(response.status)}).`;
1404
+ } catch {
1405
+ options?.signal?.throwIfAborted();
1406
+ putErrors[index] = timeout.aborted ? `Uploading ${file.fileName} timed out.` : `Uploading ${file.fileName} failed: the connection dropped.`;
1407
+ }
1408
+ }));
1409
+ return (await this.upload.finish({ uploadId: started.uploadId }, options)).files.map((file, index) => file.status === "failed" && putErrors[index] ? {
1410
+ ...file,
1411
+ error: putErrors[index]
1412
+ } : file);
1413
+ }
1414
+ async #request(key, args, options = {}) {
1415
+ const tool = toSnake(key);
1416
+ const operation = OPERATIONS[key];
1417
+ const policy = typeof operation.retry === "function" ? operation.retry(args) : operation.retry;
1418
+ const body = key === "canvasEdit" || key === "runStart" && !args.dryRun ? {
1419
+ ...args,
1420
+ idempotencyKey: args.idempotencyKey ?? crypto.randomUUID()
1421
+ } : args;
1422
+ const send = sdk_gen_exports[key];
1423
+ const waitSeconds = Math.min(args?.waitSeconds ?? (key === "toolBuild" ? MAX_WAIT_SECONDS : 0), MAX_WAIT_SECONDS);
1424
+ const timeoutMs = (options.timeoutMs ?? this.#timeoutMs) + waitSeconds * 1e3;
1425
+ const maxRetries = options.maxRetries ?? this.#maxRetries;
1426
+ for (let attempt = 0;; attempt++) {
1427
+ const timeout = AbortSignal.timeout(timeoutMs);
1428
+ const result = await send({
1429
+ client: this.client,
1430
+ ...body === void 0 ? {} : { [operation.in]: body },
1431
+ ...options.headers ? { headers: options.headers } : {},
1432
+ signal: withSignal(options.signal, timeout)
1433
+ });
1434
+ if (result.error === void 0 && result.response?.ok) return result.data;
1435
+ options.signal?.throwIfAborted();
1436
+ const error = result.response && !result.response.ok ? errorFromResponse(tool, result.response, result.error) : timeout.aborted ? new TimeoutError(`${tool} timed out.`, {
1437
+ tool,
1438
+ cause: result.error
1439
+ }) : new ConnectionError(`${tool} could not reach Fuser.`, {
1440
+ tool,
1441
+ cause: result.error
1442
+ });
1443
+ const retryable = error.status === void 0 ? policy === "transient" : policy === "transient" ? RETRYABLE_STATUSES.has(error.status) : error.status === 429;
1444
+ const delay = error.retryAfterMs ?? Math.min(8e3, 500 * 2 ** attempt) * (.75 + Math.random() / 2);
1445
+ if (!retryable || attempt >= maxRetries || delay > MAX_RETRY_DELAY_MS) throw error;
1446
+ await sleep(delay, options.signal);
1447
+ }
1448
+ }
1449
+ };
1450
+ //#endregion
1451
+ export { AuthenticationError, BadRequestError, ConflictError, ConnectionError, Fuser, FuserError, InternalServerError, NotFoundError, PagePromise, PermissionDeniedError, RateLimitError, RunCall, RunRefusedError, TimeoutError, ToolBuildCall };
1452
+
1453
+ //# sourceMappingURL=index.js.map