@runware/sdk-js 1.1.9 → 1.1.11

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.
@@ -0,0 +1,1064 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __defProps = Object.defineProperties;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
+ var __getProtoOf = Object.getPrototypeOf;
9
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
10
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
11
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
12
+ var __spreadValues = (a, b) => {
13
+ for (var prop in b || (b = {}))
14
+ if (__hasOwnProp.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ if (__getOwnPropSymbols)
17
+ for (var prop of __getOwnPropSymbols(b)) {
18
+ if (__propIsEnum.call(b, prop))
19
+ __defNormalProp(a, prop, b[prop]);
20
+ }
21
+ return a;
22
+ };
23
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
24
+ var __esm = (fn, res) => function __init() {
25
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
26
+ };
27
+ var __commonJS = (cb, mod) => function __require() {
28
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
29
+ };
30
+ var __export = (target, all) => {
31
+ for (var name in all)
32
+ __defProp(target, name, { get: all[name], enumerable: true });
33
+ };
34
+ var __copyProps = (to, from, except, desc) => {
35
+ if (from && typeof from === "object" || typeof from === "function") {
36
+ for (let key of __getOwnPropNames(from))
37
+ if (!__hasOwnProp.call(to, key) && key !== except)
38
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
39
+ }
40
+ return to;
41
+ };
42
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
43
+ // If the importer is in node compatibility mode or this is not an ESM
44
+ // file that has been converted to a CommonJS file using a Babel-
45
+ // compatible transform (i.e. "__esModule" has not been set), then set
46
+ // "default" to the CommonJS "module.exports" for node compatibility.
47
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
48
+ mod
49
+ ));
50
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
51
+
52
+ // Runware/types.ts
53
+ var Environment, SdkType, ETaskType, EControlMode, EPreProcessorGroup, EPreProcessor, EOpenPosePreProcessor;
54
+ var init_types = __esm({
55
+ "Runware/types.ts"() {
56
+ "use strict";
57
+ Environment = /* @__PURE__ */ ((Environment2) => {
58
+ Environment2["PRODUCTION"] = "PRODUCTION";
59
+ Environment2["DEVELOPMENT"] = "DEVELOPMENT";
60
+ Environment2["TEST"] = "TEST";
61
+ return Environment2;
62
+ })(Environment || {});
63
+ SdkType = /* @__PURE__ */ ((SdkType2) => {
64
+ SdkType2["CLIENT"] = "CLIENT";
65
+ SdkType2["SERVER"] = "SERVER";
66
+ return SdkType2;
67
+ })(SdkType || {});
68
+ ETaskType = /* @__PURE__ */ ((ETaskType2) => {
69
+ ETaskType2["IMAGE_INFERENCE"] = "imageInference";
70
+ ETaskType2["IMAGE_UPLOAD"] = "imageUpload";
71
+ ETaskType2["IMAGE_UPSCALE"] = "imageUpscale";
72
+ ETaskType2["IMAGE_BACKGROUND_REMOVAL"] = "imageBackgroundRemoval";
73
+ ETaskType2["IMAGE_CAPTION"] = "imageCaption";
74
+ ETaskType2["IMAGE_CONTROL_NET_PRE_PROCESS"] = "imageControlNetPreProcess";
75
+ ETaskType2["PROMPT_ENHANCE"] = "promptEnhance";
76
+ ETaskType2["AUTHENTICATION"] = "authentication";
77
+ return ETaskType2;
78
+ })(ETaskType || {});
79
+ EControlMode = /* @__PURE__ */ ((EControlMode2) => {
80
+ EControlMode2["BALANCED"] = "balanced";
81
+ EControlMode2["PROMPT"] = "prompt";
82
+ EControlMode2["CONTROL_NET"] = "controlnet";
83
+ return EControlMode2;
84
+ })(EControlMode || {});
85
+ EPreProcessorGroup = /* @__PURE__ */ ((EPreProcessorGroup3) => {
86
+ EPreProcessorGroup3["canny"] = "canny";
87
+ EPreProcessorGroup3["depth"] = "depth";
88
+ EPreProcessorGroup3["mlsd"] = "mlsd";
89
+ EPreProcessorGroup3["normalbae"] = "normalbae";
90
+ EPreProcessorGroup3["openpose"] = "openpose";
91
+ EPreProcessorGroup3["tile"] = "tile";
92
+ EPreProcessorGroup3["seg"] = "seg";
93
+ EPreProcessorGroup3["lineart"] = "lineart";
94
+ EPreProcessorGroup3["lineart_anime"] = "lineart_anime";
95
+ EPreProcessorGroup3["shuffle"] = "shuffle";
96
+ EPreProcessorGroup3["scribble"] = "scribble";
97
+ EPreProcessorGroup3["softedge"] = "softedge";
98
+ return EPreProcessorGroup3;
99
+ })(EPreProcessorGroup || {});
100
+ EPreProcessor = /* @__PURE__ */ ((EPreProcessor3) => {
101
+ EPreProcessor3["canny"] = "canny";
102
+ EPreProcessor3["depth_leres"] = "depth_leres";
103
+ EPreProcessor3["depth_midas"] = "depth_midas";
104
+ EPreProcessor3["depth_zoe"] = "depth_zoe";
105
+ EPreProcessor3["inpaint_global_harmonious"] = "inpaint_global_harmonious";
106
+ EPreProcessor3["lineart_anime"] = "lineart_anime";
107
+ EPreProcessor3["lineart_coarse"] = "lineart_coarse";
108
+ EPreProcessor3["lineart_realistic"] = "lineart_realistic";
109
+ EPreProcessor3["lineart_standard"] = "lineart_standard";
110
+ EPreProcessor3["mlsd"] = "mlsd";
111
+ EPreProcessor3["normal_bae"] = "normal_bae";
112
+ EPreProcessor3["scribble_hed"] = "scribble_hed";
113
+ EPreProcessor3["scribble_pidinet"] = "scribble_pidinet";
114
+ EPreProcessor3["seg_ofade20k"] = "seg_ofade20k";
115
+ EPreProcessor3["seg_ofcoco"] = "seg_ofcoco";
116
+ EPreProcessor3["seg_ufade20k"] = "seg_ufade20k";
117
+ EPreProcessor3["shuffle"] = "shuffle";
118
+ EPreProcessor3["softedge_hed"] = "softedge_hed";
119
+ EPreProcessor3["softedge_hedsafe"] = "softedge_hedsafe";
120
+ EPreProcessor3["softedge_pidinet"] = "softedge_pidinet";
121
+ EPreProcessor3["softedge_pidisafe"] = "softedge_pidisafe";
122
+ EPreProcessor3["tile_gaussian"] = "tile_gaussian";
123
+ EPreProcessor3["openpose"] = "openpose";
124
+ EPreProcessor3["openpose_face"] = "openpose_face";
125
+ EPreProcessor3["openpose_faceonly"] = "openpose_faceonly";
126
+ EPreProcessor3["openpose_full"] = "openpose_full";
127
+ EPreProcessor3["openpose_hand"] = "openpose_hand";
128
+ return EPreProcessor3;
129
+ })(EPreProcessor || {});
130
+ EOpenPosePreProcessor = /* @__PURE__ */ ((EOpenPosePreProcessor2) => {
131
+ EOpenPosePreProcessor2["openpose"] = "openpose";
132
+ EOpenPosePreProcessor2["openpose_face"] = "openpose_face";
133
+ EOpenPosePreProcessor2["openpose_faceonly"] = "openpose_faceonly";
134
+ EOpenPosePreProcessor2["openpose_full"] = "openpose_full";
135
+ EOpenPosePreProcessor2["openpose_hand"] = "openpose_hand";
136
+ return EOpenPosePreProcessor2;
137
+ })(EOpenPosePreProcessor || {});
138
+ }
139
+ });
140
+
141
+ // Runware/utils.ts
142
+ import { v4 as uuidv4, validate as validateUUID } from "uuid";
143
+ var TIMEOUT_DURATION, POLLING_INTERVAL, BASE_RUNWARE_URLS, removeFromAray, getIntervalWithPromise, fileToBase64, getUUID, isValidUUID, accessDeepObject, delay, removeListener, evaluateNonTrue;
144
+ var init_utils = __esm({
145
+ "Runware/utils.ts"() {
146
+ "use strict";
147
+ init_types();
148
+ TIMEOUT_DURATION = 6e4;
149
+ POLLING_INTERVAL = 100;
150
+ BASE_RUNWARE_URLS = {
151
+ ["PRODUCTION" /* PRODUCTION */]: "wss://ws-api.runware.ai/v1",
152
+ ["TEST" /* TEST */]: "ws://localhost:8080"
153
+ };
154
+ removeFromAray = (col, targetElem) => {
155
+ if (col == null) {
156
+ return;
157
+ }
158
+ let i = col.indexOf(targetElem);
159
+ if (i === -1) {
160
+ return;
161
+ }
162
+ col.splice(i, 1);
163
+ };
164
+ getIntervalWithPromise = (callback, {
165
+ debugKey = "debugKey",
166
+ timeOutDuration = TIMEOUT_DURATION,
167
+ shouldThrowError = true
168
+ }) => {
169
+ return new Promise((resolve, reject) => {
170
+ const timeoutId = setTimeout(() => {
171
+ if (intervalId) {
172
+ clearInterval(intervalId);
173
+ if (shouldThrowError) {
174
+ reject(`Message could not be received for ${debugKey}`);
175
+ console.error("Message could not be received for ", debugKey);
176
+ }
177
+ }
178
+ clearTimeout(timeoutId);
179
+ }, timeOutDuration);
180
+ let intervalId = setInterval(async () => {
181
+ const shouldClear = callback({ resolve, reject, intervalId });
182
+ if (shouldClear) {
183
+ clearInterval(intervalId);
184
+ clearTimeout(timeoutId);
185
+ }
186
+ }, POLLING_INTERVAL);
187
+ });
188
+ };
189
+ fileToBase64 = (file) => new Promise((resolve) => {
190
+ const reader = new FileReader();
191
+ reader.readAsDataURL(file);
192
+ reader.onload = function() {
193
+ resolve(reader.result);
194
+ };
195
+ });
196
+ getUUID = () => uuidv4();
197
+ isValidUUID = (uuid) => validateUUID(uuid);
198
+ accessDeepObject = ({
199
+ key,
200
+ data,
201
+ useZero = true,
202
+ shouldReturnString = false
203
+ }) => {
204
+ const splittedKeys = key.split(/\.|\[/).map((key2) => key2.replace(/\]$/, ""));
205
+ const value = splittedKeys.reduce((acc, curr) => {
206
+ var _a, _b;
207
+ const returnZero = useZero ? 0 : void 0;
208
+ const currentValue = acc == null ? void 0 : acc[curr];
209
+ if (!currentValue) {
210
+ return returnZero;
211
+ }
212
+ if (Array.isArray(currentValue) && /^\d+$/.test(curr)) {
213
+ const index = parseInt(curr, 10);
214
+ if (index >= 0 && index < currentValue.length) {
215
+ return acc[curr] = currentValue[index];
216
+ } else {
217
+ return (_a = acc[curr]) != null ? _a : returnZero;
218
+ }
219
+ } else {
220
+ return (_b = acc[curr]) != null ? _b : returnZero;
221
+ }
222
+ }, data || {});
223
+ return value != null ? value : {};
224
+ };
225
+ delay = (time, milliseconds = 1e3) => {
226
+ return new Promise((resolve) => setTimeout(resolve, time * milliseconds));
227
+ };
228
+ removeListener = (listeners, listener) => {
229
+ return listeners.filter((lis) => lis.key !== listener.key);
230
+ };
231
+ evaluateNonTrue = ({
232
+ key,
233
+ value
234
+ }) => {
235
+ if (!!value || value === 0 || value === false) {
236
+ return { [key]: value };
237
+ } else {
238
+ return {};
239
+ }
240
+ };
241
+ }
242
+ });
243
+
244
+ // Runware/async-retry.ts
245
+ var asyncRetry;
246
+ var init_async_retry = __esm({
247
+ "Runware/async-retry.ts"() {
248
+ "use strict";
249
+ init_utils();
250
+ asyncRetry = async (apiCall, options = {}) => {
251
+ var _a;
252
+ const { delayInSeconds = 1, callback } = options;
253
+ let maxRetries = (_a = options.maxRetries) != null ? _a : 1;
254
+ while (maxRetries) {
255
+ try {
256
+ const result = await apiCall();
257
+ return result;
258
+ } catch (error) {
259
+ callback == null ? void 0 : callback();
260
+ maxRetries--;
261
+ if (maxRetries > 0) {
262
+ await delay(delayInSeconds);
263
+ await asyncRetry(apiCall, __spreadProps(__spreadValues({}, options), { maxRetries }));
264
+ } else {
265
+ throw error;
266
+ }
267
+ }
268
+ }
269
+ };
270
+ }
271
+ });
272
+
273
+ // Runware/Runware-base.ts
274
+ var RunwareBase;
275
+ var init_Runware_base = __esm({
276
+ "Runware/Runware-base.ts"() {
277
+ init_async_retry();
278
+ init_types();
279
+ init_utils();
280
+ RunwareBase = class {
281
+ constructor({ apiKey, url = BASE_RUNWARE_URLS.PRODUCTION }) {
282
+ this._listeners = [];
283
+ // _globalMessages: any[] = [];
284
+ this._globalMessages = {};
285
+ this._globalImages = [];
286
+ this.isWebsocketReadyState = () => {
287
+ var _a;
288
+ return ((_a = this._ws) == null ? void 0 : _a.readyState) === 1;
289
+ };
290
+ // We moving to an array format, it make sense to consolidate all request to an array here
291
+ this.send = (msg) => {
292
+ this._ws.send(JSON.stringify([msg]));
293
+ };
294
+ this.uploadImage = async (file) => {
295
+ try {
296
+ return await asyncRetry(async () => {
297
+ const taskUUID = getUUID();
298
+ if (typeof file === "string" && isValidUUID(file)) {
299
+ return {
300
+ imageURL: file,
301
+ imageUUID: file,
302
+ taskUUID,
303
+ taskType: "imageUpload" /* IMAGE_UPLOAD */
304
+ };
305
+ }
306
+ const imageBase64 = typeof file === "string" ? file : await fileToBase64(file);
307
+ this.send({
308
+ taskType: "imageUpload" /* IMAGE_UPLOAD */,
309
+ image: imageBase64,
310
+ taskUUID
311
+ });
312
+ const lis = this.globalListener({
313
+ taskUUID
314
+ });
315
+ const image = await getIntervalWithPromise(
316
+ ({ resolve, reject }) => {
317
+ const uploadedImage = this.getSingleMessage({
318
+ taskUUID
319
+ });
320
+ if (!uploadedImage)
321
+ return;
322
+ if (uploadedImage == null ? void 0 : uploadedImage.error) {
323
+ reject(uploadedImage);
324
+ return true;
325
+ }
326
+ if (uploadedImage) {
327
+ delete this._globalMessages[taskUUID];
328
+ resolve(uploadedImage);
329
+ return true;
330
+ }
331
+ },
332
+ { debugKey: "upload-image" }
333
+ );
334
+ lis.destroy();
335
+ return image;
336
+ });
337
+ } catch (e) {
338
+ throw e;
339
+ }
340
+ };
341
+ this.controlNetPreProcess = async ({
342
+ inputImage,
343
+ preProcessor,
344
+ height,
345
+ width,
346
+ outputType,
347
+ outputFormat,
348
+ highThresholdCanny,
349
+ lowThresholdCanny,
350
+ includeHandsAndFaceOpenPose,
351
+ includeCost,
352
+ customTaskUUID
353
+ }) => {
354
+ try {
355
+ const image = await this.uploadImage(inputImage);
356
+ if (!(image == null ? void 0 : image.imageUUID))
357
+ return null;
358
+ const taskUUID = customTaskUUID || getUUID();
359
+ this.send(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
360
+ inputImage: image.imageUUID,
361
+ taskType: "imageControlNetPreProcess" /* IMAGE_CONTROL_NET_PRE_PROCESS */,
362
+ taskUUID,
363
+ preProcessor
364
+ }, evaluateNonTrue({ key: "height", value: height })), evaluateNonTrue({ key: "width", value: width })), evaluateNonTrue({ key: "outputType", value: outputType })), evaluateNonTrue({ key: "outputFormat", value: outputFormat })), evaluateNonTrue({ key: "includeCost", value: includeCost })), evaluateNonTrue({
365
+ key: "highThresholdCanny",
366
+ value: highThresholdCanny
367
+ })), evaluateNonTrue({
368
+ key: "lowThresholdCanny",
369
+ value: lowThresholdCanny
370
+ })), evaluateNonTrue({
371
+ key: "includeHandsAndFaceOpenPose",
372
+ value: includeHandsAndFaceOpenPose
373
+ })));
374
+ const lis = this.globalListener({
375
+ taskUUID
376
+ });
377
+ const guideImage = await getIntervalWithPromise(
378
+ ({ resolve, reject }) => {
379
+ const uploadedImage = this.getSingleMessage({
380
+ taskUUID
381
+ });
382
+ if (!uploadedImage)
383
+ return;
384
+ if (uploadedImage == null ? void 0 : uploadedImage.error) {
385
+ reject(uploadedImage);
386
+ return true;
387
+ }
388
+ if (uploadedImage) {
389
+ resolve(uploadedImage);
390
+ return true;
391
+ }
392
+ },
393
+ { debugKey: "unprocessed-image" }
394
+ );
395
+ lis.destroy();
396
+ return guideImage;
397
+ } catch (e) {
398
+ throw e;
399
+ }
400
+ };
401
+ this.requestImageToText = async ({
402
+ inputImage,
403
+ includeCost,
404
+ customTaskUUID
405
+ }) => {
406
+ try {
407
+ await this.ensureConnection();
408
+ return await asyncRetry(async () => {
409
+ const imageUploaded = await this.uploadImage(
410
+ inputImage
411
+ );
412
+ if (!(imageUploaded == null ? void 0 : imageUploaded.imageUUID))
413
+ return null;
414
+ const taskUUID = customTaskUUID || getUUID();
415
+ this.send(__spreadValues({
416
+ taskUUID,
417
+ taskType: "imageCaption" /* IMAGE_CAPTION */,
418
+ inputImage: imageUploaded.imageUUID
419
+ }, evaluateNonTrue({ key: "includeCost", value: includeCost })));
420
+ const lis = this.globalListener({
421
+ taskUUID
422
+ });
423
+ const response = await getIntervalWithPromise(
424
+ ({ resolve, reject }) => {
425
+ const newReverseClip = this.getSingleMessage({
426
+ taskUUID
427
+ });
428
+ if (!newReverseClip)
429
+ return;
430
+ if (newReverseClip == null ? void 0 : newReverseClip.error) {
431
+ reject(newReverseClip);
432
+ return true;
433
+ }
434
+ if (newReverseClip) {
435
+ delete this._globalMessages[taskUUID];
436
+ resolve(newReverseClip);
437
+ return true;
438
+ }
439
+ },
440
+ { debugKey: "remove-image-background" }
441
+ );
442
+ lis.destroy();
443
+ return response;
444
+ });
445
+ } catch (e) {
446
+ throw e;
447
+ }
448
+ };
449
+ this.removeImageBackground = async ({
450
+ inputImage,
451
+ outputType,
452
+ outputFormat,
453
+ rgba,
454
+ postProcessMask,
455
+ returnOnlyMask,
456
+ alphaMatting,
457
+ alphaMattingForegroundThreshold,
458
+ alphaMattingBackgroundThreshold,
459
+ alphaMattingErodeSize,
460
+ includeCost,
461
+ customTaskUUID
462
+ }) => {
463
+ try {
464
+ await this.ensureConnection();
465
+ return await asyncRetry(async () => {
466
+ const imageUploaded = inputImage ? await this.uploadImage(inputImage) : null;
467
+ const taskUUID = customTaskUUID || getUUID();
468
+ this.send(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
469
+ taskType: "imageBackgroundRemoval" /* IMAGE_BACKGROUND_REMOVAL */,
470
+ taskUUID,
471
+ inputImage: imageUploaded == null ? void 0 : imageUploaded.imageUUID
472
+ }, evaluateNonTrue({ key: "rgba", value: rgba })), evaluateNonTrue({
473
+ key: "postProcessMask",
474
+ value: postProcessMask
475
+ })), evaluateNonTrue({ key: "returnOnlyMask", value: returnOnlyMask })), evaluateNonTrue({ key: "alphaMatting", value: alphaMatting })), evaluateNonTrue({ key: "includeCost", value: includeCost })), evaluateNonTrue({
476
+ key: "alphaMattingForegroundThreshold",
477
+ value: alphaMattingForegroundThreshold
478
+ })), evaluateNonTrue({
479
+ key: "alphaMattingBackgroundThreshold",
480
+ value: alphaMattingBackgroundThreshold
481
+ })), evaluateNonTrue({
482
+ key: "alphaMattingErodeSize",
483
+ value: alphaMattingErodeSize
484
+ })), evaluateNonTrue({ key: "outputType", value: outputType })), evaluateNonTrue({ key: "outputFormat", value: outputFormat })));
485
+ const lis = this.globalListener({
486
+ taskUUID
487
+ });
488
+ const response = await getIntervalWithPromise(
489
+ ({ resolve, reject }) => {
490
+ const newRemoveBackground = this.getSingleMessage({ taskUUID });
491
+ if (!newRemoveBackground)
492
+ return;
493
+ if (newRemoveBackground == null ? void 0 : newRemoveBackground.error) {
494
+ reject(newRemoveBackground);
495
+ return true;
496
+ }
497
+ if (newRemoveBackground) {
498
+ delete this._globalMessages[taskUUID];
499
+ resolve([newRemoveBackground]);
500
+ return true;
501
+ }
502
+ },
503
+ { debugKey: "remove-image-background" }
504
+ );
505
+ lis.destroy();
506
+ return response;
507
+ });
508
+ } catch (e) {
509
+ throw e;
510
+ }
511
+ };
512
+ this.upscaleGan = async ({
513
+ inputImage,
514
+ upscaleFactor,
515
+ outputType,
516
+ outputFormat,
517
+ includeCost,
518
+ customTaskUUID
519
+ }) => {
520
+ try {
521
+ await this.ensureConnection();
522
+ return await asyncRetry(async () => {
523
+ let imageUploaded;
524
+ imageUploaded = await this.uploadImage(inputImage);
525
+ if (!(imageUploaded == null ? void 0 : imageUploaded.imageUUID))
526
+ return null;
527
+ const taskUUID = customTaskUUID || getUUID();
528
+ this.send(__spreadValues(__spreadValues(__spreadValues({
529
+ taskUUID,
530
+ inputImage: imageUploaded == null ? void 0 : imageUploaded.imageUUID,
531
+ taskType: "imageUpscale" /* IMAGE_UPSCALE */,
532
+ upscaleFactor
533
+ }, evaluateNonTrue({ key: "includeCost", value: includeCost })), outputType ? { outputType } : {}), outputFormat ? { outputFormat } : {}));
534
+ const lis = this.globalListener({
535
+ taskUUID
536
+ });
537
+ const response = await getIntervalWithPromise(
538
+ ({ resolve, reject }) => {
539
+ const newUpscaleGan = this.getSingleMessage({ taskUUID });
540
+ if (!newUpscaleGan)
541
+ return;
542
+ if (newUpscaleGan == null ? void 0 : newUpscaleGan.error) {
543
+ reject(newUpscaleGan);
544
+ return true;
545
+ }
546
+ if (newUpscaleGan) {
547
+ delete this._globalMessages[taskUUID];
548
+ resolve([newUpscaleGan]);
549
+ return true;
550
+ }
551
+ },
552
+ { debugKey: "upscale-gan" }
553
+ );
554
+ lis.destroy();
555
+ return response;
556
+ });
557
+ } catch (e) {
558
+ throw e;
559
+ }
560
+ };
561
+ this.enhancePrompt = async ({
562
+ prompt,
563
+ promptMaxLength = 380,
564
+ promptVersions = 1,
565
+ includeCost,
566
+ customTaskUUID
567
+ }) => {
568
+ try {
569
+ await this.ensureConnection();
570
+ return await asyncRetry(async () => {
571
+ const taskUUID = customTaskUUID || getUUID();
572
+ this.send(__spreadProps(__spreadValues({
573
+ prompt,
574
+ taskUUID,
575
+ promptMaxLength,
576
+ promptVersions
577
+ }, evaluateNonTrue({ key: "includeCost", value: includeCost })), {
578
+ taskType: "promptEnhance" /* PROMPT_ENHANCE */
579
+ }));
580
+ const lis = this.globalListener({
581
+ taskUUID
582
+ });
583
+ const response = await getIntervalWithPromise(
584
+ ({ resolve, reject }) => {
585
+ const reducedPrompt = this._globalMessages[taskUUID];
586
+ if (reducedPrompt == null ? void 0 : reducedPrompt.error) {
587
+ reject(reducedPrompt);
588
+ return true;
589
+ }
590
+ if ((reducedPrompt == null ? void 0 : reducedPrompt.length) >= promptVersions) {
591
+ delete this._globalMessages[taskUUID];
592
+ resolve(reducedPrompt);
593
+ return true;
594
+ }
595
+ },
596
+ { debugKey: "enhance-prompt" }
597
+ );
598
+ lis.destroy();
599
+ return response;
600
+ });
601
+ } catch (e) {
602
+ throw e;
603
+ }
604
+ };
605
+ this.getSingleMessage = ({ taskUUID }) => {
606
+ var _a;
607
+ const value = this._globalMessages[taskUUID] || ((_a = this._globalMessages[taskUUID]) == null ? void 0 : _a[0]);
608
+ if (!value)
609
+ return null;
610
+ return value;
611
+ };
612
+ this.disconnect = () => {
613
+ var _a, _b, _c, _d;
614
+ (_b = (_a = this._ws) == null ? void 0 : _a.terminate) == null ? void 0 : _b.call(_a);
615
+ (_d = (_c = this._ws) == null ? void 0 : _c.close) == null ? void 0 : _d.call(_c);
616
+ };
617
+ this.connected = () => this.isWebsocketReadyState() && !!this._connectionSessionUUID;
618
+ this._apiKey = apiKey;
619
+ this._url = url;
620
+ this._sdkType = "CLIENT" /* CLIENT */;
621
+ }
622
+ // protected addListener({
623
+ // lis,
624
+ // check,
625
+ // }: {
626
+ // lis: (v: any) => any;
627
+ // check: (v: any) => any;
628
+ // groupKey?: string;
629
+ // }): { destroy: Function } {
630
+ // this._ws.onmessage = (e: any) => {
631
+ // const m = JSON.parse(e.data);
632
+ // if (m?.error) {
633
+ // lis(m);
634
+ // } else if (check(m)) {
635
+ // lis(m);
636
+ // }
637
+ // };
638
+ // return {
639
+ // destroy: () => {},
640
+ // };
641
+ // }
642
+ addListener({
643
+ lis,
644
+ // check,
645
+ groupKey,
646
+ taskUUID
647
+ }) {
648
+ const listener = (msg) => {
649
+ var _a;
650
+ const arrayMessage = Array.isArray(msg == null ? void 0 : msg.data) ? msg.data : [msg.data];
651
+ const arrayErrors = Array.isArray(msg == null ? void 0 : msg.errors) ? msg.errors : [msg.errors];
652
+ const filteredMessage = arrayMessage.filter(
653
+ (v) => ((v == null ? void 0 : v.taskUUID) || (v == null ? void 0 : v.taskType)) === taskUUID
654
+ );
655
+ const filteredErrors = arrayErrors.filter(
656
+ (v) => ((v == null ? void 0 : v.taskUUID) || (v == null ? void 0 : v.taskType)) === taskUUID
657
+ );
658
+ if (filteredErrors.length) {
659
+ lis({ error: __spreadValues({}, (_a = arrayErrors[0]) != null ? _a : {}) });
660
+ return;
661
+ }
662
+ if (filteredMessage.length) {
663
+ lis({ [taskUUID]: arrayMessage });
664
+ return;
665
+ }
666
+ };
667
+ const groupListener = { key: getUUID(), listener, groupKey };
668
+ this._listeners.push(groupListener);
669
+ const destroy = () => {
670
+ this._listeners = removeListener(this._listeners, groupListener);
671
+ };
672
+ return {
673
+ destroy
674
+ };
675
+ }
676
+ connect() {
677
+ this._ws.onopen = (e) => {
678
+ if (this._connectionSessionUUID) {
679
+ this.send({
680
+ taskType: "authentication" /* AUTHENTICATION */,
681
+ apiKey: this._apiKey,
682
+ connectionSessionUUID: this._connectionSessionUUID
683
+ });
684
+ } else {
685
+ this.send({ apiKey: this._apiKey, taskType: "authentication" /* AUTHENTICATION */ });
686
+ }
687
+ this.addListener({
688
+ taskUUID: "authentication" /* AUTHENTICATION */,
689
+ lis: (m) => {
690
+ var _a, _b;
691
+ if (m == null ? void 0 : m.error) {
692
+ this._invalidAPIkey = "Invalid API key";
693
+ return;
694
+ }
695
+ this._connectionSessionUUID = (_b = (_a = m == null ? void 0 : m["authentication" /* AUTHENTICATION */]) == null ? void 0 : _a[0]) == null ? void 0 : _b.connectionSessionUUID;
696
+ this._invalidAPIkey = void 0;
697
+ }
698
+ });
699
+ };
700
+ this._ws.onmessage = (e) => {
701
+ var _a;
702
+ const data = JSON.parse(e.data);
703
+ for (const lis of this._listeners) {
704
+ const result = (_a = lis == null ? void 0 : lis.listener) == null ? void 0 : _a.call(lis, data);
705
+ if (result)
706
+ return;
707
+ }
708
+ };
709
+ this._ws.onclose = (e) => {
710
+ if (this._invalidAPIkey) {
711
+ console.error(this._invalidAPIkey);
712
+ return;
713
+ }
714
+ };
715
+ }
716
+ destroy(lis) {
717
+ removeFromAray(this._listeners, lis);
718
+ }
719
+ listenToImages({
720
+ onPartialImages,
721
+ taskUUID,
722
+ groupKey,
723
+ positivePrompt,
724
+ negativePrompt
725
+ }) {
726
+ return this.addListener({
727
+ taskUUID,
728
+ lis: (m) => {
729
+ var _a, _b;
730
+ let images = (_a = m == null ? void 0 : m[taskUUID]) == null ? void 0 : _a.filter(
731
+ (img) => img.taskUUID === taskUUID
732
+ );
733
+ if (m.error) {
734
+ onPartialImages == null ? void 0 : onPartialImages(images, (m == null ? void 0 : m.error) && m);
735
+ this._globalError = m;
736
+ } else {
737
+ images = images.map((image) => __spreadProps(__spreadValues({}, image), {
738
+ positivePrompt,
739
+ negativePrompt
740
+ }));
741
+ onPartialImages == null ? void 0 : onPartialImages(images, (m == null ? void 0 : m.error) && m);
742
+ if (this._sdkType === "CLIENT" /* CLIENT */) {
743
+ this._globalImages = [
744
+ ...this._globalImages,
745
+ ...((_b = m == null ? void 0 : m[taskUUID]) != null ? _b : []).map((image) => __spreadProps(__spreadValues({}, image), {
746
+ positivePrompt,
747
+ negativePrompt
748
+ }))
749
+ ];
750
+ } else {
751
+ this._globalImages = [...this._globalImages, ...images];
752
+ }
753
+ }
754
+ },
755
+ groupKey
756
+ });
757
+ }
758
+ globalListener({ taskUUID }) {
759
+ return this.addListener({
760
+ // check: (m) => {
761
+ // const value = accessDeepObject({
762
+ // key: responseKey,
763
+ // data: m,
764
+ // useZero: false,
765
+ // });
766
+ // return !!value;
767
+ // },
768
+ // check: responseKey,
769
+ taskUUID,
770
+ lis: (m) => {
771
+ console.log("m", m);
772
+ if (m.error) {
773
+ this._globalMessages[taskUUID] = m;
774
+ return;
775
+ }
776
+ const value = accessDeepObject({
777
+ key: taskUUID,
778
+ data: m,
779
+ useZero: false
780
+ });
781
+ if (Array.isArray(value)) {
782
+ value.forEach((v) => {
783
+ var _a;
784
+ this._globalMessages[v.taskUUID] = [
785
+ ...(_a = this._globalMessages[v.taskUUID]) != null ? _a : [],
786
+ v
787
+ ];
788
+ });
789
+ } else {
790
+ this._globalMessages[value.taskUUID] = value;
791
+ }
792
+ }
793
+ });
794
+ }
795
+ async requestImages({
796
+ outputType,
797
+ outputFormat,
798
+ uploadEndpoint,
799
+ checkNsfw,
800
+ positivePrompt,
801
+ negativePrompt,
802
+ seedImage,
803
+ maskImage,
804
+ strength,
805
+ height,
806
+ width,
807
+ model,
808
+ steps,
809
+ scheduler,
810
+ seed,
811
+ CFGScale,
812
+ clipSkip,
813
+ usePromptWeighting,
814
+ numberResults = 1,
815
+ controlNet,
816
+ lora,
817
+ onPartialImages,
818
+ includeCost,
819
+ customTaskUUID,
820
+ retry = 2
821
+ }) {
822
+ await this.ensureConnection();
823
+ let lis = void 0;
824
+ let requestObject = void 0;
825
+ let taskUUIDs = [];
826
+ let retryCount = 0;
827
+ try {
828
+ await this.ensureConnection();
829
+ let seedImageUUID = null;
830
+ let maskImageUUID = null;
831
+ let controlNetData = [];
832
+ if (seedImage) {
833
+ const uploadedImage = await this.uploadImage(seedImage);
834
+ if (!uploadedImage)
835
+ return [];
836
+ seedImageUUID = uploadedImage.imageUUID;
837
+ }
838
+ if (maskImage) {
839
+ const uploadedMaskInitiator = await this.uploadImage(maskImage);
840
+ if (!uploadedMaskInitiator)
841
+ return [];
842
+ maskImageUUID = uploadedMaskInitiator.imageUUID;
843
+ }
844
+ if (controlNet == null ? void 0 : controlNet.length) {
845
+ for (let i = 0; i < controlNet.length; i++) {
846
+ const controlData = controlNet[i];
847
+ const {
848
+ endStep,
849
+ startStep,
850
+ weight,
851
+ guideImage,
852
+ controlMode,
853
+ startStepPercentage,
854
+ endStepPercentage,
855
+ model: controlNetModel
856
+ } = controlData;
857
+ if (!guideImage)
858
+ return;
859
+ const imageUploaded = await this.uploadImage(
860
+ guideImage
861
+ );
862
+ if (!imageUploaded)
863
+ return;
864
+ controlNetData.push(__spreadProps(__spreadValues(__spreadValues({
865
+ guideImage: imageUploaded.imageUUID,
866
+ model: controlNetModel,
867
+ endStep,
868
+ startStep,
869
+ weight
870
+ }, evaluateNonTrue({
871
+ key: "startStepPercentage",
872
+ value: startStepPercentage
873
+ })), evaluateNonTrue({
874
+ key: "endStepPercentage",
875
+ value: endStepPercentage
876
+ })), {
877
+ controlMode: controlMode || "controlnet" /* CONTROL_NET */
878
+ }));
879
+ }
880
+ }
881
+ requestObject = __spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadProps(__spreadValues(__spreadValues(__spreadValues({
882
+ taskType: "imageInference" /* IMAGE_INFERENCE */,
883
+ model,
884
+ positivePrompt
885
+ }, negativePrompt ? { negativePrompt } : {}), height ? { height } : {}), width ? { width } : {}), {
886
+ numberResults
887
+ }), (lora == null ? void 0 : lora.length) ? { lora } : {}), outputType ? { outputType } : {}), outputFormat ? { outputFormat } : {}), uploadEndpoint ? { uploadEndpoint } : {}), evaluateNonTrue({ key: "checkNsfw", value: checkNsfw })), evaluateNonTrue({ key: "strength", value: strength })), evaluateNonTrue({ key: "CFGScale", value: CFGScale })), evaluateNonTrue({ key: "clipSkip", value: clipSkip })), evaluateNonTrue({
888
+ key: "usePromptWeighting",
889
+ value: usePromptWeighting
890
+ })), evaluateNonTrue({ key: "steps", value: steps })), controlNetData.length ? { controlNet: controlNetData } : {}), seed ? { seed } : {}), scheduler ? { scheduler } : {}), evaluateNonTrue({ key: "includeCost", value: includeCost })), seedImageUUID ? { seedImage: seedImageUUID } : {}), maskImageUUID ? { maskImage: maskImageUUID } : {});
891
+ return await asyncRetry(
892
+ async () => {
893
+ retryCount++;
894
+ lis == null ? void 0 : lis.destroy();
895
+ const imagesWithSimilarTask = this._globalImages.filter(
896
+ (img) => taskUUIDs.includes(img.taskUUID)
897
+ );
898
+ const taskUUID = customTaskUUID || getUUID();
899
+ taskUUIDs.push(taskUUID);
900
+ const imageRemaining = numberResults - imagesWithSimilarTask.length;
901
+ const newRequestObject = __spreadProps(__spreadValues({}, requestObject), {
902
+ taskUUID,
903
+ numberResults: imageRemaining
904
+ });
905
+ this.send(newRequestObject);
906
+ lis = this.listenToImages({
907
+ onPartialImages,
908
+ taskUUID,
909
+ groupKey: "REQUEST_IMAGES" /* REQUEST_IMAGES */,
910
+ positivePrompt,
911
+ negativePrompt
912
+ });
913
+ const promise = await this.getSimilarImages({
914
+ taskUUID: taskUUIDs,
915
+ numberResults,
916
+ lis
917
+ });
918
+ lis.destroy();
919
+ return promise;
920
+ },
921
+ {
922
+ maxRetries: retry,
923
+ callback: () => {
924
+ lis == null ? void 0 : lis.destroy();
925
+ }
926
+ }
927
+ );
928
+ } catch (e) {
929
+ if (e.taskUUID) {
930
+ throw e;
931
+ }
932
+ if (retryCount >= retry) {
933
+ return this.handleIncompleteImages({ taskUUIDs, error: e });
934
+ }
935
+ }
936
+ }
937
+ async ensureConnection() {
938
+ var _a;
939
+ let isConnected = this.connected();
940
+ if (isConnected || this._url === BASE_RUNWARE_URLS.TEST)
941
+ return;
942
+ const retryInterval = 2e3;
943
+ const pollingInterval = 200;
944
+ try {
945
+ if (this._invalidAPIkey)
946
+ throw this._invalidAPIkey;
947
+ return new Promise((resolve, reject) => {
948
+ let retry = 0;
949
+ const MAX_RETRY = 10;
950
+ let retryIntervalId;
951
+ let pollingIntervalId;
952
+ const clearAllIntervals = () => {
953
+ clearInterval(retryIntervalId);
954
+ clearInterval(pollingIntervalId);
955
+ };
956
+ if (this._sdkType === "SERVER" /* SERVER */) {
957
+ retryIntervalId = setInterval(async () => {
958
+ try {
959
+ const hasConnected = this.connected();
960
+ if (hasConnected) {
961
+ clearAllIntervals();
962
+ resolve(true);
963
+ } else if (retry >= MAX_RETRY) {
964
+ clearAllIntervals();
965
+ reject(new Error("Retry timed out"));
966
+ } else {
967
+ this.connect();
968
+ retry++;
969
+ }
970
+ } catch (error) {
971
+ clearAllIntervals();
972
+ reject(error);
973
+ }
974
+ }, retryInterval);
975
+ }
976
+ pollingIntervalId = setInterval(async () => {
977
+ const hasConnected = this.connected();
978
+ if (hasConnected) {
979
+ clearAllIntervals();
980
+ resolve(true);
981
+ }
982
+ if (!!this._invalidAPIkey) {
983
+ clearAllIntervals();
984
+ reject(new Error("Invalid API key"));
985
+ return;
986
+ }
987
+ }, pollingInterval);
988
+ });
989
+ if (!isConnected) {
990
+ this.connect();
991
+ await delay(2);
992
+ }
993
+ } catch (e) {
994
+ throw (_a = this._invalidAPIkey) != null ? _a : "Could not connect to server. Ensure your API key is correct";
995
+ }
996
+ }
997
+ async getSimilarImages({
998
+ taskUUID,
999
+ numberResults,
1000
+ shouldThrowError,
1001
+ lis
1002
+ }) {
1003
+ return await getIntervalWithPromise(
1004
+ ({ resolve, reject, intervalId }) => {
1005
+ const taskUUIDs = Array.isArray(taskUUID) ? taskUUID : [taskUUID];
1006
+ const imagesWithSimilarTask = this._globalImages.filter(
1007
+ (img) => taskUUIDs.includes(img.taskUUID)
1008
+ );
1009
+ if (this._globalError) {
1010
+ const newData = this._globalError;
1011
+ this._globalError = void 0;
1012
+ clearInterval(intervalId);
1013
+ reject == null ? void 0 : reject(newData);
1014
+ return true;
1015
+ } else if (imagesWithSimilarTask.length >= numberResults) {
1016
+ clearInterval(intervalId);
1017
+ this._globalImages = this._globalImages.filter(
1018
+ (img) => !taskUUIDs.includes(img.taskUUID)
1019
+ );
1020
+ resolve([...imagesWithSimilarTask].slice(0, numberResults));
1021
+ return true;
1022
+ }
1023
+ },
1024
+ { debugKey: "getting images", shouldThrowError }
1025
+ );
1026
+ }
1027
+ handleIncompleteImages({
1028
+ taskUUIDs,
1029
+ error
1030
+ }) {
1031
+ const imagesWithSimilarTask = this._globalImages.filter(
1032
+ (img) => taskUUIDs.includes(img.taskUUID)
1033
+ );
1034
+ if (imagesWithSimilarTask.length > 1) {
1035
+ this._globalImages = this._globalImages.filter(
1036
+ (img) => !taskUUIDs.includes(img.taskUUID)
1037
+ );
1038
+ return imagesWithSimilarTask;
1039
+ } else {
1040
+ throw error;
1041
+ }
1042
+ }
1043
+ //end of data
1044
+ };
1045
+ }
1046
+ });
1047
+
1048
+ export {
1049
+ __esm,
1050
+ __commonJS,
1051
+ __export,
1052
+ __toESM,
1053
+ __toCommonJS,
1054
+ Environment,
1055
+ SdkType,
1056
+ ETaskType,
1057
+ EControlMode,
1058
+ EPreProcessorGroup,
1059
+ EPreProcessor,
1060
+ EOpenPosePreProcessor,
1061
+ init_types,
1062
+ RunwareBase,
1063
+ init_Runware_base
1064
+ };