@runware/sdk-js 1.1.18 → 1.1.20-beta.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/dist/index.cjs ADDED
@@ -0,0 +1,1504 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __defProps = Object.defineProperties;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
7
+ var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
9
+ var __getProtoOf = Object.getPrototypeOf;
10
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
11
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
12
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
13
+ var __spreadValues = (a, b) => {
14
+ for (var prop in b || (b = {}))
15
+ if (__hasOwnProp.call(b, prop))
16
+ __defNormalProp(a, prop, b[prop]);
17
+ if (__getOwnPropSymbols)
18
+ for (var prop of __getOwnPropSymbols(b)) {
19
+ if (__propIsEnum.call(b, prop))
20
+ __defNormalProp(a, prop, b[prop]);
21
+ }
22
+ return a;
23
+ };
24
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
25
+ var __objRest = (source, exclude) => {
26
+ var target = {};
27
+ for (var prop in source)
28
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
29
+ target[prop] = source[prop];
30
+ if (source != null && __getOwnPropSymbols)
31
+ for (var prop of __getOwnPropSymbols(source)) {
32
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
33
+ target[prop] = source[prop];
34
+ }
35
+ return target;
36
+ };
37
+ var __commonJS = (cb, mod) => function __require() {
38
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
39
+ };
40
+ var __export = (target, all) => {
41
+ for (var name in all)
42
+ __defProp(target, name, { get: all[name], enumerable: true });
43
+ };
44
+ var __copyProps = (to, from, except, desc) => {
45
+ if (from && typeof from === "object" || typeof from === "function") {
46
+ for (let key of __getOwnPropNames(from))
47
+ if (!__hasOwnProp.call(to, key) && key !== except)
48
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
49
+ }
50
+ return to;
51
+ };
52
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
53
+ // If the importer is in node compatibility mode or this is not an ESM
54
+ // file that has been converted to a CommonJS file using a Babel-
55
+ // compatible transform (i.e. "__esModule" has not been set), then set
56
+ // "default" to the CommonJS "module.exports" for node compatibility.
57
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
58
+ mod
59
+ ));
60
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
61
+
62
+ // Runware/reconnect.ts
63
+ var require_reconnect = __commonJS({
64
+ "Runware/reconnect.ts"(exports, module) {
65
+ "use strict";
66
+ var isWebSocket = (constructor) => constructor && constructor.CLOSING === 2;
67
+ var isGlobalWebSocket = () => typeof WebSocket !== "undefined" && isWebSocket(WebSocket);
68
+ var getDefaultOptions = () => ({
69
+ constructor: isGlobalWebSocket() ? WebSocket : null,
70
+ maxReconnectionDelay: 1e4,
71
+ minReconnectionDelay: 1500,
72
+ reconnectionDelayGrowFactor: 1.3,
73
+ connectionTimeout: 4e3,
74
+ maxRetries: Infinity,
75
+ debug: false
76
+ });
77
+ var bypassProperty = (src, dst, name) => {
78
+ Object.defineProperty(dst, name, {
79
+ get: () => src[name],
80
+ set: (value) => {
81
+ src[name] = value;
82
+ },
83
+ enumerable: true,
84
+ configurable: true
85
+ });
86
+ };
87
+ var initReconnectionDelay = (config) => config.minReconnectionDelay + Math.random() * config.minReconnectionDelay;
88
+ var updateReconnectionDelay = (config, previousDelay) => {
89
+ const newDelay = previousDelay * config.reconnectionDelayGrowFactor;
90
+ return newDelay > config.maxReconnectionDelay ? config.maxReconnectionDelay : newDelay;
91
+ };
92
+ var LEVEL_0_EVENTS = ["onopen", "onclose", "onmessage", "onerror"];
93
+ var reassignEventListeners = (ws, oldWs, listeners) => {
94
+ Object.keys(listeners).forEach((type) => {
95
+ listeners[type].forEach(([listener, options]) => {
96
+ ws.addEventListener(type, listener, options);
97
+ });
98
+ });
99
+ if (oldWs) {
100
+ LEVEL_0_EVENTS.forEach((name) => {
101
+ ws[name] = oldWs[name];
102
+ });
103
+ }
104
+ };
105
+ var ReconnectingWebsocket2 = function(url, protocols, options = {}) {
106
+ let ws;
107
+ let connectingTimeout;
108
+ let reconnectDelay = 0;
109
+ let retriesCount = 0;
110
+ let shouldRetry = true;
111
+ const listeners = {};
112
+ if (!(this instanceof ReconnectingWebsocket2)) {
113
+ throw new TypeError(
114
+ "Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator"
115
+ );
116
+ }
117
+ const config = getDefaultOptions();
118
+ Object.keys(config).filter((key) => options.hasOwnProperty(key)).forEach((key) => config[key] = options[key]);
119
+ if (!isWebSocket(config.constructor)) {
120
+ throw new TypeError(
121
+ "Invalid WebSocket constructor. Set `options.constructor`"
122
+ );
123
+ }
124
+ const log = config.debug ? (...params) => console.log("RWS:", ...params) : () => {
125
+ };
126
+ const emitError = (code, msg) => setTimeout(() => {
127
+ const err = new Error(msg);
128
+ err.code = code;
129
+ if (Array.isArray(listeners.error)) {
130
+ listeners.error.forEach(([fn]) => fn(err));
131
+ }
132
+ if (ws.onerror) {
133
+ ws.onerror(err);
134
+ }
135
+ }, 0);
136
+ const handleClose = () => {
137
+ log("close");
138
+ retriesCount++;
139
+ log("retries count:", retriesCount);
140
+ if (retriesCount > config.maxRetries) {
141
+ emitError("EHOSTDOWN", "Too many failed connection attempts");
142
+ return;
143
+ }
144
+ if (!reconnectDelay) {
145
+ reconnectDelay = initReconnectionDelay(config);
146
+ } else {
147
+ reconnectDelay = updateReconnectionDelay(config, reconnectDelay);
148
+ }
149
+ log("reconnectDelay:", reconnectDelay);
150
+ if (shouldRetry) {
151
+ setTimeout(connect, reconnectDelay);
152
+ }
153
+ };
154
+ const connect = () => {
155
+ log("connect");
156
+ const oldWs = ws;
157
+ ws = new config.constructor(url, protocols);
158
+ connectingTimeout = setTimeout(() => {
159
+ log("timeout");
160
+ ws.close();
161
+ emitError("ETIMEDOUT", "Connection timeout");
162
+ }, config.connectionTimeout);
163
+ log("bypass properties");
164
+ for (let key in ws) {
165
+ if (["addEventListener", "removeEventListener", "close", "send"].indexOf(
166
+ key
167
+ ) < 0) {
168
+ bypassProperty(ws, this, key);
169
+ }
170
+ }
171
+ ws.addEventListener("open", () => {
172
+ clearTimeout(connectingTimeout);
173
+ log("open");
174
+ reconnectDelay = initReconnectionDelay(config);
175
+ log("reconnectDelay:", reconnectDelay);
176
+ retriesCount = 0;
177
+ });
178
+ ws.addEventListener("close", handleClose);
179
+ reassignEventListeners(ws, oldWs, listeners);
180
+ };
181
+ log("init");
182
+ connect();
183
+ this.close = (code = 1e3, reason = "", { keepClosed = false, fastClose = true, delay: delay3 = 0 } = {}) => {
184
+ if (delay3) {
185
+ reconnectDelay = delay3;
186
+ }
187
+ shouldRetry = !keepClosed;
188
+ ws.close(code, reason);
189
+ if (fastClose) {
190
+ const fakeCloseEvent = {
191
+ code,
192
+ reason,
193
+ wasClean: true
194
+ };
195
+ handleClose();
196
+ if (Array.isArray(listeners.close)) {
197
+ listeners.close.forEach(([listener, options2]) => {
198
+ listener(fakeCloseEvent);
199
+ ws.removeEventListener("close", listener, options2);
200
+ });
201
+ }
202
+ if (ws.onclose) {
203
+ ws.onclose(fakeCloseEvent);
204
+ ws.onclose = null;
205
+ }
206
+ }
207
+ };
208
+ this.send = (data) => {
209
+ ws.send(data);
210
+ };
211
+ this.addEventListener = (type, listener, options2) => {
212
+ if (Array.isArray(listeners[type])) {
213
+ if (!listeners[type].some(([l]) => l === listener)) {
214
+ listeners[type].push([listener, options2]);
215
+ }
216
+ } else {
217
+ listeners[type] = [[listener, options2]];
218
+ }
219
+ ws.addEventListener(type, listener, options2);
220
+ };
221
+ this.removeEventListener = (type, listener, options2) => {
222
+ if (Array.isArray(listeners[type])) {
223
+ listeners[type] = listeners[type].filter(([l]) => l !== listener);
224
+ }
225
+ ws.removeEventListener(type, listener, options2);
226
+ };
227
+ };
228
+ module.exports = ReconnectingWebsocket2;
229
+ }
230
+ });
231
+
232
+ // Runware/index.ts
233
+ var Runware_exports = {};
234
+ __export(Runware_exports, {
235
+ EControlMode: () => EControlMode,
236
+ EOpenPosePreProcessor: () => EOpenPosePreProcessor,
237
+ EPreProcessor: () => EPreProcessor,
238
+ EPreProcessorGroup: () => EPreProcessorGroup,
239
+ ETaskType: () => ETaskType,
240
+ Environment: () => Environment,
241
+ Runware: () => Runware,
242
+ RunwareClient: () => RunwareClient,
243
+ RunwareServer: () => RunwareServer,
244
+ SdkType: () => SdkType
245
+ });
246
+ module.exports = __toCommonJS(Runware_exports);
247
+
248
+ // Runware/types.ts
249
+ var Environment = /* @__PURE__ */ ((Environment2) => {
250
+ Environment2["PRODUCTION"] = "PRODUCTION";
251
+ Environment2["DEVELOPMENT"] = "DEVELOPMENT";
252
+ Environment2["TEST"] = "TEST";
253
+ return Environment2;
254
+ })(Environment || {});
255
+ var SdkType = /* @__PURE__ */ ((SdkType2) => {
256
+ SdkType2["CLIENT"] = "CLIENT";
257
+ SdkType2["SERVER"] = "SERVER";
258
+ return SdkType2;
259
+ })(SdkType || {});
260
+ var ETaskType = /* @__PURE__ */ ((ETaskType2) => {
261
+ ETaskType2["IMAGE_INFERENCE"] = "imageInference";
262
+ ETaskType2["IMAGE_UPLOAD"] = "imageUpload";
263
+ ETaskType2["IMAGE_UPSCALE"] = "imageUpscale";
264
+ ETaskType2["IMAGE_BACKGROUND_REMOVAL"] = "imageBackgroundRemoval";
265
+ ETaskType2["IMAGE_CAPTION"] = "imageCaption";
266
+ ETaskType2["IMAGE_CONTROL_NET_PRE_PROCESS"] = "imageControlNetPreProcess";
267
+ ETaskType2["PROMPT_ENHANCE"] = "promptEnhance";
268
+ ETaskType2["AUTHENTICATION"] = "authentication";
269
+ ETaskType2["MODEL_UPLOAD"] = "modelUpload";
270
+ return ETaskType2;
271
+ })(ETaskType || {});
272
+ var EControlMode = /* @__PURE__ */ ((EControlMode2) => {
273
+ EControlMode2["BALANCED"] = "balanced";
274
+ EControlMode2["PROMPT"] = "prompt";
275
+ EControlMode2["CONTROL_NET"] = "controlnet";
276
+ return EControlMode2;
277
+ })(EControlMode || {});
278
+ var EPreProcessorGroup = /* @__PURE__ */ ((EPreProcessorGroup2) => {
279
+ EPreProcessorGroup2["canny"] = "canny";
280
+ EPreProcessorGroup2["depth"] = "depth";
281
+ EPreProcessorGroup2["mlsd"] = "mlsd";
282
+ EPreProcessorGroup2["normalbae"] = "normalbae";
283
+ EPreProcessorGroup2["openpose"] = "openpose";
284
+ EPreProcessorGroup2["tile"] = "tile";
285
+ EPreProcessorGroup2["seg"] = "seg";
286
+ EPreProcessorGroup2["lineart"] = "lineart";
287
+ EPreProcessorGroup2["lineart_anime"] = "lineart_anime";
288
+ EPreProcessorGroup2["shuffle"] = "shuffle";
289
+ EPreProcessorGroup2["scribble"] = "scribble";
290
+ EPreProcessorGroup2["softedge"] = "softedge";
291
+ return EPreProcessorGroup2;
292
+ })(EPreProcessorGroup || {});
293
+ var EPreProcessor = /* @__PURE__ */ ((EPreProcessor2) => {
294
+ EPreProcessor2["canny"] = "canny";
295
+ EPreProcessor2["depth_leres"] = "depth_leres";
296
+ EPreProcessor2["depth_midas"] = "depth_midas";
297
+ EPreProcessor2["depth_zoe"] = "depth_zoe";
298
+ EPreProcessor2["inpaint_global_harmonious"] = "inpaint_global_harmonious";
299
+ EPreProcessor2["lineart_anime"] = "lineart_anime";
300
+ EPreProcessor2["lineart_coarse"] = "lineart_coarse";
301
+ EPreProcessor2["lineart_realistic"] = "lineart_realistic";
302
+ EPreProcessor2["lineart_standard"] = "lineart_standard";
303
+ EPreProcessor2["mlsd"] = "mlsd";
304
+ EPreProcessor2["normal_bae"] = "normal_bae";
305
+ EPreProcessor2["scribble_hed"] = "scribble_hed";
306
+ EPreProcessor2["scribble_pidinet"] = "scribble_pidinet";
307
+ EPreProcessor2["seg_ofade20k"] = "seg_ofade20k";
308
+ EPreProcessor2["seg_ofcoco"] = "seg_ofcoco";
309
+ EPreProcessor2["seg_ufade20k"] = "seg_ufade20k";
310
+ EPreProcessor2["shuffle"] = "shuffle";
311
+ EPreProcessor2["softedge_hed"] = "softedge_hed";
312
+ EPreProcessor2["softedge_hedsafe"] = "softedge_hedsafe";
313
+ EPreProcessor2["softedge_pidinet"] = "softedge_pidinet";
314
+ EPreProcessor2["softedge_pidisafe"] = "softedge_pidisafe";
315
+ EPreProcessor2["tile_gaussian"] = "tile_gaussian";
316
+ EPreProcessor2["openpose"] = "openpose";
317
+ EPreProcessor2["openpose_face"] = "openpose_face";
318
+ EPreProcessor2["openpose_faceonly"] = "openpose_faceonly";
319
+ EPreProcessor2["openpose_full"] = "openpose_full";
320
+ EPreProcessor2["openpose_hand"] = "openpose_hand";
321
+ return EPreProcessor2;
322
+ })(EPreProcessor || {});
323
+ var EOpenPosePreProcessor = /* @__PURE__ */ ((EOpenPosePreProcessor2) => {
324
+ EOpenPosePreProcessor2["openpose"] = "openpose";
325
+ EOpenPosePreProcessor2["openpose_face"] = "openpose_face";
326
+ EOpenPosePreProcessor2["openpose_faceonly"] = "openpose_faceonly";
327
+ EOpenPosePreProcessor2["openpose_full"] = "openpose_full";
328
+ EOpenPosePreProcessor2["openpose_hand"] = "openpose_hand";
329
+ return EOpenPosePreProcessor2;
330
+ })(EOpenPosePreProcessor || {});
331
+
332
+ // Runware/utils.ts
333
+ var import_uuid = require("uuid");
334
+ var TIMEOUT_DURATION = 6e4;
335
+ var MINIMUM_TIMEOUT_DURATION = 1e3;
336
+ var POLLING_INTERVAL = 100;
337
+ var BASE_RUNWARE_URLS = {
338
+ ["PRODUCTION" /* PRODUCTION */]: "wss://ws-api.runware.ai/v1",
339
+ ["TEST" /* TEST */]: "ws://localhost:8080"
340
+ };
341
+ var removeFromAray = (col, targetElem) => {
342
+ if (col == null) {
343
+ return;
344
+ }
345
+ let i = col.indexOf(targetElem);
346
+ if (i === -1) {
347
+ return;
348
+ }
349
+ col.splice(i, 1);
350
+ };
351
+ var getIntervalWithPromise = (callback, {
352
+ debugKey = "debugKey",
353
+ timeoutDuration = TIMEOUT_DURATION,
354
+ shouldThrowError = true
355
+ }) => {
356
+ timeoutDuration = timeoutDuration < MINIMUM_TIMEOUT_DURATION ? MINIMUM_TIMEOUT_DURATION : timeoutDuration;
357
+ return new Promise((resolve, reject) => {
358
+ const timeoutId = setTimeout(() => {
359
+ if (intervalId) {
360
+ clearInterval(intervalId);
361
+ if (shouldThrowError) {
362
+ reject(`Response could not be received from server for ${debugKey}`);
363
+ }
364
+ }
365
+ clearTimeout(timeoutId);
366
+ }, timeoutDuration);
367
+ let intervalId = setInterval(async () => {
368
+ const shouldClear = callback({ resolve, reject, intervalId });
369
+ if (shouldClear) {
370
+ clearInterval(intervalId);
371
+ clearTimeout(timeoutId);
372
+ }
373
+ }, POLLING_INTERVAL);
374
+ });
375
+ };
376
+ var fileToBase64 = (file) => new Promise((resolve) => {
377
+ const reader = new FileReader();
378
+ reader.readAsDataURL(file);
379
+ reader.onload = function() {
380
+ resolve(reader.result);
381
+ };
382
+ });
383
+ var getUUID = () => (0, import_uuid.v4)();
384
+ var isValidUUID = (uuid) => (0, import_uuid.validate)(uuid);
385
+ var accessDeepObject = ({
386
+ key,
387
+ data,
388
+ useZero = true,
389
+ shouldReturnString = false
390
+ }) => {
391
+ const splittedKeys = key.split(/\.|\[/).map((key2) => key2.replace(/\]$/, ""));
392
+ const value = splittedKeys.reduce((acc, curr) => {
393
+ var _a, _b;
394
+ const returnZero = useZero ? 0 : void 0;
395
+ const currentValue = acc == null ? void 0 : acc[curr];
396
+ if (!currentValue) {
397
+ return returnZero;
398
+ }
399
+ if (Array.isArray(currentValue) && /^\d+$/.test(curr)) {
400
+ const index = parseInt(curr, 10);
401
+ if (index >= 0 && index < currentValue.length) {
402
+ return acc[curr] = currentValue[index];
403
+ } else {
404
+ return (_a = acc[curr]) != null ? _a : returnZero;
405
+ }
406
+ } else {
407
+ return (_b = acc[curr]) != null ? _b : returnZero;
408
+ }
409
+ }, data || {});
410
+ return value != null ? value : {};
411
+ };
412
+ var delay = (time, milliseconds = 1e3) => {
413
+ return new Promise((resolve) => setTimeout(resolve, time * milliseconds));
414
+ };
415
+ var removeListener = (listeners, listener) => {
416
+ return listeners.filter((lis) => lis.key !== listener.key);
417
+ };
418
+ var evaluateNonTrue = ({
419
+ key,
420
+ value
421
+ }) => {
422
+ if (!!value || value === 0 || value === false) {
423
+ return { [key]: value };
424
+ } else {
425
+ return {};
426
+ }
427
+ };
428
+
429
+ // Runware/async-retry.ts
430
+ var asyncRetry = async (apiCall, options = {}) => {
431
+ var _a;
432
+ const { delayInSeconds = 1, callback } = options;
433
+ let maxRetries = (_a = options.maxRetries) != null ? _a : 1;
434
+ while (maxRetries) {
435
+ try {
436
+ const result = await apiCall();
437
+ return result;
438
+ } catch (error) {
439
+ callback == null ? void 0 : callback();
440
+ maxRetries--;
441
+ if (maxRetries > 0) {
442
+ await delay(delayInSeconds);
443
+ await asyncRetry(apiCall, __spreadProps(__spreadValues({}, options), { maxRetries }));
444
+ } else {
445
+ throw error;
446
+ }
447
+ }
448
+ }
449
+ };
450
+
451
+ // Runware/Runware-base.ts
452
+ var RunwareBase = class {
453
+ constructor({
454
+ apiKey,
455
+ url = BASE_RUNWARE_URLS.PRODUCTION,
456
+ shouldReconnect = true,
457
+ globalMaxRetries = 2,
458
+ timeoutDuration = TIMEOUT_DURATION
459
+ }) {
460
+ this._listeners = [];
461
+ // _globalMessages: any[] = [];
462
+ this._globalMessages = {};
463
+ this._globalImages = [];
464
+ this.isWebsocketReadyState = () => {
465
+ var _a;
466
+ return ((_a = this._ws) == null ? void 0 : _a.readyState) === 1;
467
+ };
468
+ // We moving to an array format, it make sense to consolidate all request to an array here
469
+ this.send = (msg) => {
470
+ this._ws.send(JSON.stringify([msg]));
471
+ };
472
+ this.uploadImage = async (file) => {
473
+ try {
474
+ return await asyncRetry(async () => {
475
+ const taskUUID = getUUID();
476
+ if (typeof file === "string" && isValidUUID(file)) {
477
+ return {
478
+ imageURL: file,
479
+ imageUUID: file,
480
+ taskUUID,
481
+ taskType: "imageUpload" /* IMAGE_UPLOAD */
482
+ };
483
+ }
484
+ const imageBase64 = typeof file === "string" ? file : await fileToBase64(file);
485
+ return {
486
+ imageURL: imageBase64,
487
+ imageUUID: imageBase64,
488
+ taskUUID,
489
+ taskType: "imageUpload" /* IMAGE_UPLOAD */
490
+ };
491
+ });
492
+ } catch (e) {
493
+ throw e;
494
+ }
495
+ };
496
+ this.controlNetPreProcess = async ({
497
+ inputImage,
498
+ preProcessorType,
499
+ height,
500
+ width,
501
+ outputType,
502
+ outputFormat,
503
+ highThresholdCanny,
504
+ lowThresholdCanny,
505
+ includeHandsAndFaceOpenPose,
506
+ includeCost,
507
+ customTaskUUID,
508
+ retry
509
+ }) => {
510
+ const totalRetry = retry || this._globalMaxRetries;
511
+ let lis = void 0;
512
+ try {
513
+ return await asyncRetry(
514
+ async () => {
515
+ await this.ensureConnection();
516
+ const image = await this.uploadImage(inputImage);
517
+ if (!(image == null ? void 0 : image.imageUUID))
518
+ return null;
519
+ const taskUUID = customTaskUUID || getUUID();
520
+ this.send(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
521
+ inputImage: image.imageUUID,
522
+ taskType: "imageControlNetPreProcess" /* IMAGE_CONTROL_NET_PRE_PROCESS */,
523
+ taskUUID,
524
+ preProcessorType
525
+ }, 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({
526
+ key: "highThresholdCanny",
527
+ value: highThresholdCanny
528
+ })), evaluateNonTrue({
529
+ key: "lowThresholdCanny",
530
+ value: lowThresholdCanny
531
+ })), evaluateNonTrue({
532
+ key: "includeHandsAndFaceOpenPose",
533
+ value: includeHandsAndFaceOpenPose
534
+ })));
535
+ lis = this.globalListener({
536
+ taskUUID
537
+ });
538
+ const guideImage = await getIntervalWithPromise(
539
+ ({ resolve, reject }) => {
540
+ const uploadedImage = this.getSingleMessage({
541
+ taskUUID
542
+ });
543
+ if (!uploadedImage)
544
+ return;
545
+ if (uploadedImage == null ? void 0 : uploadedImage.error) {
546
+ reject(uploadedImage);
547
+ return true;
548
+ }
549
+ if (uploadedImage) {
550
+ resolve(uploadedImage);
551
+ return true;
552
+ }
553
+ },
554
+ {
555
+ debugKey: "unprocessed-image",
556
+ timeoutDuration: this._timeoutDuration
557
+ }
558
+ );
559
+ lis.destroy();
560
+ return guideImage;
561
+ },
562
+ {
563
+ maxRetries: totalRetry,
564
+ callback: () => {
565
+ lis == null ? void 0 : lis.destroy();
566
+ }
567
+ }
568
+ );
569
+ } catch (e) {
570
+ throw e;
571
+ }
572
+ };
573
+ this.requestImageToText = async ({
574
+ inputImage,
575
+ includeCost,
576
+ customTaskUUID,
577
+ retry
578
+ }) => {
579
+ const totalRetry = retry || this._globalMaxRetries;
580
+ let lis = void 0;
581
+ try {
582
+ return await asyncRetry(
583
+ async () => {
584
+ await this.ensureConnection();
585
+ const imageUploaded = inputImage ? await this.uploadImage(inputImage) : null;
586
+ const taskUUID = customTaskUUID || getUUID();
587
+ this.send(__spreadValues({
588
+ taskUUID,
589
+ taskType: "imageCaption" /* IMAGE_CAPTION */,
590
+ inputImage: imageUploaded == null ? void 0 : imageUploaded.imageUUID
591
+ }, evaluateNonTrue({ key: "includeCost", value: includeCost })));
592
+ lis = this.globalListener({
593
+ taskUUID
594
+ });
595
+ const response = await getIntervalWithPromise(
596
+ ({ resolve, reject }) => {
597
+ const newReverseClip = this.getSingleMessage({
598
+ taskUUID
599
+ });
600
+ if (!newReverseClip)
601
+ return;
602
+ if (newReverseClip == null ? void 0 : newReverseClip.error) {
603
+ reject(newReverseClip);
604
+ return true;
605
+ }
606
+ if (newReverseClip) {
607
+ delete this._globalMessages[taskUUID];
608
+ resolve(newReverseClip);
609
+ return true;
610
+ }
611
+ },
612
+ {
613
+ debugKey: "remove-image-background",
614
+ timeoutDuration: this._timeoutDuration
615
+ }
616
+ );
617
+ lis.destroy();
618
+ return response;
619
+ },
620
+ {
621
+ maxRetries: totalRetry,
622
+ callback: () => {
623
+ lis == null ? void 0 : lis.destroy();
624
+ }
625
+ }
626
+ );
627
+ } catch (e) {
628
+ throw e;
629
+ }
630
+ };
631
+ this.removeImageBackground = async ({
632
+ inputImage,
633
+ outputType,
634
+ outputFormat,
635
+ rgba,
636
+ postProcessMask,
637
+ returnOnlyMask,
638
+ alphaMatting,
639
+ alphaMattingForegroundThreshold,
640
+ alphaMattingBackgroundThreshold,
641
+ alphaMattingErodeSize,
642
+ includeCost,
643
+ customTaskUUID,
644
+ retry
645
+ }) => {
646
+ const totalRetry = retry || this._globalMaxRetries;
647
+ let lis = void 0;
648
+ try {
649
+ return await asyncRetry(
650
+ async () => {
651
+ await this.ensureConnection();
652
+ const imageUploaded = inputImage ? await this.uploadImage(inputImage) : null;
653
+ const taskUUID = customTaskUUID || getUUID();
654
+ this.send(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
655
+ taskType: "imageBackgroundRemoval" /* IMAGE_BACKGROUND_REMOVAL */,
656
+ taskUUID,
657
+ inputImage: imageUploaded == null ? void 0 : imageUploaded.imageUUID
658
+ }, evaluateNonTrue({ key: "rgba", value: rgba })), evaluateNonTrue({
659
+ key: "postProcessMask",
660
+ value: postProcessMask
661
+ })), evaluateNonTrue({
662
+ key: "returnOnlyMask",
663
+ value: returnOnlyMask
664
+ })), evaluateNonTrue({ key: "alphaMatting", value: alphaMatting })), evaluateNonTrue({ key: "includeCost", value: includeCost })), evaluateNonTrue({
665
+ key: "alphaMattingForegroundThreshold",
666
+ value: alphaMattingForegroundThreshold
667
+ })), evaluateNonTrue({
668
+ key: "alphaMattingBackgroundThreshold",
669
+ value: alphaMattingBackgroundThreshold
670
+ })), evaluateNonTrue({
671
+ key: "alphaMattingErodeSize",
672
+ value: alphaMattingErodeSize
673
+ })), evaluateNonTrue({ key: "outputType", value: outputType })), evaluateNonTrue({ key: "outputFormat", value: outputFormat })));
674
+ lis = this.globalListener({
675
+ taskUUID
676
+ });
677
+ const response = await getIntervalWithPromise(
678
+ ({ resolve, reject }) => {
679
+ const newRemoveBackground = this.getSingleMessage({ taskUUID });
680
+ if (!newRemoveBackground)
681
+ return;
682
+ if (newRemoveBackground == null ? void 0 : newRemoveBackground.error) {
683
+ reject(newRemoveBackground);
684
+ return true;
685
+ }
686
+ if (newRemoveBackground) {
687
+ delete this._globalMessages[taskUUID];
688
+ resolve(newRemoveBackground);
689
+ return true;
690
+ }
691
+ },
692
+ {
693
+ debugKey: "remove-image-background",
694
+ timeoutDuration: this._timeoutDuration
695
+ }
696
+ );
697
+ lis.destroy();
698
+ return response;
699
+ },
700
+ {
701
+ maxRetries: totalRetry,
702
+ callback: () => {
703
+ lis == null ? void 0 : lis.destroy();
704
+ }
705
+ }
706
+ );
707
+ } catch (e) {
708
+ throw e;
709
+ }
710
+ };
711
+ this.upscaleGan = async ({
712
+ inputImage,
713
+ upscaleFactor,
714
+ outputType,
715
+ outputFormat,
716
+ includeCost,
717
+ customTaskUUID,
718
+ retry
719
+ }) => {
720
+ const totalRetry = retry || this._globalMaxRetries;
721
+ let lis = void 0;
722
+ try {
723
+ return await asyncRetry(
724
+ async () => {
725
+ await this.ensureConnection();
726
+ let imageUploaded;
727
+ imageUploaded = await this.uploadImage(inputImage);
728
+ const taskUUID = customTaskUUID || getUUID();
729
+ this.send(__spreadValues(__spreadValues(__spreadValues({
730
+ taskUUID,
731
+ inputImage: imageUploaded == null ? void 0 : imageUploaded.imageUUID,
732
+ taskType: "imageUpscale" /* IMAGE_UPSCALE */,
733
+ upscaleFactor
734
+ }, evaluateNonTrue({ key: "includeCost", value: includeCost })), outputType ? { outputType } : {}), outputFormat ? { outputFormat } : {}));
735
+ lis = this.globalListener({
736
+ taskUUID
737
+ });
738
+ const response = await getIntervalWithPromise(
739
+ ({ resolve, reject }) => {
740
+ const newUpscaleGan = this.getSingleMessage({ taskUUID });
741
+ if (!newUpscaleGan)
742
+ return;
743
+ if (newUpscaleGan == null ? void 0 : newUpscaleGan.error) {
744
+ reject(newUpscaleGan);
745
+ return true;
746
+ }
747
+ if (newUpscaleGan) {
748
+ delete this._globalMessages[taskUUID];
749
+ resolve(newUpscaleGan);
750
+ return true;
751
+ }
752
+ },
753
+ { debugKey: "upscale-gan", timeoutDuration: this._timeoutDuration }
754
+ );
755
+ lis.destroy();
756
+ return response;
757
+ },
758
+ {
759
+ maxRetries: totalRetry,
760
+ callback: () => {
761
+ lis == null ? void 0 : lis.destroy();
762
+ }
763
+ }
764
+ );
765
+ } catch (e) {
766
+ throw e;
767
+ }
768
+ };
769
+ this.enhancePrompt = async ({
770
+ prompt,
771
+ promptMaxLength = 380,
772
+ promptVersions = 1,
773
+ includeCost,
774
+ customTaskUUID,
775
+ retry
776
+ }) => {
777
+ const totalRetry = retry || this._globalMaxRetries;
778
+ let lis = void 0;
779
+ try {
780
+ return await asyncRetry(
781
+ async () => {
782
+ await this.ensureConnection();
783
+ const taskUUID = customTaskUUID || getUUID();
784
+ this.send(__spreadProps(__spreadValues({
785
+ prompt,
786
+ taskUUID,
787
+ promptMaxLength,
788
+ promptVersions
789
+ }, evaluateNonTrue({ key: "includeCost", value: includeCost })), {
790
+ taskType: "promptEnhance" /* PROMPT_ENHANCE */
791
+ }));
792
+ lis = this.globalListener({
793
+ taskUUID
794
+ });
795
+ const response = await getIntervalWithPromise(
796
+ ({ resolve, reject }) => {
797
+ const reducedPrompt = this._globalMessages[taskUUID];
798
+ if (reducedPrompt == null ? void 0 : reducedPrompt.error) {
799
+ reject(reducedPrompt);
800
+ return true;
801
+ }
802
+ if ((reducedPrompt == null ? void 0 : reducedPrompt.length) >= promptVersions) {
803
+ delete this._globalMessages[taskUUID];
804
+ resolve(reducedPrompt);
805
+ return true;
806
+ }
807
+ },
808
+ {
809
+ debugKey: "enhance-prompt",
810
+ timeoutDuration: this._timeoutDuration
811
+ }
812
+ );
813
+ lis.destroy();
814
+ return response;
815
+ },
816
+ {
817
+ maxRetries: totalRetry,
818
+ callback: () => {
819
+ lis == null ? void 0 : lis.destroy();
820
+ }
821
+ }
822
+ );
823
+ } catch (e) {
824
+ throw e;
825
+ }
826
+ };
827
+ this.modelUpload = async (payload) => {
828
+ const _a = payload, { onUploadStream, retry, customTaskUUID } = _a, addModelPayload = __objRest(_a, ["onUploadStream", "retry", "customTaskUUID"]);
829
+ const totalRetry = retry || this._globalMaxRetries;
830
+ let lis = void 0;
831
+ try {
832
+ return await asyncRetry(
833
+ async () => {
834
+ await this.ensureConnection();
835
+ const taskUUID = customTaskUUID || getUUID();
836
+ this.send(__spreadProps(__spreadValues({}, addModelPayload), {
837
+ taskUUID,
838
+ taskType: "modelUpload" /* MODEL_UPLOAD */
839
+ }));
840
+ let result;
841
+ lis = this.listenToUpload({
842
+ taskUUID,
843
+ onUploadStream: (response, error) => {
844
+ onUploadStream == null ? void 0 : onUploadStream(response, error);
845
+ if ((response == null ? void 0 : response.statusId) === 1 || error) {
846
+ result = response || error;
847
+ }
848
+ }
849
+ });
850
+ const modelUploadResponse = await getIntervalWithPromise(
851
+ ({ resolve }) => {
852
+ if (result) {
853
+ resolve(result);
854
+ return true;
855
+ }
856
+ },
857
+ {
858
+ shouldThrowError: false,
859
+ timeoutDuration: 60 * 60 * 1e3
860
+ }
861
+ );
862
+ return modelUploadResponse;
863
+ },
864
+ {
865
+ maxRetries: totalRetry,
866
+ callback: () => {
867
+ lis == null ? void 0 : lis.destroy();
868
+ }
869
+ }
870
+ );
871
+ } catch (e) {
872
+ throw e;
873
+ }
874
+ };
875
+ this.getSingleMessage = ({ taskUUID }) => {
876
+ var _a;
877
+ const value = (_a = this._globalMessages[taskUUID]) == null ? void 0 : _a[0];
878
+ const errorValue = this._globalMessages[taskUUID];
879
+ if (!value && !errorValue)
880
+ return null;
881
+ return (errorValue == null ? void 0 : errorValue.error) ? errorValue : value;
882
+ };
883
+ this.disconnect = async () => {
884
+ var _a, _b, _c, _d;
885
+ (_b = (_a = this._ws) == null ? void 0 : _a.terminate) == null ? void 0 : _b.call(_a);
886
+ (_d = (_c = this._ws) == null ? void 0 : _c.close) == null ? void 0 : _d.call(_c);
887
+ };
888
+ this.connected = () => this.isWebsocketReadyState() && !!this._connectionSessionUUID;
889
+ this._apiKey = apiKey;
890
+ this._url = url;
891
+ this._sdkType = "CLIENT" /* CLIENT */;
892
+ this._shouldReconnect = shouldReconnect;
893
+ this._globalMaxRetries = globalMaxRetries;
894
+ this._timeoutDuration = timeoutDuration;
895
+ }
896
+ static async initialize(props) {
897
+ try {
898
+ const instance = new this(props);
899
+ await instance.ensureConnection();
900
+ return instance;
901
+ } catch (e) {
902
+ throw e;
903
+ }
904
+ }
905
+ // protected addListener({
906
+ // lis,
907
+ // check,
908
+ // }: {
909
+ // lis: (v: any) => any;
910
+ // check: (v: any) => any;
911
+ // groupKey?: string;
912
+ // }): { destroy: Function } {
913
+ // this._ws.onmessage = (e: any) => {
914
+ // const m = JSON.parse(e.data);
915
+ // if (m?.error) {
916
+ // lis(m);
917
+ // } else if (check(m)) {
918
+ // lis(m);
919
+ // }
920
+ // };
921
+ // return {
922
+ // destroy: () => {},
923
+ // };
924
+ // }
925
+ addListener({
926
+ lis,
927
+ // check,
928
+ groupKey,
929
+ taskUUID
930
+ }) {
931
+ const listener = (msg) => {
932
+ var _a, _b, _c;
933
+ const arrayMessage = Array.isArray(msg == null ? void 0 : msg.data) ? msg.data : [msg.data];
934
+ const arrayErrors = ((_a = msg == null ? void 0 : msg[0]) == null ? void 0 : _a.errors) ? (_b = msg == null ? void 0 : msg[0]) == null ? void 0 : _b.errors : Array.isArray(msg == null ? void 0 : msg.errors) ? msg.errors : [msg.errors];
935
+ const filteredMessage = arrayMessage.filter(
936
+ (v) => ((v == null ? void 0 : v.taskUUID) || (v == null ? void 0 : v.taskType)) === taskUUID
937
+ );
938
+ const filteredErrors = arrayErrors.filter(
939
+ (v) => ((v == null ? void 0 : v.taskUUID) || (v == null ? void 0 : v.taskType)) === taskUUID
940
+ );
941
+ if (filteredErrors.length) {
942
+ lis({ error: __spreadValues({}, (_c = arrayErrors[0]) != null ? _c : {}) });
943
+ return;
944
+ }
945
+ if (filteredMessage.length) {
946
+ lis({ [taskUUID]: arrayMessage });
947
+ return;
948
+ }
949
+ };
950
+ const groupListener = { key: taskUUID || getUUID(), listener, groupKey };
951
+ this._listeners.push(groupListener);
952
+ const destroy = () => {
953
+ this._listeners = removeListener(this._listeners, groupListener);
954
+ };
955
+ return {
956
+ destroy
957
+ };
958
+ }
959
+ connect() {
960
+ this._ws.onopen = (e) => {
961
+ if (this._connectionSessionUUID) {
962
+ this.send({
963
+ taskType: "authentication" /* AUTHENTICATION */,
964
+ apiKey: this._apiKey,
965
+ connectionSessionUUID: this._connectionSessionUUID
966
+ });
967
+ } else {
968
+ this.send({ apiKey: this._apiKey, taskType: "authentication" /* AUTHENTICATION */ });
969
+ }
970
+ this.addListener({
971
+ taskUUID: "authentication" /* AUTHENTICATION */,
972
+ lis: (m) => {
973
+ var _a, _b;
974
+ if (m == null ? void 0 : m.error) {
975
+ this._invalidAPIkey = m;
976
+ return;
977
+ }
978
+ this._connectionSessionUUID = (_b = (_a = m == null ? void 0 : m["authentication" /* AUTHENTICATION */]) == null ? void 0 : _a[0]) == null ? void 0 : _b.connectionSessionUUID;
979
+ this._invalidAPIkey = void 0;
980
+ }
981
+ });
982
+ };
983
+ this._ws.onmessage = (e) => {
984
+ var _a;
985
+ const data = JSON.parse(e.data);
986
+ for (const lis of this._listeners) {
987
+ const result = (_a = lis == null ? void 0 : lis.listener) == null ? void 0 : _a.call(lis, data);
988
+ if (result)
989
+ return;
990
+ }
991
+ };
992
+ this._ws.onclose = (e) => {
993
+ if (this._invalidAPIkey) {
994
+ return;
995
+ }
996
+ };
997
+ }
998
+ destroy(lis) {
999
+ removeFromAray(this._listeners, lis);
1000
+ }
1001
+ listenToImages({
1002
+ onPartialImages,
1003
+ taskUUID,
1004
+ groupKey,
1005
+ positivePrompt,
1006
+ negativePrompt
1007
+ }) {
1008
+ return this.addListener({
1009
+ taskUUID,
1010
+ lis: (m) => {
1011
+ var _a, _b;
1012
+ let images = (_a = m == null ? void 0 : m[taskUUID]) == null ? void 0 : _a.filter(
1013
+ (img) => img.taskUUID === taskUUID
1014
+ );
1015
+ if (m.error) {
1016
+ onPartialImages == null ? void 0 : onPartialImages(images, (m == null ? void 0 : m.error) && m);
1017
+ this._globalError = m;
1018
+ } else {
1019
+ images = images.map((image) => __spreadProps(__spreadValues({}, image), {
1020
+ positivePrompt,
1021
+ negativePrompt
1022
+ }));
1023
+ onPartialImages == null ? void 0 : onPartialImages(images, (m == null ? void 0 : m.error) && m);
1024
+ if (this._sdkType === "CLIENT" /* CLIENT */) {
1025
+ this._globalImages = [
1026
+ ...this._globalImages,
1027
+ ...((_b = m == null ? void 0 : m[taskUUID]) != null ? _b : []).map((image) => __spreadProps(__spreadValues({}, image), {
1028
+ positivePrompt,
1029
+ negativePrompt
1030
+ }))
1031
+ ];
1032
+ } else {
1033
+ this._globalImages = [...this._globalImages, ...images];
1034
+ }
1035
+ }
1036
+ },
1037
+ groupKey
1038
+ });
1039
+ }
1040
+ listenToUpload({
1041
+ onUploadStream,
1042
+ taskUUID
1043
+ }) {
1044
+ return this.addListener({
1045
+ taskUUID,
1046
+ lis: (m) => {
1047
+ var _a;
1048
+ const error = m == null ? void 0 : m.error;
1049
+ const result = (_a = m == null ? void 0 : m[taskUUID]) == null ? void 0 : _a[0];
1050
+ let response = (result == null ? void 0 : result.taskUUID) === taskUUID ? result : null;
1051
+ if (response || error) {
1052
+ onUploadStream == null ? void 0 : onUploadStream(response || void 0, error);
1053
+ }
1054
+ }
1055
+ });
1056
+ }
1057
+ globalListener({ taskUUID }) {
1058
+ return this.addListener({
1059
+ // check: (m) => {
1060
+ // const value = accessDeepObject({
1061
+ // key: responseKey,
1062
+ // data: m,
1063
+ // useZero: false,
1064
+ // });
1065
+ // return !!value;
1066
+ // },
1067
+ // check: responseKey,
1068
+ taskUUID,
1069
+ lis: (m) => {
1070
+ if (m.error) {
1071
+ this._globalMessages[taskUUID] = m;
1072
+ return;
1073
+ }
1074
+ const value = accessDeepObject({
1075
+ key: taskUUID,
1076
+ data: m,
1077
+ useZero: false
1078
+ });
1079
+ if (Array.isArray(value)) {
1080
+ value.forEach((v) => {
1081
+ var _a;
1082
+ this._globalMessages[v.taskUUID] = [
1083
+ ...(_a = this._globalMessages[v.taskUUID]) != null ? _a : [],
1084
+ v
1085
+ ];
1086
+ });
1087
+ } else {
1088
+ this._globalMessages[value.taskUUID] = value;
1089
+ }
1090
+ }
1091
+ });
1092
+ }
1093
+ async requestImages({
1094
+ outputType,
1095
+ outputFormat,
1096
+ uploadEndpoint,
1097
+ checkNsfw,
1098
+ positivePrompt,
1099
+ negativePrompt,
1100
+ seedImage,
1101
+ maskImage,
1102
+ strength,
1103
+ height,
1104
+ width,
1105
+ model,
1106
+ steps,
1107
+ scheduler,
1108
+ seed,
1109
+ CFGScale,
1110
+ clipSkip,
1111
+ usePromptWeighting,
1112
+ numberResults = 1,
1113
+ controlNet,
1114
+ lora,
1115
+ onPartialImages,
1116
+ includeCost,
1117
+ customTaskUUID,
1118
+ retry
1119
+ }) {
1120
+ let lis = void 0;
1121
+ let requestObject = void 0;
1122
+ let taskUUIDs = [];
1123
+ let retryCount = 0;
1124
+ const totalRetry = retry || this._globalMaxRetries;
1125
+ try {
1126
+ await this.ensureConnection();
1127
+ let seedImageUUID = null;
1128
+ let maskImageUUID = null;
1129
+ let controlNetData = [];
1130
+ if (seedImage) {
1131
+ const uploadedImage = await this.uploadImage(seedImage);
1132
+ if (!uploadedImage)
1133
+ return [];
1134
+ seedImageUUID = uploadedImage.imageUUID;
1135
+ }
1136
+ if (maskImage) {
1137
+ const uploadedMaskInitiator = await this.uploadImage(maskImage);
1138
+ if (!uploadedMaskInitiator)
1139
+ return [];
1140
+ maskImageUUID = uploadedMaskInitiator.imageUUID;
1141
+ }
1142
+ if (controlNet == null ? void 0 : controlNet.length) {
1143
+ for (let i = 0; i < controlNet.length; i++) {
1144
+ const controlData = controlNet[i];
1145
+ const {
1146
+ endStep,
1147
+ startStep,
1148
+ weight,
1149
+ guideImage,
1150
+ controlMode,
1151
+ startStepPercentage,
1152
+ endStepPercentage,
1153
+ model: controlNetModel
1154
+ } = controlData;
1155
+ const imageUploaded = guideImage ? await this.uploadImage(guideImage) : null;
1156
+ controlNetData.push(__spreadProps(__spreadValues(__spreadValues({
1157
+ guideImage: imageUploaded == null ? void 0 : imageUploaded.imageUUID,
1158
+ model: controlNetModel,
1159
+ endStep,
1160
+ startStep,
1161
+ weight
1162
+ }, evaluateNonTrue({
1163
+ key: "startStepPercentage",
1164
+ value: startStepPercentage
1165
+ })), evaluateNonTrue({
1166
+ key: "endStepPercentage",
1167
+ value: endStepPercentage
1168
+ })), {
1169
+ controlMode: controlMode || "controlnet" /* CONTROL_NET */
1170
+ }));
1171
+ }
1172
+ }
1173
+ requestObject = __spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadProps(__spreadValues(__spreadValues(__spreadValues({
1174
+ taskType: "imageInference" /* IMAGE_INFERENCE */,
1175
+ model,
1176
+ positivePrompt
1177
+ }, negativePrompt ? { negativePrompt } : {}), height ? { height } : {}), width ? { width } : {}), {
1178
+ numberResults
1179
+ }), (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({
1180
+ key: "usePromptWeighting",
1181
+ value: usePromptWeighting
1182
+ })), evaluateNonTrue({ key: "steps", value: steps })), controlNetData.length ? { controlNet: controlNetData } : {}), seed ? { seed } : {}), scheduler ? { scheduler } : {}), evaluateNonTrue({ key: "includeCost", value: includeCost })), seedImageUUID ? { seedImage: seedImageUUID } : {}), maskImageUUID ? { maskImage: maskImageUUID } : {});
1183
+ return await asyncRetry(
1184
+ async () => {
1185
+ retryCount++;
1186
+ lis == null ? void 0 : lis.destroy();
1187
+ const imagesWithSimilarTask = this._globalImages.filter(
1188
+ (img) => taskUUIDs.includes(img.taskUUID)
1189
+ );
1190
+ const taskUUID = customTaskUUID || getUUID();
1191
+ taskUUIDs.push(taskUUID);
1192
+ const imageRemaining = numberResults - imagesWithSimilarTask.length;
1193
+ const newRequestObject = __spreadProps(__spreadValues({}, requestObject), {
1194
+ taskUUID,
1195
+ numberResults: imageRemaining
1196
+ });
1197
+ this.send(newRequestObject);
1198
+ lis = this.listenToImages({
1199
+ onPartialImages,
1200
+ taskUUID,
1201
+ groupKey: "REQUEST_IMAGES" /* REQUEST_IMAGES */,
1202
+ positivePrompt,
1203
+ negativePrompt
1204
+ });
1205
+ const promise = await this.getSimilarImages({
1206
+ taskUUID: taskUUIDs,
1207
+ numberResults,
1208
+ lis
1209
+ });
1210
+ lis.destroy();
1211
+ return promise;
1212
+ },
1213
+ {
1214
+ maxRetries: totalRetry,
1215
+ callback: () => {
1216
+ lis == null ? void 0 : lis.destroy();
1217
+ }
1218
+ }
1219
+ );
1220
+ } catch (e) {
1221
+ if (e.taskUUID) {
1222
+ throw e;
1223
+ }
1224
+ if (retryCount >= totalRetry) {
1225
+ return this.handleIncompleteImages({ taskUUIDs, error: e });
1226
+ }
1227
+ }
1228
+ }
1229
+ async ensureConnection() {
1230
+ var _a;
1231
+ let isConnected = this.connected();
1232
+ if (isConnected || this._url === BASE_RUNWARE_URLS.TEST)
1233
+ return;
1234
+ const retryInterval = 2e3;
1235
+ const pollingInterval = 200;
1236
+ try {
1237
+ if (this._invalidAPIkey)
1238
+ throw this._invalidAPIkey;
1239
+ return new Promise((resolve, reject) => {
1240
+ let retry = 0;
1241
+ const MAX_RETRY = 30;
1242
+ const SHOULD_RETRY = 30 / 2 === retry;
1243
+ let retryIntervalId;
1244
+ let pollingIntervalId;
1245
+ const clearAllIntervals = () => {
1246
+ clearInterval(retryIntervalId);
1247
+ clearInterval(pollingIntervalId);
1248
+ };
1249
+ if (this._sdkType === "SERVER" /* SERVER */) {
1250
+ retryIntervalId = setInterval(async () => {
1251
+ try {
1252
+ const hasConnected = this.connected();
1253
+ if (hasConnected) {
1254
+ clearAllIntervals();
1255
+ resolve(true);
1256
+ } else if (retry >= MAX_RETRY) {
1257
+ clearAllIntervals();
1258
+ reject(new Error("Retry timed out"));
1259
+ } else {
1260
+ if (SHOULD_RETRY) {
1261
+ this.connect();
1262
+ }
1263
+ retry++;
1264
+ }
1265
+ } catch (error) {
1266
+ clearAllIntervals();
1267
+ reject(error);
1268
+ }
1269
+ }, retryInterval);
1270
+ }
1271
+ pollingIntervalId = setInterval(async () => {
1272
+ const hasConnected = this.connected();
1273
+ if (hasConnected) {
1274
+ clearAllIntervals();
1275
+ resolve(true);
1276
+ return;
1277
+ }
1278
+ if (!!this._invalidAPIkey) {
1279
+ clearAllIntervals();
1280
+ reject(this._invalidAPIkey);
1281
+ return;
1282
+ }
1283
+ }, pollingInterval);
1284
+ });
1285
+ } catch (e) {
1286
+ throw (_a = this._invalidAPIkey) != null ? _a : "Could not connect to server. Ensure your API key is correct";
1287
+ }
1288
+ }
1289
+ async getSimilarImages({
1290
+ taskUUID,
1291
+ numberResults,
1292
+ shouldThrowError,
1293
+ lis
1294
+ }) {
1295
+ return await getIntervalWithPromise(
1296
+ ({ resolve, reject, intervalId }) => {
1297
+ const taskUUIDs = Array.isArray(taskUUID) ? taskUUID : [taskUUID];
1298
+ const imagesWithSimilarTask = this._globalImages.filter(
1299
+ (img) => taskUUIDs.includes(img.taskUUID)
1300
+ );
1301
+ if (this._globalError) {
1302
+ const newData = this._globalError;
1303
+ this._globalError = void 0;
1304
+ clearInterval(intervalId);
1305
+ reject == null ? void 0 : reject(newData);
1306
+ return true;
1307
+ } else if (imagesWithSimilarTask.length >= numberResults) {
1308
+ clearInterval(intervalId);
1309
+ this._globalImages = this._globalImages.filter(
1310
+ (img) => !taskUUIDs.includes(img.taskUUID)
1311
+ );
1312
+ resolve([...imagesWithSimilarTask].slice(0, numberResults));
1313
+ return true;
1314
+ }
1315
+ },
1316
+ {
1317
+ debugKey: "getting images",
1318
+ shouldThrowError,
1319
+ timeoutDuration: this._timeoutDuration
1320
+ }
1321
+ );
1322
+ }
1323
+ handleIncompleteImages({
1324
+ taskUUIDs,
1325
+ error
1326
+ }) {
1327
+ const imagesWithSimilarTask = this._globalImages.filter(
1328
+ (img) => taskUUIDs.includes(img.taskUUID)
1329
+ );
1330
+ if (imagesWithSimilarTask.length > 1) {
1331
+ this._globalImages = this._globalImages.filter(
1332
+ (img) => !taskUUIDs.includes(img.taskUUID)
1333
+ );
1334
+ return imagesWithSimilarTask;
1335
+ } else {
1336
+ throw error;
1337
+ }
1338
+ }
1339
+ //end of data
1340
+ };
1341
+
1342
+ // Runware/Runware-client.ts
1343
+ var import_reconnect = __toESM(require_reconnect(), 1);
1344
+ var RunwareClient = class extends RunwareBase {
1345
+ constructor(props) {
1346
+ const _a = props, { shouldReconnect } = _a, rest = __objRest(_a, ["shouldReconnect"]);
1347
+ super(rest);
1348
+ this._ws = new import_reconnect.default(
1349
+ this._url
1350
+ );
1351
+ this.connect();
1352
+ }
1353
+ };
1354
+
1355
+ // Runware/Runware-server.ts
1356
+ var import_ws = __toESM(require("ws"), 1);
1357
+ var RunwareServer = class extends RunwareBase {
1358
+ constructor(props) {
1359
+ super(props);
1360
+ this._instantiated = false;
1361
+ this._listeners = [];
1362
+ this._reconnectingIntervalId = null;
1363
+ this.send = (msg) => {
1364
+ this._ws.send(JSON.stringify([msg]));
1365
+ };
1366
+ this.resetConnection = () => {
1367
+ if (this._ws) {
1368
+ this._listeners.forEach((list) => {
1369
+ var _a;
1370
+ (_a = list == null ? void 0 : list.destroy) == null ? void 0 : _a.call(list);
1371
+ });
1372
+ this._ws.removeAllListeners();
1373
+ this._ws.terminate();
1374
+ this._ws.close();
1375
+ this._ws = null;
1376
+ this._listeners = [];
1377
+ }
1378
+ };
1379
+ this._sdkType = "SERVER" /* SERVER */;
1380
+ this.connect();
1381
+ }
1382
+ // protected addListener({
1383
+ // lis,
1384
+ // check,
1385
+ // groupKey,
1386
+ // }: {
1387
+ // lis: (v: any) => any;
1388
+ // check: (v: any) => any;
1389
+ // groupKey?: string;
1390
+ // }) {
1391
+ // const listener = (msg: any) => {
1392
+ // if (msg?.error) {
1393
+ // lis(msg);
1394
+ // } else if (check(msg)) {
1395
+ // lis(msg);
1396
+ // }
1397
+ // };
1398
+ // const groupListener = { key: getUUID(), listener, groupKey };
1399
+ // this._listeners.push(groupListener);
1400
+ // const destroy = () => {
1401
+ // this._listeners = removeListener(this._listeners, groupListener);
1402
+ // };
1403
+ // return {
1404
+ // destroy,
1405
+ // };
1406
+ // }
1407
+ async connect() {
1408
+ if (!this._url)
1409
+ return;
1410
+ this.resetConnection();
1411
+ this._ws = new import_ws.default(this._url, {
1412
+ perMessageDeflate: false
1413
+ });
1414
+ this._ws.on("error", () => {
1415
+ });
1416
+ this._ws.on("close", () => {
1417
+ this.handleClose();
1418
+ });
1419
+ this._ws.on("open", () => {
1420
+ if (this._reconnectingIntervalId) {
1421
+ clearInterval(this._reconnectingIntervalId);
1422
+ }
1423
+ if (this._connectionSessionUUID && this.isWebsocketReadyState()) {
1424
+ this.send({
1425
+ taskType: "authentication" /* AUTHENTICATION */,
1426
+ apiKey: this._apiKey,
1427
+ connectionSessionUUID: this._connectionSessionUUID
1428
+ });
1429
+ } else {
1430
+ if (this.isWebsocketReadyState()) {
1431
+ this.send({
1432
+ apiKey: this._apiKey,
1433
+ taskType: "authentication" /* AUTHENTICATION */
1434
+ });
1435
+ }
1436
+ }
1437
+ this.addListener({
1438
+ taskUUID: "authentication" /* AUTHENTICATION */,
1439
+ lis: (m) => {
1440
+ var _a, _b;
1441
+ if (m == null ? void 0 : m.error) {
1442
+ this._invalidAPIkey = m;
1443
+ return;
1444
+ }
1445
+ this._connectionSessionUUID = (_b = (_a = m == null ? void 0 : m["authentication" /* AUTHENTICATION */]) == null ? void 0 : _a[0]) == null ? void 0 : _b.connectionSessionUUID;
1446
+ this._invalidAPIkey = void 0;
1447
+ }
1448
+ });
1449
+ });
1450
+ this._ws.on("message", (e, isBinary) => {
1451
+ const data = isBinary ? e : e == null ? void 0 : e.toString();
1452
+ if (!data)
1453
+ return;
1454
+ const m = JSON.parse(data);
1455
+ this._listeners.forEach((lis) => {
1456
+ const result = lis.listener(m);
1457
+ if (result) {
1458
+ return;
1459
+ }
1460
+ });
1461
+ });
1462
+ }
1463
+ handleClose() {
1464
+ if (this._invalidAPIkey) {
1465
+ return;
1466
+ }
1467
+ if (this._reconnectingIntervalId) {
1468
+ clearInterval(this._reconnectingIntervalId);
1469
+ }
1470
+ if (this._shouldReconnect) {
1471
+ setTimeout(() => this.connect(), 1e3);
1472
+ }
1473
+ }
1474
+ heartBeat() {
1475
+ clearTimeout(this._pingTimeout);
1476
+ this._pingTimeout = setTimeout(() => {
1477
+ if (this.isWebsocketReadyState()) {
1478
+ this.send({ ping: true });
1479
+ }
1480
+ }, 5e3);
1481
+ }
1482
+ //end of data
1483
+ };
1484
+
1485
+ // Runware/Runware.ts
1486
+ var Runware;
1487
+ if (typeof window === "undefined") {
1488
+ Runware = RunwareServer;
1489
+ } else {
1490
+ Runware = RunwareClient;
1491
+ }
1492
+ // Annotate the CommonJS export names for ESM import in node:
1493
+ 0 && (module.exports = {
1494
+ EControlMode,
1495
+ EOpenPosePreProcessor,
1496
+ EPreProcessor,
1497
+ EPreProcessorGroup,
1498
+ ETaskType,
1499
+ Environment,
1500
+ Runware,
1501
+ RunwareClient,
1502
+ RunwareServer,
1503
+ SdkType
1504
+ });