@runware/sdk-js 1.1.20-beta.2 → 1.1.20-beta.4

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