@mynthio/sdk 0.0.41 → 0.0.42

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/README.md CHANGED
@@ -136,6 +136,22 @@ if (status.status === "completed") {
136
136
  }
137
137
  ```
138
138
 
139
+ ### Cancelling
140
+
141
+ Pass an `AbortSignal` to stop waiting, for example when the incoming request disconnects:
142
+
143
+ ```ts
144
+ const task = await mynth.image.generate(
145
+ { prompt: "A lighthouse in a storm" },
146
+ { signal: AbortSignal.timeout(60_000) },
147
+ );
148
+
149
+ // Or on an async task:
150
+ const completedTask = await taskAsync.wait({ signal: request.signal });
151
+ ```
152
+
153
+ An abort cancels pending uploads and API requests and stops polling, and the call rejects with the signal's reason. A task that was already created keeps running on Mynth. For `generateAsync()`, the signal covers the upload and the create request; pass one to `wait()` to abort the wait. When several `wait()` calls share a task, polling stops only after every one of them has aborted.
154
+
139
155
  ## Request Shape
140
156
 
141
157
  `generate()` accepts a typed `ImageGenerationRequest`. The simplest request is just a prompt:
@@ -525,7 +541,7 @@ console.log(model);
525
541
  // {
526
542
  // id: "google/gemini-3.1-flash-image",
527
543
  // label: "Nano Banana 2",
528
- // capabilities: ["inputs", "4k", "native_enhance_prompt"]
544
+ // capabilities: ["inputs", "4k"]
529
545
  // }
530
546
  ```
531
547
 
package/dist/index.d.ts CHANGED
@@ -14,6 +14,7 @@ type MynthClientRequestOptions = {
14
14
  headers?: Record<string, string>;
15
15
  accessToken?: string | undefined;
16
16
  auth?: boolean | undefined;
17
+ signal?: AbortSignal | undefined;
17
18
  };
18
19
  /**
19
20
  * Internal HTTP client for making API requests.
@@ -26,10 +27,10 @@ declare class MynthClient {
26
27
  apiKey?: string | undefined;
27
28
  baseUrl?: string | undefined;
28
29
  });
29
- getAuthHeaders(override?: Omit<MynthClientRequestOptions, "headers">): Record<string, string>;
30
+ getAuthHeaders(override?: Pick<MynthClientRequestOptions, "accessToken" | "auth">): Record<string, string>;
30
31
  getUrl(path: string): string;
31
- post<DataType>(path: string, data: unknown): Promise<DataType>;
32
- get<DataType>(path: string, { headers, accessToken, auth }?: MynthClientRequestOptions): Promise<{
32
+ post<DataType>(path: string, data: unknown, { signal }?: Pick<MynthClientRequestOptions, "signal">): Promise<DataType>;
33
+ get<DataType>(path: string, { headers, accessToken, auth, signal }?: MynthClientRequestOptions): Promise<{
33
34
  data: DataType;
34
35
  status: number;
35
36
  ok: boolean;
@@ -230,6 +231,17 @@ export declare class TaskAsyncTaskFetchError extends Error {
230
231
  export declare class TaskAsyncTaskFailedError extends Error {
231
232
  constructor(taskId: string);
232
233
  }
234
+ /**
235
+ * Options for {@link TaskAsync.wait}.
236
+ */
237
+ type TaskAsyncWaitOptions = {
238
+ /**
239
+ * Stops this wait when aborted, rejecting with the signal's reason. Polling
240
+ * stops as well once no other `wait()` call is still waiting on the task.
241
+ * Aborting never cancels the task itself: Mynth keeps generating it.
242
+ */
243
+ signal?: AbortSignal | undefined;
244
+ };
233
245
  /**
234
246
  * Public access information for a task, used for client-side polling.
235
247
  */
@@ -250,7 +262,7 @@ export declare class TaskAsync<ResultT> {
250
262
  private readonly _access;
251
263
  private readonly resultFactory;
252
264
  private readonly polling;
253
- private _completionPromise;
265
+ private poll;
254
266
  constructor(id: string, options: {
255
267
  client: MynthClient;
256
268
  pat?: string | undefined;
@@ -265,15 +277,17 @@ export declare class TaskAsync<ResultT> {
265
277
  toString(): string;
266
278
  /**
267
279
  * Polls the task until completion and returns the typed result.
268
- * Multiple calls to this method return the same promise.
280
+ * Concurrent calls share one polling loop and settle with the same result.
269
281
  *
282
+ * @param options.signal - Stops this wait when aborted (see {@link TaskAsyncWaitOptions})
270
283
  * @throws {TaskAsyncTimeoutError} If polling exceeds the timeout
271
284
  * @throws {TaskAsyncUnauthorizedError} If access is denied
272
285
  * @throws {TaskAsyncFetchError} If fetching status fails repeatedly
273
286
  * @throws {TaskAsyncTaskFetchError} If fetching the completed task fails
274
287
  * @throws {TaskAsyncTaskFailedError} If the task fails before completion
275
288
  */
276
- wait(): Promise<ResultT>;
289
+ wait({ signal }?: TaskAsyncWaitOptions): Promise<ResultT>;
290
+ private startPoll;
277
291
  private pollUntilCompleted;
278
292
  private fetchStatus;
279
293
  private fetchTask;
@@ -346,6 +360,17 @@ type MynthOptions = {
346
360
  */
347
361
  destination?: string | undefined;
348
362
  };
363
+ /**
364
+ * Per-call options for SDK methods that talk to the API.
365
+ */
366
+ type MynthRequestOptions = {
367
+ /**
368
+ * Aborts the call: pending uploads and API requests are cancelled, and a
369
+ * method that waits for completion stops polling. A task that was already
370
+ * created keeps running on Mynth.
371
+ */
372
+ signal?: AbortSignal | undefined;
373
+ };
349
374
  type MynthModel = MynthSDKTypes.Model;
350
375
  type MynthModelPricing = MynthSDKTypes.ModelPricing;
351
376
  type ExtractMetadata<T extends MynthSDKTypes.ImageGenerationClientRequest> = T["metadata"];
@@ -416,6 +441,7 @@ declare class MynthImage {
416
441
  * Generate images from a text prompt.
417
442
  *
418
443
  * @param request - Image generation request parameters
444
+ * @param options.signal - Aborts the upload, the create request, or the wait for completion
419
445
  * @returns A completed ImageGenerationResult with the generation results
420
446
  *
421
447
  * @example
@@ -427,7 +453,7 @@ declare class MynthImage {
427
453
  * console.log(result.urls);
428
454
  * ```
429
455
  */
430
- generate<const T extends MynthSDKTypes.ImageGenerationClientRequest>(request: T): Promise<ImageGenerationResult<ExtractMetadata<T>, ExtractRatingResponse<T>>>;
456
+ generate<const T extends MynthSDKTypes.ImageGenerationClientRequest>(request: T, options?: MynthRequestOptions): Promise<ImageGenerationResult<ExtractMetadata<T>, ExtractRatingResponse<T>>>;
431
457
  /**
432
458
  * Upload one or more images to Mynth temporary input storage.
433
459
  *
@@ -447,6 +473,7 @@ declare class MynthImage {
447
473
  * Start image generation without waiting for completion.
448
474
  *
449
475
  * @param request - Image generation request parameters
476
+ * @param options.signal - Aborts the upload or the create request. Pass a signal to `.wait()` to abort the wait.
450
477
  * @returns A TaskAsync that can be polled for completion via `.wait()`
451
478
  *
452
479
  * @example
@@ -458,7 +485,7 @@ declare class MynthImage {
458
485
  * return { id: taskAsync.id, access: taskAsync.access };
459
486
  * ```
460
487
  */
461
- generateAsync<const T extends MynthSDKTypes.ImageGenerationClientRequest>(request: T): Promise<TaskAsync<ImageGenerationResult<ExtractMetadata<T>, ExtractRatingResponse<T>>>>;
488
+ generateAsync<const T extends MynthSDKTypes.ImageGenerationClientRequest>(request: T, options?: MynthRequestOptions): Promise<TaskAsync<ImageGenerationResult<ExtractMetadata<T>, ExtractRatingResponse<T>>>>;
462
489
  private createGenerationTask;
463
490
  /**
464
491
  * Rate the content of a single image.
@@ -760,4 +787,4 @@ declare class Mynth {
760
787
  get video(): MynthVideo;
761
788
  }
762
789
  //#endregion
763
- export { AVAILABLE_MODELS, AVAILABLE_VIDEO_MODELS, type AvailableModel, type AvailableVideoModel, type ModelCapability, Mynth, Mynth as default, MynthImage, type MynthModel, type MynthModelPricing, MynthModels, type MynthOptions, type MynthSDKTypes, MynthVideo, type TaskAsyncAccess, type VideoInputRole, type VideoResolutionTier };
790
+ export { AVAILABLE_MODELS, AVAILABLE_VIDEO_MODELS, type AvailableModel, type AvailableVideoModel, type ModelCapability, Mynth, Mynth as default, MynthImage, type MynthModel, type MynthModelPricing, MynthModels, type MynthOptions, type MynthRequestOptions, type MynthSDKTypes, MynthVideo, type TaskAsyncAccess, type TaskAsyncWaitOptions, type VideoInputRole, type VideoResolutionTier };
package/dist/index.js CHANGED
@@ -30,22 +30,22 @@ const AVAILABLE_MODELS = [
30
30
  {
31
31
  id: "alibaba/qwen-image-2.0",
32
32
  label: "Qwen Image 2.0",
33
- capabilities: ["inputs", "native_enhance_prompt"]
33
+ capabilities: ["inputs"]
34
34
  },
35
35
  {
36
36
  id: "alibaba/qwen-image-2.0-pro",
37
37
  label: "Qwen Image 2.0 Pro",
38
- capabilities: ["inputs", "native_enhance_prompt"]
38
+ capabilities: ["inputs"]
39
39
  },
40
40
  {
41
41
  id: "alibaba/qwen-image-3.0",
42
42
  label: "Qwen Image 3.0",
43
- capabilities: ["inputs", "native_enhance_prompt"]
43
+ capabilities: ["inputs"]
44
44
  },
45
45
  {
46
46
  id: "alibaba/qwen-image-3.0-pro",
47
47
  label: "Qwen Image 3.0 Pro",
48
- capabilities: ["inputs", "native_enhance_prompt"]
48
+ capabilities: ["inputs"]
49
49
  },
50
50
  {
51
51
  id: "bytedance/seedream-5.0-lite",
@@ -210,34 +210,22 @@ const AVAILABLE_MODELS = [
210
210
  {
211
211
  id: "sourceful/riverflow-2.0-pro",
212
212
  label: "Riverflow 2.0 Pro",
213
- capabilities: [
214
- "inputs",
215
- "4k",
216
- "native_enhance_prompt"
217
- ]
213
+ capabilities: ["inputs", "4k"]
218
214
  },
219
215
  {
220
216
  id: "google/gemini-3.1-flash-lite-image",
221
217
  label: "Nano Banana 2 Lite",
222
- capabilities: ["inputs", "native_enhance_prompt"]
218
+ capabilities: ["inputs"]
223
219
  },
224
220
  {
225
221
  id: "google/gemini-3.1-flash-image",
226
222
  label: "Nano Banana 2",
227
- capabilities: [
228
- "inputs",
229
- "4k",
230
- "native_enhance_prompt"
231
- ]
223
+ capabilities: ["inputs", "4k"]
232
224
  },
233
225
  {
234
226
  id: "google/gemini-3-pro-image-preview",
235
227
  label: "Nano Banana Pro",
236
- capabilities: [
237
- "inputs",
238
- "4k",
239
- "native_enhance_prompt"
240
- ]
228
+ capabilities: ["inputs", "4k"]
241
229
  },
242
230
  {
243
231
  id: "imagineart/imagineart-1.5-pro",
@@ -399,7 +387,7 @@ var MynthClient = class {
399
387
  getUrl(path) {
400
388
  return `${this.baseUrl}${path}`;
401
389
  }
402
- async post(path, data) {
390
+ async post(path, data, { signal } = {}) {
403
391
  const isFormData = typeof FormData !== "undefined" && data instanceof FormData;
404
392
  const response = await fetch(this.getUrl(path), {
405
393
  method: "POST",
@@ -407,20 +395,24 @@ var MynthClient = class {
407
395
  ...isFormData ? {} : { "Content-Type": "application/json" },
408
396
  ...this.getAuthHeaders()
409
397
  },
410
- body: isFormData ? data : JSON.stringify(data)
398
+ body: isFormData ? data : JSON.stringify(data),
399
+ ...signal ? { signal } : {}
411
400
  });
412
401
  const json = await response.json();
413
402
  if (!response.ok) throw createApiError(json, response.status);
414
403
  return json;
415
404
  }
416
- async get(path, { headers, accessToken, auth } = {}) {
417
- const response = await fetch(this.getUrl(path), { headers: {
418
- ...this.getAuthHeaders({
419
- accessToken,
420
- auth
421
- }),
422
- ...headers
423
- } });
405
+ async get(path, { headers, accessToken, auth, signal } = {}) {
406
+ const response = await fetch(this.getUrl(path), {
407
+ headers: {
408
+ ...this.getAuthHeaders({
409
+ accessToken,
410
+ auth
411
+ }),
412
+ ...headers
413
+ },
414
+ ...signal ? { signal } : {}
415
+ });
424
416
  return {
425
417
  data: await response.json(),
426
418
  status: response.status,
@@ -683,7 +675,7 @@ var TaskAsync = class {
683
675
  _access;
684
676
  resultFactory;
685
677
  polling;
686
- _completionPromise = null;
678
+ poll = null;
687
679
  constructor(id, options) {
688
680
  this.id = id;
689
681
  this.client = options.client;
@@ -708,19 +700,54 @@ var TaskAsync = class {
708
700
  }
709
701
  /**
710
702
  * Polls the task until completion and returns the typed result.
711
- * Multiple calls to this method return the same promise.
703
+ * Concurrent calls share one polling loop and settle with the same result.
712
704
  *
705
+ * @param options.signal - Stops this wait when aborted (see {@link TaskAsyncWaitOptions})
713
706
  * @throws {TaskAsyncTimeoutError} If polling exceeds the timeout
714
707
  * @throws {TaskAsyncUnauthorizedError} If access is denied
715
708
  * @throws {TaskAsyncFetchError} If fetching status fails repeatedly
716
709
  * @throws {TaskAsyncTaskFetchError} If fetching the completed task fails
717
710
  * @throws {TaskAsyncTaskFailedError} If the task fails before completion
718
711
  */
719
- async wait() {
720
- if (!this._completionPromise) this._completionPromise = this.pollUntilCompleted();
721
- return this._completionPromise;
712
+ async wait({ signal } = {}) {
713
+ signal?.throwIfAborted();
714
+ const poll = this.poll ??= this.startPoll();
715
+ if (!signal) {
716
+ poll.pinned = true;
717
+ return poll.promise;
718
+ }
719
+ poll.abortableWaiters++;
720
+ return new Promise((resolve, reject) => {
721
+ const onAbort = () => {
722
+ poll.abortableWaiters--;
723
+ reject(signal.reason);
724
+ if (poll.abortableWaiters === 0 && !poll.pinned) {
725
+ poll.controller.abort(signal.reason);
726
+ if (this.poll === poll) this.poll = null;
727
+ }
728
+ };
729
+ signal.addEventListener("abort", onAbort, { once: true });
730
+ poll.promise.then((result) => {
731
+ signal.removeEventListener("abort", onAbort);
732
+ resolve(result);
733
+ }, (error) => {
734
+ signal.removeEventListener("abort", onAbort);
735
+ reject(error);
736
+ });
737
+ });
722
738
  }
723
- async pollUntilCompleted() {
739
+ startPoll() {
740
+ const controller = new AbortController();
741
+ const promise = this.pollUntilCompleted(controller.signal);
742
+ promise.catch(() => {});
743
+ return {
744
+ promise,
745
+ controller,
746
+ abortableWaiters: 0,
747
+ pinned: false
748
+ };
749
+ }
750
+ async pollUntilCompleted(signal) {
724
751
  const { timeoutMs, fastDurationMs, fastIntervalMs, intervalMs } = this.polling;
725
752
  const startTime = Date.now();
726
753
  let retryCount = 0;
@@ -729,10 +756,10 @@ var TaskAsync = class {
729
756
  while (true) {
730
757
  const elapsed = Date.now() - startTime;
731
758
  if (elapsed >= timeoutMs) throw new TaskAsyncTimeoutError(this.id, timeoutMs);
732
- const result = await this.fetchStatus(useApiKeyFallback);
759
+ const result = await this.fetchStatus(useApiKeyFallback, signal);
733
760
  if (result.ok) {
734
761
  if (result.status === "completed") {
735
- const fetched = await this.fetchTask();
762
+ const fetched = await this.fetchTask(signal);
736
763
  if (fetched.ok) return this.resultFactory(fetched.data);
737
764
  if (fetched.unauthorized) throw new TaskAsyncUnauthorizedError(this.id);
738
765
  retryCount++;
@@ -754,13 +781,16 @@ var TaskAsync = class {
754
781
  const interval = (elapsed < fastDurationMs ? fastIntervalMs : intervalMs) + Math.random() * 500;
755
782
  const remainingTime = timeoutMs - elapsed;
756
783
  const waitTime = Math.min(interval, remainingTime);
757
- await this.sleep(waitTime);
784
+ await this.sleep(waitTime, signal);
758
785
  }
759
786
  }
760
- async fetchStatus(useApiKey) {
787
+ async fetchStatus(useApiKey, signal) {
761
788
  const accessToken = useApiKey || !this._access.publicAccessToken ? void 0 : this._access.publicAccessToken;
762
789
  try {
763
- const response = await this.client.get(TASK_STATUS_PATH(this.id), { accessToken });
790
+ const response = await this.client.get(TASK_STATUS_PATH(this.id), {
791
+ accessToken,
792
+ signal
793
+ });
764
794
  if (response.ok) return {
765
795
  ok: true,
766
796
  status: response.data.data.status
@@ -787,6 +817,7 @@ var TaskAsync = class {
787
817
  retryable: false
788
818
  };
789
819
  } catch (error) {
820
+ signal.throwIfAborted();
790
821
  return {
791
822
  ok: false,
792
823
  unauthorized: false,
@@ -795,9 +826,9 @@ var TaskAsync = class {
795
826
  };
796
827
  }
797
828
  }
798
- async fetchTask() {
829
+ async fetchTask(signal) {
799
830
  try {
800
- const response = await this.client.get(TASK_DETAILS_PATH(this.id));
831
+ const response = await this.client.get(TASK_DETAILS_PATH(this.id), { signal });
801
832
  if (response.ok) return {
802
833
  ok: true,
803
834
  data: response.data.data
@@ -820,6 +851,7 @@ var TaskAsync = class {
820
851
  status: response.status
821
852
  };
822
853
  } catch (error) {
854
+ signal.throwIfAborted();
823
855
  return {
824
856
  ok: false,
825
857
  unauthorized: false,
@@ -828,8 +860,19 @@ var TaskAsync = class {
828
860
  };
829
861
  }
830
862
  }
831
- sleep(ms) {
832
- return new Promise((resolve) => setTimeout(resolve, ms));
863
+ sleep(ms, signal) {
864
+ return new Promise((resolve, reject) => {
865
+ signal.throwIfAborted();
866
+ const onAbort = () => {
867
+ clearTimeout(timer);
868
+ reject(signal.reason);
869
+ };
870
+ const timer = setTimeout(() => {
871
+ signal.removeEventListener("abort", onAbort);
872
+ resolve();
873
+ }, ms);
874
+ signal.addEventListener("abort", onAbort, { once: true });
875
+ });
833
876
  }
834
877
  };
835
878
  //#endregion
@@ -843,25 +886,25 @@ function isUploadInput(value) {
843
886
  * Upload images to Mynth temporary input storage.
844
887
  * Image and video generation share this endpoint: video inputs are images.
845
888
  */
846
- async function uploadImages(client, input) {
889
+ async function uploadImages(client, input, { signal } = {}) {
847
890
  const form = new FormData();
848
891
  const inputs = Array.isArray(input) ? input : [input];
849
892
  for (const upload of inputs) form.append(UPLOAD_FIELD_NAME, upload, typeof File !== "undefined" && upload instanceof File ? upload.name : UPLOAD_FILENAME);
850
- return (await client.post(UPLOAD_IMAGE_PATH, form)).data;
893
+ return (await client.post(UPLOAD_IMAGE_PATH, form, { signal })).data;
851
894
  }
852
895
  /**
853
896
  * Turn caller inputs into wire inputs, uploading any local files first.
854
897
  * All files go up in a single request, and the returned URLs are slotted back
855
898
  * into their original positions so input order (and role) is preserved.
856
899
  */
857
- async function resolveInputs(client, inputs) {
900
+ async function resolveInputs(client, inputs, { signal } = {}) {
858
901
  if (!inputs?.length) return;
859
902
  const files = inputs.flatMap((input) => {
860
903
  if (isUploadInput(input)) return [input];
861
904
  if (typeof input !== "string" && input.source.type === "file") return [input.source.file];
862
905
  return [];
863
906
  });
864
- const urls = files.length ? (await uploadImages(client, files)).urls : [];
907
+ const urls = files.length ? (await uploadImages(client, files, { signal })).urls : [];
865
908
  let i = 0;
866
909
  return inputs.map((input) => {
867
910
  if (typeof input === "string") return input;
@@ -995,6 +1038,7 @@ var MynthImage = class {
995
1038
  * Generate images from a text prompt.
996
1039
  *
997
1040
  * @param request - Image generation request parameters
1041
+ * @param options.signal - Aborts the upload, the create request, or the wait for completion
998
1042
  * @returns A completed ImageGenerationResult with the generation results
999
1043
  *
1000
1044
  * @example
@@ -1006,8 +1050,8 @@ var MynthImage = class {
1006
1050
  * console.log(result.urls);
1007
1051
  * ```
1008
1052
  */
1009
- async generate(request) {
1010
- return (await this.createGenerationTask(request)).wait();
1053
+ async generate(request, options = {}) {
1054
+ return (await this.createGenerationTask(request, options)).wait(options);
1011
1055
  }
1012
1056
  /**
1013
1057
  * Upload one or more images to Mynth temporary input storage.
@@ -1030,6 +1074,7 @@ var MynthImage = class {
1030
1074
  * Start image generation without waiting for completion.
1031
1075
  *
1032
1076
  * @param request - Image generation request parameters
1077
+ * @param options.signal - Aborts the upload or the create request. Pass a signal to `.wait()` to abort the wait.
1033
1078
  * @returns A TaskAsync that can be polled for completion via `.wait()`
1034
1079
  *
1035
1080
  * @example
@@ -1041,16 +1086,16 @@ var MynthImage = class {
1041
1086
  * return { id: taskAsync.id, access: taskAsync.access };
1042
1087
  * ```
1043
1088
  */
1044
- async generateAsync(request) {
1045
- return this.createGenerationTask(request);
1089
+ async generateAsync(request, options = {}) {
1090
+ return this.createGenerationTask(request, options);
1046
1091
  }
1047
- async createGenerationTask(request) {
1048
- const inputs = await resolveInputs(this.client, request.inputs);
1092
+ async createGenerationTask(request, { signal }) {
1093
+ const inputs = await resolveInputs(this.client, request.inputs, { signal });
1049
1094
  const data = (await this.client.post(GENERATE_IMAGE_PATH, {
1050
1095
  ...request,
1051
1096
  inputs,
1052
1097
  destination: request.destination ?? this.defaultDestination
1053
- })).data;
1098
+ }, { signal })).data;
1054
1099
  return new TaskAsync(data.taskId, {
1055
1100
  client: this.client,
1056
1101
  pat: data.access?.publicAccessToken,
package/dist/types.d.ts CHANGED
@@ -4,9 +4,8 @@
4
4
  * - `negative_prompt`: Supports structured negative prompts
5
5
  * - `inputs`: Supports input images
6
6
  * - `4k`: Supports 4k resolution output
7
- * - `native_enhance_prompt`: Supports provider-native prompt enhancement
8
7
  */
9
- type ModelCapability = "inputs" | "negative_prompt" | "4k" | "native_enhance_prompt";
8
+ type ModelCapability = "inputs" | "negative_prompt" | "4k";
10
9
  /**
11
10
  * Information about an available image generation model.
12
11
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mynthio/sdk",
3
- "version": "0.0.41",
3
+ "version": "0.0.42",
4
4
  "description": "Official Mynth SDK for image generation and analysis",
5
5
  "keywords": [
6
6
  "ai",