@runware/sdk-js 1.2.7 → 1.2.8
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 +4 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +77 -7
- package/dist/index.d.ts +77 -7
- package/dist/index.js +4 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/readme.md +4 -0
package/dist/index.d.cts
CHANGED
|
@@ -1,3 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runware SDK Telemetry Logger
|
|
3
|
+
*
|
|
4
|
+
* Beautiful colored console output for debugging SDK internals.
|
|
5
|
+
* Only active when `enableLogging: true` is passed during instantiation.
|
|
6
|
+
*
|
|
7
|
+
* Usage:
|
|
8
|
+
* const runware = new RunwareServer({ apiKey: "...", enableLogging: true });
|
|
9
|
+
*/
|
|
10
|
+
declare enum LogLevel {
|
|
11
|
+
CONNECTION = "CONNECTION",
|
|
12
|
+
AUTH = "AUTH",
|
|
13
|
+
HEARTBEAT = "HEARTBEAT",
|
|
14
|
+
SEND = "SEND",
|
|
15
|
+
RECEIVE = "RECEIVE",
|
|
16
|
+
RETRY = "RETRY",
|
|
17
|
+
REQUEST = "REQUEST",
|
|
18
|
+
ERROR = "ERROR",
|
|
19
|
+
WARN = "WARN",
|
|
20
|
+
INFO = "INFO"
|
|
21
|
+
}
|
|
22
|
+
declare class RunwareLogger {
|
|
23
|
+
private enabled;
|
|
24
|
+
constructor(enabled?: boolean);
|
|
25
|
+
private log;
|
|
26
|
+
connecting(url: string): void;
|
|
27
|
+
connected(sessionUUID: string): void;
|
|
28
|
+
reconnecting(attempt: number): void;
|
|
29
|
+
reconnectScheduled(delayMs: number): void;
|
|
30
|
+
disconnected(reason?: string): void;
|
|
31
|
+
connectionClosed(code?: number): void;
|
|
32
|
+
connectionError(error?: any): void;
|
|
33
|
+
ensureConnectionStart(): void;
|
|
34
|
+
ensureConnectionSuccess(): void;
|
|
35
|
+
ensureConnectionTimeout(): void;
|
|
36
|
+
authenticating(hasSession: boolean): void;
|
|
37
|
+
authenticated(sessionUUID: string): void;
|
|
38
|
+
authError(error: any): void;
|
|
39
|
+
heartbeatStarted(intervalMs: number): void;
|
|
40
|
+
heartbeatPingSent(): void;
|
|
41
|
+
heartbeatPongReceived(): void;
|
|
42
|
+
heartbeatPongMissed(count: number, max: number): void;
|
|
43
|
+
heartbeatStopped(): void;
|
|
44
|
+
messageSent(taskType: string, taskUUID?: string): void;
|
|
45
|
+
messageReceived(taskType?: string, taskUUID?: string): void;
|
|
46
|
+
sendReconnecting(): void;
|
|
47
|
+
sendFailed(error: string): void;
|
|
48
|
+
requestStart(taskType: string, taskUUID: string): void;
|
|
49
|
+
requestComplete(taskType: string, taskUUID: string, durationMs: number): void;
|
|
50
|
+
requestTimeout(taskUUID: string, timeoutMs: number): void;
|
|
51
|
+
requestError(taskUUID: string, error: any): void;
|
|
52
|
+
retryAttempt(attempt: number, maxRetries: number, delayMs: number): void;
|
|
53
|
+
retrySuccess(attempt: number): void;
|
|
54
|
+
retryExhausted(maxRetries: number): void;
|
|
55
|
+
retrySkippedApiError(code: string): void;
|
|
56
|
+
info(message: string, data?: any): void;
|
|
57
|
+
warn(message: string, data?: any): void;
|
|
58
|
+
error(message: string, data?: any): void;
|
|
59
|
+
}
|
|
60
|
+
declare function createLogger(enabled: boolean): RunwareLogger;
|
|
61
|
+
|
|
1
62
|
declare enum Environment {
|
|
2
63
|
PRODUCTION = "PRODUCTION",
|
|
3
64
|
DEVELOPMENT = "DEVELOPMENT",
|
|
@@ -34,6 +95,8 @@ type RunwareBaseType = {
|
|
|
34
95
|
shouldReconnect?: boolean;
|
|
35
96
|
globalMaxRetries?: number;
|
|
36
97
|
timeoutDuration?: number;
|
|
98
|
+
heartbeatInterval?: number;
|
|
99
|
+
enableLogging?: boolean;
|
|
37
100
|
};
|
|
38
101
|
type IOutputType = "base64Data" | "dataURI" | "URL";
|
|
39
102
|
type IOutputFormat = "JPG" | "PNG" | "WEBP";
|
|
@@ -842,8 +905,14 @@ declare class RunwareBase {
|
|
|
842
905
|
_shouldReconnect: boolean;
|
|
843
906
|
_globalMaxRetries: number;
|
|
844
907
|
_timeoutDuration: number;
|
|
908
|
+
_heartbeatIntervalId: any;
|
|
909
|
+
_pongTimeoutId: any;
|
|
910
|
+
_heartbeatInterval: number;
|
|
911
|
+
_missedPongCount: number;
|
|
912
|
+
_maxMissedPongs: number;
|
|
845
913
|
ensureConnectionUUID: string | null;
|
|
846
|
-
|
|
914
|
+
_logger: RunwareLogger;
|
|
915
|
+
constructor({ apiKey, url, shouldReconnect, globalMaxRetries, timeoutDuration, heartbeatInterval, enableLogging, }: RunwareBaseType);
|
|
847
916
|
private getUniqueUUID;
|
|
848
917
|
/**
|
|
849
918
|
* Shared polling logic for async results.
|
|
@@ -855,6 +924,9 @@ declare class RunwareBase {
|
|
|
855
924
|
static initialize(props: RunwareBaseType): Promise<RunwareBase>;
|
|
856
925
|
protected isWebsocketReadyState: () => boolean;
|
|
857
926
|
protected isInvalidAPIKey: () => boolean;
|
|
927
|
+
protected startHeartbeat(): void;
|
|
928
|
+
protected stopHeartbeat(): void;
|
|
929
|
+
protected handlePongMessage(data: any): boolean;
|
|
858
930
|
protected addListener({ lis, groupKey, taskUUID, }: {
|
|
859
931
|
lis: (v: any) => any;
|
|
860
932
|
groupKey?: string;
|
|
@@ -863,7 +935,7 @@ declare class RunwareBase {
|
|
|
863
935
|
destroy: () => void;
|
|
864
936
|
};
|
|
865
937
|
protected connect(): void;
|
|
866
|
-
protected send: (msg: Object) => void
|
|
938
|
+
protected send: (msg: Object) => Promise<void>;
|
|
867
939
|
private destroy;
|
|
868
940
|
private uploadImage;
|
|
869
941
|
private listenToResponse;
|
|
@@ -939,16 +1011,14 @@ declare class RunwareServer extends RunwareBase {
|
|
|
939
1011
|
_instantiated: boolean;
|
|
940
1012
|
_listeners: any[];
|
|
941
1013
|
_reconnectingIntervalId: null | any;
|
|
942
|
-
|
|
943
|
-
_pongListener: any;
|
|
1014
|
+
private _connecting;
|
|
944
1015
|
constructor(props: RunwareBaseType);
|
|
945
1016
|
protected connect(): Promise<void>;
|
|
946
|
-
protected send: (msg: Object) => void
|
|
1017
|
+
protected send: (msg: Object) => Promise<void>;
|
|
947
1018
|
protected handleClose(): void;
|
|
948
1019
|
protected resetConnection: () => void;
|
|
949
|
-
protected heartBeat(): void;
|
|
950
1020
|
}
|
|
951
1021
|
|
|
952
1022
|
declare let Runware: typeof RunwareClient | typeof RunwareServer;
|
|
953
1023
|
|
|
954
|
-
export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseAsyncCallBackType, type GetWithPromiseCallBackType, type IAddModelResponse, type IAdditionalResponsePayload, type IAsyncResults, type IAudio, type IAudioOutputFormat, type IBflProviderSettings, type IControlNet, type IControlNetGeneral, type IControlNetImage, type IControlNetPreprocess, type IControlNetWithUUID, type IEmbedding, type IEnhancedPrompt, type IError, type IErrorResponse, type IImage, type IImageToText, type IOutpaint, type IOutputFormat, type IOutputType, type IPromptEnhancer, type IProviderSettings, type IRefiner, type IRemoveImage, type IRemoveImageBackground, type IRequestAudio, type IRequestImage, type IRequestImageToText, type IRequestTextInference, type IRequestThreeD, type IRequestVideo, type ITextMessage, type ITextResponse, type ITextToImage, type IThreeDImage, type IThreeDOutputFormat, type IUpscaleGan, type IVideoOutputFormat, type IVideoToImage, type IipAdapter, type ListenerType, type MediaUUID, type ProviderSettings, type ReconnectingWebsocketProps, type RequireAtLeastOne, type RequireOnlyOne, Runware, type RunwareBaseType, RunwareClient, RunwareServer, SDK_VERSION, SdkType, type TAcceleratorOptions, type TAddModel, type TAddModelBaseType, type TAddModelCheckPoint, type TAddModelControlNet, type TAddModelLora, type TImageMasking, type TImageMaskingResponse, type TImageUpload, type TImageUploadResponse, type TMediaStorage, type TMediaStorageResponse, type TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type TServerError, type TVectorize, type TVectorizeResponse, type UploadImageType };
|
|
1024
|
+
export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseAsyncCallBackType, type GetWithPromiseCallBackType, type IAddModelResponse, type IAdditionalResponsePayload, type IAsyncResults, type IAudio, type IAudioOutputFormat, type IBflProviderSettings, type IControlNet, type IControlNetGeneral, type IControlNetImage, type IControlNetPreprocess, type IControlNetWithUUID, type IEmbedding, type IEnhancedPrompt, type IError, type IErrorResponse, type IImage, type IImageToText, type IOutpaint, type IOutputFormat, type IOutputType, type IPromptEnhancer, type IProviderSettings, type IRefiner, type IRemoveImage, type IRemoveImageBackground, type IRequestAudio, type IRequestImage, type IRequestImageToText, type IRequestTextInference, type IRequestThreeD, type IRequestVideo, type ITextMessage, type ITextResponse, type ITextToImage, type IThreeDImage, type IThreeDOutputFormat, type IUpscaleGan, type IVideoOutputFormat, type IVideoToImage, type IipAdapter, type ListenerType, LogLevel, type MediaUUID, type ProviderSettings, type ReconnectingWebsocketProps, type RequireAtLeastOne, type RequireOnlyOne, Runware, type RunwareBaseType, RunwareClient, RunwareLogger, RunwareServer, SDK_VERSION, SdkType, type TAcceleratorOptions, type TAddModel, type TAddModelBaseType, type TAddModelCheckPoint, type TAddModelControlNet, type TAddModelLora, type TImageMasking, type TImageMaskingResponse, type TImageUpload, type TImageUploadResponse, type TMediaStorage, type TMediaStorageResponse, type TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type TServerError, type TVectorize, type TVectorizeResponse, type UploadImageType, createLogger };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runware SDK Telemetry Logger
|
|
3
|
+
*
|
|
4
|
+
* Beautiful colored console output for debugging SDK internals.
|
|
5
|
+
* Only active when `enableLogging: true` is passed during instantiation.
|
|
6
|
+
*
|
|
7
|
+
* Usage:
|
|
8
|
+
* const runware = new RunwareServer({ apiKey: "...", enableLogging: true });
|
|
9
|
+
*/
|
|
10
|
+
declare enum LogLevel {
|
|
11
|
+
CONNECTION = "CONNECTION",
|
|
12
|
+
AUTH = "AUTH",
|
|
13
|
+
HEARTBEAT = "HEARTBEAT",
|
|
14
|
+
SEND = "SEND",
|
|
15
|
+
RECEIVE = "RECEIVE",
|
|
16
|
+
RETRY = "RETRY",
|
|
17
|
+
REQUEST = "REQUEST",
|
|
18
|
+
ERROR = "ERROR",
|
|
19
|
+
WARN = "WARN",
|
|
20
|
+
INFO = "INFO"
|
|
21
|
+
}
|
|
22
|
+
declare class RunwareLogger {
|
|
23
|
+
private enabled;
|
|
24
|
+
constructor(enabled?: boolean);
|
|
25
|
+
private log;
|
|
26
|
+
connecting(url: string): void;
|
|
27
|
+
connected(sessionUUID: string): void;
|
|
28
|
+
reconnecting(attempt: number): void;
|
|
29
|
+
reconnectScheduled(delayMs: number): void;
|
|
30
|
+
disconnected(reason?: string): void;
|
|
31
|
+
connectionClosed(code?: number): void;
|
|
32
|
+
connectionError(error?: any): void;
|
|
33
|
+
ensureConnectionStart(): void;
|
|
34
|
+
ensureConnectionSuccess(): void;
|
|
35
|
+
ensureConnectionTimeout(): void;
|
|
36
|
+
authenticating(hasSession: boolean): void;
|
|
37
|
+
authenticated(sessionUUID: string): void;
|
|
38
|
+
authError(error: any): void;
|
|
39
|
+
heartbeatStarted(intervalMs: number): void;
|
|
40
|
+
heartbeatPingSent(): void;
|
|
41
|
+
heartbeatPongReceived(): void;
|
|
42
|
+
heartbeatPongMissed(count: number, max: number): void;
|
|
43
|
+
heartbeatStopped(): void;
|
|
44
|
+
messageSent(taskType: string, taskUUID?: string): void;
|
|
45
|
+
messageReceived(taskType?: string, taskUUID?: string): void;
|
|
46
|
+
sendReconnecting(): void;
|
|
47
|
+
sendFailed(error: string): void;
|
|
48
|
+
requestStart(taskType: string, taskUUID: string): void;
|
|
49
|
+
requestComplete(taskType: string, taskUUID: string, durationMs: number): void;
|
|
50
|
+
requestTimeout(taskUUID: string, timeoutMs: number): void;
|
|
51
|
+
requestError(taskUUID: string, error: any): void;
|
|
52
|
+
retryAttempt(attempt: number, maxRetries: number, delayMs: number): void;
|
|
53
|
+
retrySuccess(attempt: number): void;
|
|
54
|
+
retryExhausted(maxRetries: number): void;
|
|
55
|
+
retrySkippedApiError(code: string): void;
|
|
56
|
+
info(message: string, data?: any): void;
|
|
57
|
+
warn(message: string, data?: any): void;
|
|
58
|
+
error(message: string, data?: any): void;
|
|
59
|
+
}
|
|
60
|
+
declare function createLogger(enabled: boolean): RunwareLogger;
|
|
61
|
+
|
|
1
62
|
declare enum Environment {
|
|
2
63
|
PRODUCTION = "PRODUCTION",
|
|
3
64
|
DEVELOPMENT = "DEVELOPMENT",
|
|
@@ -34,6 +95,8 @@ type RunwareBaseType = {
|
|
|
34
95
|
shouldReconnect?: boolean;
|
|
35
96
|
globalMaxRetries?: number;
|
|
36
97
|
timeoutDuration?: number;
|
|
98
|
+
heartbeatInterval?: number;
|
|
99
|
+
enableLogging?: boolean;
|
|
37
100
|
};
|
|
38
101
|
type IOutputType = "base64Data" | "dataURI" | "URL";
|
|
39
102
|
type IOutputFormat = "JPG" | "PNG" | "WEBP";
|
|
@@ -842,8 +905,14 @@ declare class RunwareBase {
|
|
|
842
905
|
_shouldReconnect: boolean;
|
|
843
906
|
_globalMaxRetries: number;
|
|
844
907
|
_timeoutDuration: number;
|
|
908
|
+
_heartbeatIntervalId: any;
|
|
909
|
+
_pongTimeoutId: any;
|
|
910
|
+
_heartbeatInterval: number;
|
|
911
|
+
_missedPongCount: number;
|
|
912
|
+
_maxMissedPongs: number;
|
|
845
913
|
ensureConnectionUUID: string | null;
|
|
846
|
-
|
|
914
|
+
_logger: RunwareLogger;
|
|
915
|
+
constructor({ apiKey, url, shouldReconnect, globalMaxRetries, timeoutDuration, heartbeatInterval, enableLogging, }: RunwareBaseType);
|
|
847
916
|
private getUniqueUUID;
|
|
848
917
|
/**
|
|
849
918
|
* Shared polling logic for async results.
|
|
@@ -855,6 +924,9 @@ declare class RunwareBase {
|
|
|
855
924
|
static initialize(props: RunwareBaseType): Promise<RunwareBase>;
|
|
856
925
|
protected isWebsocketReadyState: () => boolean;
|
|
857
926
|
protected isInvalidAPIKey: () => boolean;
|
|
927
|
+
protected startHeartbeat(): void;
|
|
928
|
+
protected stopHeartbeat(): void;
|
|
929
|
+
protected handlePongMessage(data: any): boolean;
|
|
858
930
|
protected addListener({ lis, groupKey, taskUUID, }: {
|
|
859
931
|
lis: (v: any) => any;
|
|
860
932
|
groupKey?: string;
|
|
@@ -863,7 +935,7 @@ declare class RunwareBase {
|
|
|
863
935
|
destroy: () => void;
|
|
864
936
|
};
|
|
865
937
|
protected connect(): void;
|
|
866
|
-
protected send: (msg: Object) => void
|
|
938
|
+
protected send: (msg: Object) => Promise<void>;
|
|
867
939
|
private destroy;
|
|
868
940
|
private uploadImage;
|
|
869
941
|
private listenToResponse;
|
|
@@ -939,16 +1011,14 @@ declare class RunwareServer extends RunwareBase {
|
|
|
939
1011
|
_instantiated: boolean;
|
|
940
1012
|
_listeners: any[];
|
|
941
1013
|
_reconnectingIntervalId: null | any;
|
|
942
|
-
|
|
943
|
-
_pongListener: any;
|
|
1014
|
+
private _connecting;
|
|
944
1015
|
constructor(props: RunwareBaseType);
|
|
945
1016
|
protected connect(): Promise<void>;
|
|
946
|
-
protected send: (msg: Object) => void
|
|
1017
|
+
protected send: (msg: Object) => Promise<void>;
|
|
947
1018
|
protected handleClose(): void;
|
|
948
1019
|
protected resetConnection: () => void;
|
|
949
|
-
protected heartBeat(): void;
|
|
950
1020
|
}
|
|
951
1021
|
|
|
952
1022
|
declare let Runware: typeof RunwareClient | typeof RunwareServer;
|
|
953
1023
|
|
|
954
|
-
export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseAsyncCallBackType, type GetWithPromiseCallBackType, type IAddModelResponse, type IAdditionalResponsePayload, type IAsyncResults, type IAudio, type IAudioOutputFormat, type IBflProviderSettings, type IControlNet, type IControlNetGeneral, type IControlNetImage, type IControlNetPreprocess, type IControlNetWithUUID, type IEmbedding, type IEnhancedPrompt, type IError, type IErrorResponse, type IImage, type IImageToText, type IOutpaint, type IOutputFormat, type IOutputType, type IPromptEnhancer, type IProviderSettings, type IRefiner, type IRemoveImage, type IRemoveImageBackground, type IRequestAudio, type IRequestImage, type IRequestImageToText, type IRequestTextInference, type IRequestThreeD, type IRequestVideo, type ITextMessage, type ITextResponse, type ITextToImage, type IThreeDImage, type IThreeDOutputFormat, type IUpscaleGan, type IVideoOutputFormat, type IVideoToImage, type IipAdapter, type ListenerType, type MediaUUID, type ProviderSettings, type ReconnectingWebsocketProps, type RequireAtLeastOne, type RequireOnlyOne, Runware, type RunwareBaseType, RunwareClient, RunwareServer, SDK_VERSION, SdkType, type TAcceleratorOptions, type TAddModel, type TAddModelBaseType, type TAddModelCheckPoint, type TAddModelControlNet, type TAddModelLora, type TImageMasking, type TImageMaskingResponse, type TImageUpload, type TImageUploadResponse, type TMediaStorage, type TMediaStorageResponse, type TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type TServerError, type TVectorize, type TVectorizeResponse, type UploadImageType };
|
|
1024
|
+
export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseAsyncCallBackType, type GetWithPromiseCallBackType, type IAddModelResponse, type IAdditionalResponsePayload, type IAsyncResults, type IAudio, type IAudioOutputFormat, type IBflProviderSettings, type IControlNet, type IControlNetGeneral, type IControlNetImage, type IControlNetPreprocess, type IControlNetWithUUID, type IEmbedding, type IEnhancedPrompt, type IError, type IErrorResponse, type IImage, type IImageToText, type IOutpaint, type IOutputFormat, type IOutputType, type IPromptEnhancer, type IProviderSettings, type IRefiner, type IRemoveImage, type IRemoveImageBackground, type IRequestAudio, type IRequestImage, type IRequestImageToText, type IRequestTextInference, type IRequestThreeD, type IRequestVideo, type ITextMessage, type ITextResponse, type ITextToImage, type IThreeDImage, type IThreeDOutputFormat, type IUpscaleGan, type IVideoOutputFormat, type IVideoToImage, type IipAdapter, type ListenerType, LogLevel, type MediaUUID, type ProviderSettings, type ReconnectingWebsocketProps, type RequireAtLeastOne, type RequireOnlyOne, Runware, type RunwareBaseType, RunwareClient, RunwareLogger, RunwareServer, SDK_VERSION, SdkType, type TAcceleratorOptions, type TAddModel, type TAddModelBaseType, type TAddModelCheckPoint, type TAddModelControlNet, type TAddModelLora, type TImageMasking, type TImageMaskingResponse, type TImageUpload, type TImageUploadResponse, type TMediaStorage, type TMediaStorageResponse, type TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type TServerError, type TVectorize, type TVectorizeResponse, type UploadImageType, createLogger };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,5 @@
|
|
|
1
|
-
var Ge=Object.create;var ge=Object.defineProperty;var He=Object.getOwnPropertyDescriptor;var je=Object.getOwnPropertyNames;var Qe=Object.getPrototypeOf,ze=Object.prototype.hasOwnProperty;var Xe=(l,e)=>()=>(e||l((e={exports:{}}).exports,e),e.exports);var $e=(l,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of je(e))!ze.call(l,n)&&n!==t&&ge(l,n,{get:()=>e[n],enumerable:!(s=He(e,n))||s.enumerable});return l};var Je=(l,e,t)=>(t=l!=null?Ge(Qe(l)):{},$e(e||!l||!l.__esModule?ge(t,"default",{value:l,enumerable:!0}):t,l));var Me=Xe((_s,Ee)=>{"use strict";var we=l=>l&&l.CLOSING===2,lt=()=>typeof WebSocket<"u"&&we(WebSocket),ut=()=>({constructor:lt()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),ct=(l,e,t)=>{Object.defineProperty(e,t,{get:()=>l[t],set:s=>{l[t]=s},enumerable:!0,configurable:!0})},Se=l=>l.minReconnectionDelay+Math.random()*l.minReconnectionDelay,dt=(l,e)=>{let t=e*l.reconnectionDelayGrowFactor;return t>l.maxReconnectionDelay?l.maxReconnectionDelay:t},pt=["onopen","onclose","onmessage","onerror"],gt=(l,e,t)=>{Object.keys(t).forEach(s=>{t[s].forEach(([n,o])=>{l.addEventListener(s,n,o)})}),e&&pt.forEach(s=>{l[s]=e[s]})},Ae=function(l,e,t={}){let s,n,o=0,r=0,a=!0,i={};if(!(this instanceof Ae))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let d=ut();if(Object.keys(d).filter(c=>t.hasOwnProperty(c)).forEach(c=>d[c]=t[c]),!we(d.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");let m=d.debug?(...c)=>console.log("RWS:",...c):()=>{},g=(c,y)=>setTimeout(()=>{let U=new Error(y);U.code=c,Array.isArray(i.error)&&i.error.forEach(([b])=>b(U)),s.onerror&&s.onerror(U)},0),p=()=>{if(m("close"),r++,m("retries count:",r),r>d.maxRetries){g("EHOSTDOWN","Too many failed connection attempts");return}o?o=dt(d,o):o=Se(d),m("reconnectDelay:",o),a&&setTimeout(u,o)},u=()=>{m("connect");let c=s;s=new d.constructor(l,e),n=setTimeout(()=>{m("timeout"),s.close(),g("ETIMEDOUT","Connection timeout")},d.connectionTimeout),m("bypass properties");for(let y in s)["addEventListener","removeEventListener","close","send"].indexOf(y)<0&&ct(s,this,y);s.addEventListener("open",()=>{clearTimeout(n),m("open"),o=Se(d),m("reconnectDelay:",o),r=0}),s.addEventListener("close",p),gt(s,c,i)};m("init"),u(),this.close=(c=1e3,y="",{keepClosed:U=!1,fastClose:b=!0,delay:f=0}={})=>{if(f&&(o=f),a=!U,s.close(c,y),b){let h={code:c,reason:y,wasClean:!0};p(),Array.isArray(i.close)&&i.close.forEach(([k,I])=>{k(h),s.removeEventListener("close",k,I)}),s.onclose&&(s.onclose(h),s.onclose=null)}},this.send=c=>{s.send(c)},this.addEventListener=(c,y,U)=>{Array.isArray(i[c])?i[c].some(([b])=>b===y)||i[c].push([y,U]):i[c]=[[y,U]],s.addEventListener(c,y,U)},this.removeEventListener=(c,y,U)=>{Array.isArray(i[c])&&(i[c]=i[c].filter(([b])=>b!==y)),s.removeEventListener(c,y,U)}};Ee.exports=Ae});var me=(s=>(s.PRODUCTION="PRODUCTION",s.DEVELOPMENT="DEVELOPMENT",s.TEST="TEST",s))(me||{}),J=(t=>(t.CLIENT="CLIENT",t.SERVER="SERVER",t))(J||{}),Z=(h=>(h.IMAGE_INFERENCE="imageInference",h.IMAGE_UPLOAD="imageUpload",h.UPSCALE="upscale",h.REMOVE_BACKGROUND="removeBackground",h.VIDEO_INFERENCE="videoInference",h.CAPTION="caption",h.AUDIO_INFERENCE="audioInference",h.THREE_D_INFERENCE="3dInference",h.GET_RESPONSE="getResponse",h.PHOTO_MAKER="photoMaker",h.IMAGE_CONTROL_NET_PRE_PROCESS="imageControlNetPreProcess",h.IMAGE_MASKING="imageMasking",h.PROMPT_ENHANCE="promptEnhance",h.AUTHENTICATION="authentication",h.MODEL_UPLOAD="modelUpload",h.MODEL_SEARCH="modelSearch",h.MEDIA_STORAGE="mediaStorage",h.VECTORIZE="vectorize",h.TEXT_INFERENCE="textInference",h))(Z||{}),Ie=(s=>(s.BALANCED="balanced",s.PROMPT="prompt",s.CONTROL_NET="controlnet",s))(Ie||{}),ye=(p=>(p.canny="canny",p.depth="depth",p.mlsd="mlsd",p.normalbae="normalbae",p.openpose="openpose",p.tile="tile",p.seg="seg",p.lineart="lineart",p.lineart_anime="lineart_anime",p.shuffle="shuffle",p.scribble="scribble",p.softedge="softedge",p))(ye||{}),he=(T=>(T.canny="canny",T.depth_leres="depth_leres",T.depth_midas="depth_midas",T.depth_zoe="depth_zoe",T.inpaint_global_harmonious="inpaint_global_harmonious",T.lineart_anime="lineart_anime",T.lineart_coarse="lineart_coarse",T.lineart_realistic="lineart_realistic",T.lineart_standard="lineart_standard",T.mlsd="mlsd",T.normal_bae="normal_bae",T.scribble_hed="scribble_hed",T.scribble_pidinet="scribble_pidinet",T.seg_ofade20k="seg_ofade20k",T.seg_ofcoco="seg_ofcoco",T.seg_ufade20k="seg_ufade20k",T.shuffle="shuffle",T.softedge_hed="softedge_hed",T.softedge_hedsafe="softedge_hedsafe",T.softedge_pidinet="softedge_pidinet",T.softedge_pidisafe="softedge_pidisafe",T.tile_gaussian="tile_gaussian",T.openpose="openpose",T.openpose_face="openpose_face",T.openpose_faceonly="openpose_faceonly",T.openpose_full="openpose_full",T.openpose_hand="openpose_hand",T))(he||{}),Ze=(o=>(o.openpose="openpose",o.openpose_face="openpose_face",o.openpose_faceonly="openpose_faceonly",o.openpose_full="openpose_full",o.openpose_hand="openpose_hand",o))(Ze||{}),Ye=(t=>(t.safetensors="safetensors",t.pickletensor="pickletensor",t))(Ye||{}),et=(u=>(u.flux1d="flux1d",u.flux1s="flux1s",u.pony="pony",u.sdhyper="sdhyper",u.sd1x="sd1x",u.sd1xlcm="sd1xlcm",u.sd3="sd3",u.sdxl="sdxl",u.sdxllcm="sdxllcm",u.sdxldistilled="sdxldistilled",u.sdxlhyper="sdxlhyper",u.sdxllightning="sdxllightning",u.sdxlturbo="sdxlturbo",u))(et||{}),tt=(s=>(s.base="base",s.inpainting="inpainting",s.pix2pix="pix2pix",s))(tt||{}),st=(I=>(I.canny="canny",I.depth="depth",I.qrcode="qrcode",I.hed="hed",I.scrible="scrible",I.openpose="openpose",I.seg="segmentation",I.openmlsd="openmlsd",I.softedge="softedge",I.normal="normal bae",I.shuffle="shuffle",I.pix2pix="pix2pix",I.inpaint="inpaint",I.lineart="line art",I.sketch="sketch",I.inpaintdepth="inpaint depth",I.tile="tile",I.outfit="outfit",I.blur="blur",I.gray="gray",I.lowquality="low quality",I))(st||{}),nt=(g=>(g.NoStyle="No style",g.Cinematic="Cinematic",g.DisneyCharacter="Disney Character",g.DigitalArt="Digital Art",g.Photographic="Photographic",g.FantasyArt="Fantasy art",g.Neonpunk="Neonpunk",g.Enhance="Enhance",g.ComicBook="Comic book",g.Lowpoly="Lowpoly",g.LineArt="Line art",g))(nt||{});import{v4 as ot,validate as at}from"uuid";var Ue={name:"@runware/sdk-js",version:"1.2.7",description:"The SDK is used to run image inference with the Runware API, powered by the RunWare inference platform. It can be used to generate imaged with text-to-image and image-to-image. It also allows the use of an existing gallery of models or selecting any model or LoRA from the CivitAI gallery. The API also supports upscaling, background removal, inpainting and outpainting, and a series of other ControlNet models.",main:"dist/index.js",module:"dist/index.js",types:"dist/index.d.ts",type:"module",exports:{".":{types:"./dist/index.d.ts",require:"./dist/index.cjs",import:"./dist/index.js"}},files:["dist/"],scripts:{build:"tsup",lint:"tsc",pkg:"npx pkgfiles","dev:test":"vitest --reporter verbose",test:"vitest run --reporter verbose","test:single":"vitest run --reporter verbose tests/Runware/upscale-gan.test.ts",debug:"tsx tests/script.ts","beta:tag":"npm publish --tag beta"},keywords:["runware","sdk","ai"],author:"",license:"ISC",devDependencies:{"@types/uuid":"^9.0.6","@types/ws":"^8.5.8",dotenv:"^16.4.5","mock-socket":"^9.3.1",tsup:"^8.3.5",typescript:"^5.2.2",vitest:"^0.34.6"},dependencies:{uuid:"^9.0.1",ws:"^8.18.0"},optionalDependencies:{bufferutil:"^4.0.8"},directories:{test:"tests"}};var q=Ue.version;function W(l){let e=l.includes("?")?"&":"?";return`${l}${e}sdk=js&version=${q}`}var V=6e4,K=1e3,Te=100,Y={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},be=(l,e)=>{if(l==null)return;let t=l.indexOf(e);t!==-1&&l.splice(t,1)},M=(l,{debugKey:e="debugKey",timeoutDuration:t=V,shouldThrowError:s=!0,pollingInterval:n=Te})=>(t=t<K?K:t,new Promise((o,r)=>{let a=setTimeout(()=>{i&&(clearInterval(i),s&&r(`Response could not be received from server for ${e}`)),clearTimeout(a)},t),i=setInterval(async()=>{l({resolve:o,reject:r,intervalId:i})&&(clearInterval(i),clearTimeout(a))},n)})),fe=l=>new Promise(e=>{let t=new FileReader;t.readAsDataURL(l),t.onload=function(){e(t.result)}}),D=()=>ot(),Re=l=>at(l);var ke=({key:l,data:e,useZero:t=!0,shouldReturnString:s=!1})=>l.split(/\.|\[/).map(r=>r.replace(/\]$/,"")).reduce((r,a)=>{let i=t?0:void 0,d=r?.[a];if(!d)return i;if(Array.isArray(d)&&/^\d+$/.test(a)){let m=parseInt(a,10);return m>=0&&m<d.length?r[a]=d[m]:r[a]??i}else return r[a]??i},e||{})??{},De=(l,e=1e3)=>new Promise(t=>setTimeout(t,l*e));var _e=(l,e)=>l.filter(t=>t.key!==e.key);var R=({key:l,value:e})=>e||e===0||e===!1?{[l]:e}:{},it=(l,e)=>Math.floor(Math.random()*(e-l+1))+l,xe=()=>it(1,Number.MAX_SAFE_INTEGER),ve=(l,{debugKey:e="debugKey",timeoutDuration:t=V,shouldThrowError:s=!0,pollingInterval:n=Te})=>(t=t<K?K:t,new Promise((o,r)=>{let a=setTimeout(()=>{i&&(clearInterval(i),s&&r(`Response could not be received from server for ${e}`)),clearTimeout(a)},t),i=setInterval(async()=>{try{await l({resolve:o,reject:r,intervalId:i})&&(clearInterval(i),clearTimeout(a))}catch(d){clearInterval(i),clearTimeout(a),r(d)}},n)}));var x=async(l,e={})=>{let{delayInSeconds:t=1,callback:s}=e,n=e.maxRetries??1;for(;n;)try{return await l()}catch(o){if(s?.(),o?.error)throw o;if(n--,n>0)return await De(t),await x(l,{...e,maxRetries:n});throw o}};var C=class{constructor({apiKey:e,url:t=Y.PRODUCTION,shouldReconnect:s=!0,globalMaxRetries:n=2,timeoutDuration:o=V}){this._listeners=[];this._globalMessages={};this._globalImages=[];this._globalErrors=[];this.ensureConnectionUUID=null;this.isWebsocketReadyState=()=>this._ws?.readyState===1;this.isInvalidAPIKey=()=>this._connectionError?.error?.code==="invalidApiKey";this.send=e=>{this._ws.send(JSON.stringify([e]))};this.uploadImage=async e=>{try{return await x(async()=>{let t=D();if(typeof e=="string"&&Re(e))return{imageURL:e,imageUUID:e,taskUUID:t,taskType:"imageUpload"};let s=typeof e=="string"?e:await fe(e);return{imageURL:s,imageUUID:s,taskUUID:t,taskType:"imageUpload"}})}catch(t){throw t}};this.controlNetPreProcess=async({inputImage:e,preProcessorType:t,height:s,width:n,outputType:o,outputFormat:r,highThresholdCanny:a,lowThresholdCanny:i,includeHandsAndFaceOpenPose:d,includeCost:m,outputQuality:g,customTaskUUID:p,taskUUID:u,retry:c,includeGenerationTime:y,includePayload:U})=>{let b=c||this._globalMaxRetries,f,h=Date.now();try{return await x(async()=>{await this.ensureConnection();let k=await this.uploadImage(e);if(!k?.imageUUID)return null;let I=u||p||D(),w={inputImage:k.imageUUID,taskType:"imageControlNetPreProcess",taskUUID:I,preProcessorType:t,...R({key:"height",value:s}),...R({key:"width",value:n}),...R({key:"outputType",value:o}),...R({key:"outputFormat",value:r}),...R({key:"includeCost",value:m}),...R({key:"highThresholdCanny",value:a}),...R({key:"lowThresholdCanny",value:i}),...R({key:"includeHandsAndFaceOpenPose",value:d}),...g?{outputQuality:g}:{}};this.send({...w}),f=this.globalListener({taskUUID:I});let A=await M(({resolve:S,reject:H})=>{let v=this.getSingleMessage({taskUUID:I});if(v){if(v?.error)return H(v),!0;if(v)return S(v),!0}},{debugKey:"unprocessed-image",timeoutDuration:this._timeoutDuration});return f.destroy(),this.insertAdditionalResponse({response:A,payload:U?w:void 0,startTime:y?h:void 0}),A},{maxRetries:b,callback:()=>{f?.destroy()}})}catch(k){throw k}};this.controlNetPreprocess=async e=>this.controlNetPreProcess(e);this.requestImageToText=async({inputImage:e,inputs:t,includeCost:s,customTaskUUID:n,taskUUID:o,retry:r,includePayload:a,includeGenerationTime:i,deliveryMethod:d,skipResponse:m,model:g})=>{try{let p;e&&(p=await this.uploadImage(e));let c={taskUUID:o||n||D(),taskType:"caption",model:g,inputImage:p?.imageUUID,inputs:t,...R({key:"includeCost",value:s}),retry:r,includePayload:a,includeGenerationTime:i},y=await this.baseSingleRequest({payload:{...c,taskType:"caption"},debugKey:"caption"});if(m)return y;if(d==="async"){let U=y?.taskUUID;return(await this.pollForAsyncResults({taskUUID:U}))[0]}return y}catch(p){throw p}};this.caption=async e=>this.requestImageToText(e);this.removeImageBackground=async e=>{let{skipResponse:t,...s}=e;try{let n=s.deliveryMethod,o=await this.baseSingleRequest({payload:{...s,taskType:"removeBackground"},debugKey:"remove-background"});if(t)return o;if(n==="async"){let r=o?.taskUUID;return(await this.pollForAsyncResults({taskUUID:r}))[0]}return o}catch(n){throw n}};this.removeBackground=async e=>this.removeImageBackground(e);this.vectorize=async e=>this.baseSingleRequest({payload:{...e,taskType:"vectorize"},debugKey:"vectorize"});this.videoInference=async e=>{let{skipResponse:t,inputAudios:s,referenceVideos:n,...o}=e;try{let r=await this.baseSingleRequest({payload:{...o,...s?.length&&{inputAudios:s},...n?.length&&{referenceVideos:n},deliveryMethod:"async",taskType:"videoInference"},debugKey:"video-inference"});if(t)return r;let a=r?.taskUUID;return this.pollForAsyncResults({taskUUID:a,numberResults:e?.numberResults})}catch(r){throw r}};this.audioInference=async e=>{let{skipResponse:t,deliveryMethod:s="sync",...n}=e;try{let r=await(s==="sync"?this.baseSyncRequest:this.baseSingleRequest)({payload:{...n,numberResults:n.numberResults||1,taskType:"audioInference",deliveryMethod:s},groupKey:"REQUEST_AUDIO",debugKey:"audio-inference",skipResponse:t});if(t)return r;let a=r?.taskUUID;return s==="async"?this.pollForAsyncResults({taskUUID:a,numberResults:e?.numberResults}):r}catch(o){throw o}};this.threeDInference=async e=>{let{skipResponse:t,deliveryMethod:s="sync",...n}=e;try{let r=await(s==="sync"?this.baseSyncRequest:this.baseSingleRequest)({payload:{...n,numberResults:n.numberResults||1,taskType:"3dInference",deliveryMethod:s},groupKey:"REQUEST_IMAGES",debugKey:"three-d-inference",skipResponse:t});if(t)return r;let a=r?.taskUUID;return s==="async"?this.pollForAsyncResults({taskUUID:a,numberResults:e?.numberResults}):r}catch(o){throw o}};this.textInference=async e=>{let{skipResponse:t,deliveryMethod:s="sync",...n}=e;try{let r=await(s==="sync"?this.baseSyncRequest:this.baseSingleRequest)({payload:{...n,numberResults:n.numberResults||1,taskType:"textInference",deliveryMethod:s},groupKey:"REQUEST_TEXT",debugKey:"text-inference",skipResponse:t});if(t)return r;let a=r?.taskUUID;return s==="async"?this.pollForAsyncResults({taskUUID:a,numberResults:e?.numberResults}):r}catch(o){throw o}};this.getResponse=async e=>{let t=e.taskUUID;return this.baseSingleRequest({payload:{...e,customTaskUUID:t,taskType:"getResponse"},isMultiple:!0,debugKey:"async-results"})};this.upscaleGan=async e=>{let{inputImage:t,skipResponse:s,deliveryMethod:n="sync",...o}=e;try{let r;t&&(r=await this.uploadImage(t));let a=await this.baseSingleRequest({payload:{...o,...r?.imageUUID?{inputImage:r.imageUUID}:{},taskType:"upscale",deliveryMethod:n},debugKey:"upscale"});if(s)return a;if(n==="async"){let i=a?.taskUUID;return(await this.pollForAsyncResults({taskUUID:i}))[0]}return a}catch(r){throw r}};this.upscale=async e=>this.upscaleGan(e);this.enhancePrompt=async({prompt:e,promptMaxLength:t=380,promptVersions:s=1,includeCost:n,customTaskUUID:o,taskUUID:r,retry:a,includeGenerationTime:i,includePayload:d})=>{let m=a||this._globalMaxRetries,g,p=Date.now();try{return await x(async()=>{await this.ensureConnection();let u=r||o||D(),c={prompt:e,taskUUID:u,promptMaxLength:t,promptVersions:s,...R({key:"includeCost",value:n}),taskType:"promptEnhance"};this.send(c),g=this.globalListener({taskUUID:u});let y=await M(({resolve:U,reject:b})=>{let f=this._globalMessages[u];if(f?.error)return b(f),!0;if(f?.length>=s)return delete this._globalMessages[u],U(f),!0},{debugKey:"enhance-prompt",timeoutDuration:this._timeoutDuration});return g.destroy(),this.insertAdditionalResponse({response:y,payload:d?c:void 0,startTime:i?p:void 0}),y},{maxRetries:m,callback:()=>{g?.destroy()}})}catch(u){throw u}};this.promptEnhance=async e=>this.enhancePrompt(e);this.modelUpload=async e=>{let{onUploadStream:t,retry:s,customTaskUUID:n,taskUUID:o,...r}=e,a=s||this._globalMaxRetries,i;try{return await x(async()=>{await this.ensureConnection();let d=o||n||D();this.send({...r,taskUUID:d,taskType:"modelUpload"});let m,g;return i=this.listenToUpload({taskUUID:d,onUploadStream:(u,c)=>{t?.(u,c),u?.status==="ready"?m=u:c&&(g=c)}}),await M(({resolve:u,reject:c})=>{if(m)return u(m),!0;if(g)return c(g),!1},{shouldThrowError:!1,timeoutDuration:60*60*1e3})},{maxRetries:a,callback:()=>{i?.destroy()}})}catch(d){throw d}};this.photoMaker=async(e,t)=>{let{onPartialImages:s,retry:n,customTaskUUID:o,taskUUID:r,numberResults:a,includeGenerationTime:i,includePayload:d,...m}=e,g=n||this._globalMaxRetries,p,u=[],c=0,y=Date.now();try{return await x(async()=>{await this.ensureConnection(),c++;let U=this._globalImages.filter(I=>u.includes(I.taskUUID)),b=r||o||D();u.push(b);let f=a-U.length,h={...m,...m.seed?{seed:m.seed}:{seed:xe()},...t??{},taskUUID:b,taskType:"photoMaker",numberResults:a};this.send({...h,numberResults:f}),p=this.listenToResponse({onPartialImages:s,taskUUID:b,groupKey:"REQUEST_IMAGES",requestPayload:d?h:void 0,startTime:i?y:void 0});let k=await this.getResponseWithSimilarTaskUUID({taskUUID:u,numberResults:a,lis:p});return p.destroy(),k},{maxRetries:g,callback:()=>{p?.destroy()}})}catch(U){if(U.taskUUID)throw U;if(c>=g)return this.handleIncompleteImages({taskUUIDs:u,error:U})}};this.modelSearch=async e=>this.baseSingleRequest({payload:{...e,taskType:"modelSearch"},debugKey:"model-search"});this.imageMasking=async e=>this.baseSingleRequest({payload:{...e,taskType:"imageMasking"},debugKey:"image-masking"});this.imageUpload=async e=>this.baseSingleRequest({payload:{...e,taskType:"imageUpload"},debugKey:"image-upload"});this.mediaStorage=async e=>this.baseSingleRequest({payload:{...e,operation:e.operation||"upload",taskType:"mediaStorage"},debugKey:"media-storage"});this.baseSingleRequest=async({payload:e,debugKey:t,isMultiple:s})=>{let{retry:n,customTaskUUID:o,taskUUID:r,includePayload:a,includeGenerationTime:i,...d}=e,m=n||this._globalMaxRetries,g,p=Date.now();try{return await x(async()=>{await this.ensureConnection();let u=r||o||D(),c={...d,taskUUID:u};this.send(c),g=this.globalListener({taskUUID:u});let y=await M(({resolve:U,reject:b})=>{let f=s?this.getMultipleMessages({taskUUID:u}):this.getSingleMessage({taskUUID:u});if(f){if(f?.error)return b(f),!0;if(f)return delete this._globalMessages[u],U(f),!0}},{debugKey:t,timeoutDuration:this._timeoutDuration});return this.insertAdditionalResponse({response:y,payload:a?c:void 0,startTime:i?p:void 0}),g.destroy(),y},{maxRetries:m,callback:()=>{g?.destroy()}})}catch(u){throw u}};this.baseSyncRequest=async({payload:e,groupKey:t,skipResponse:s=!1})=>{let{retry:n,customTaskUUID:o,includePayload:r,numberResults:a=1,onPartialResponse:i,includeGenerationTime:d,...m}=e,g=n||this._globalMaxRetries,p,u=[],c=0,y=Date.now();try{return await x(async()=>{await this.ensureConnection(),c++;let U=this._globalImages.filter(I=>u.includes(I.taskUUID)),b=o||D();u.push(b);let f=a-U.length,h={...m,taskUUID:b,numberResults:f};if(this.send(h),s)return new Promise((I,w)=>{let A=this.addListener({taskUUID:b,groupKey:t,lis:S=>{A.destroy(),S.error?w(S.error):I(S[b])}})});p=this.listenToResponse({onPartialImages:i,taskUUID:b,groupKey:t,requestPayload:r?h:void 0,startTime:d?y:void 0});let k=await this.getResponseWithSimilarTaskUUID({taskUUID:u,numberResults:a,lis:p});return p.destroy(),k},{maxRetries:g,callback:()=>{p?.destroy()}})}catch(U){throw U}};this.getSingleMessage=({taskUUID:e})=>{let t=this._globalMessages[e]?.[0],s=this._globalMessages[e];return!t&&!s?null:s?.error?s:t};this.getMultipleMessages=({taskUUID:e})=>{let t=this._globalMessages[e]?.[0],s=this._globalMessages[e];return!t&&!s?null:s};this.insertAdditionalResponse=({response:e,payload:t,startTime:s})=>{if(!t&&!s)return;let n=e;n.additionalResponse={},t&&(e.additionalResponse.payload=t),s&&(e.additionalResponse.generationTime=Date.now()-s)};this.disconnect=async()=>{this._shouldReconnect=!1,this._ws?.terminate?.(),this._ws?.close?.()};this.connected=()=>this.isWebsocketReadyState()&&!!this._connectionSessionUUID;this._apiKey=e,this._url=t,this._sdkType="CLIENT",this._shouldReconnect=s,this._globalMaxRetries=n,this._timeoutDuration=o}getUniqueUUID(e){return e.mediaUUID||e.audioUUID||e.imageUUID||e.videoUUID||e.outputs?.files?.map(t=>t.uuid).join("-")||e.text}async pollForAsyncResults({taskUUID:e,numberResults:t=1}){let s=new Map;return await ve(async({resolve:n,reject:o})=>{try{let r=await this.getResponse({taskUUID:e});for(let i of r||[])if(i.status==="success"){let d=this.getUniqueUUID(i);d&&s.set(d,i)}return s.size===t?(n(Array.from(s.values())),!0):!1}catch(r){return o(r),!0}},{debugKey:"async-response",pollingInterval:2*1e3,timeoutDuration:10*60*1e3}),Array.from(s.values())}static async initialize(e){try{let t=new this(e);return await t.ensureConnection(),t}catch(t){throw t}}addListener({lis:e,groupKey:t,taskUUID:s}){let n=a=>{let i=Array.isArray(a?.data)?a.data:[a.data],d=a?.[0]?.errors?a?.[0]?.errors:Array.isArray(a?.errors)?a.errors:[a.errors],m=i.filter(p=>(p?.taskUUID||p?.taskType)===s);if(d.filter(p=>(p?.taskUUID||p?.taskType)===s).length){e({error:{...d[0]??{}}});return}if(m.length){e({[s]:i});return}},o={key:s||D(),listener:n,groupKey:t};return this._listeners.push(o),{destroy:()=>{this._listeners=_e(this._listeners,o)}}}connect(){this._ws.onopen=e=>{this._connectionSessionUUID?this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.send({apiKey:this._apiKey,taskType:"authentication"}),this.addListener({taskUUID:"authentication",lis:t=>{if(t?.error){this._connectionError=t;return}this._connectionSessionUUID=t?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0}})},this._ws.onmessage=e=>{let t=JSON.parse(e.data);for(let s of this._listeners)if(s?.listener?.(t))return},this._ws.onclose=e=>{this.isInvalidAPIKey()}}destroy(e){be(this._listeners,e)}listenToResponse({onPartialImages:e,taskUUID:t,groupKey:s,requestPayload:n,startTime:o}){return this.addListener({taskUUID:t,lis:r=>{let a=r?.[t]?.filter(i=>i.taskUUID===t);r.error?(e?.(a,r?.error&&r),this._globalErrors.push(r)):(a=a.map(i=>(this.insertAdditionalResponse({response:i,payload:n||void 0,startTime:o||void 0}),{...i})),e?.(a,r?.error&&r),this._sdkType==="CLIENT"?this._globalImages=[...this._globalImages,...(r?.[t]??[]).map(i=>(this.insertAdditionalResponse({response:i,payload:n||void 0,startTime:o||void 0}),{...i}))]:this._globalImages=[...this._globalImages,...a])},groupKey:s})}listenToUpload({onUploadStream:e,taskUUID:t}){return this.addListener({taskUUID:t,lis:s=>{let n=s?.error,o=s?.[t]?.[0],r=o?.taskUUID===t?o:null;(r||n)&&e?.(r||void 0,n)}})}globalListener({taskUUID:e}){return this.addListener({taskUUID:e,lis:t=>{if(t.error){this._globalMessages[e]=t;return}let s=ke({key:e,data:t,useZero:!1});Array.isArray(s)?s.forEach(n=>{this._globalMessages[n.taskUUID]=[...this._globalMessages[n.taskUUID]??[],n]}):this._globalMessages[s.taskUUID]=s}})}async requestImages({outputType:e,outputFormat:t,uploadEndpoint:s,checkNSFW:n,positivePrompt:o,negativePrompt:r,seedImage:a,maskImage:i,strength:d,height:m,width:g,model:p,steps:u,scheduler:c,seed:y,CFGScale:U,clipSkip:b,usePromptWeighting:f,promptWeighting:h,numberResults:k=1,onPartialImages:I,includeCost:w,customTaskUUID:A,taskUUID:S,retry:H,refiner:v,maskMargin:T,outputQuality:ee,controlNet:j,lora:te,embeddings:se,ipAdapters:ne,providerSettings:re,outpaint:oe,acceleratorOptions:ae,advancedFeatures:ie,referenceImages:le,includeGenerationTime:Ne,includePayload:Pe,...ue},Le){let O,ce,P=[],de=0,pe=H||this._globalMaxRetries;try{await this.ensureConnection();let E=null,Q=null,z=[];if(a){let _=await this.uploadImage(a);if(!_)return[];E=_.imageUUID}if(i){let _=await this.uploadImage(i);if(!_)return[];Q=_.imageUUID}if(j?.length)for(let _=0;_<j.length;_++){let N=j[_],{endStep:X,startStep:L,weight:$,guideImage:F,controlMode:Ke,startStepPercentage:qe,endStepPercentage:We,model:Ve}=N,Be=F?await this.uploadImage(F):null;z.push({guideImage:Be?.imageUUID,model:Ve,endStep:X,startStep:L,weight:$,...R({key:"startStepPercentage",value:qe}),...R({key:"endStepPercentage",value:We}),controlMode:Ke||"controlnet"})}ce={taskType:"imageInference",model:p,positivePrompt:o,...r?{negativePrompt:r}:{},...m?{height:m}:{},...g?{width:g}:{},numberResults:k,...e?{outputType:e}:{},...t?{outputFormat:t}:{},...s?{uploadEndpoint:s}:{},...R({key:"checkNSFW",value:n}),...R({key:"strength",value:d}),...R({key:"CFGScale",value:U}),...R({key:"clipSkip",value:b}),...R({key:"maskMargin",value:T}),...R({key:"usePromptWeighting",value:f}),...R({key:"steps",value:u}),...h?{promptWeighting:h}:{},...y?{seed:y}:{},...c?{scheduler:c}:{},...v?{refiner:v}:{},...oe?{outpaint:oe}:{},...R({key:"includeCost",value:w}),...E?{seedImage:E}:{},...Q?{maskImage:Q}:{},...ee?{outputQuality:ee}:{},...z.length?{controlNet:z}:{},...te?.length?{lora:te}:{},...se?.length?{embeddings:se}:{},...ne?.length?{ipAdapters:ne}:{},...re?{providerSettings:re}:{},...ae?{acceleratorOptions:ae}:{},...ie?{advancedFeatures:ie}:{},...le?.length?{referenceImages:le}:{},...ue,...Le??{}};let Fe=Date.now();return await x(async()=>{de++,O?.destroy();let _=this._globalImages.filter(F=>P.includes(F.taskUUID)),N=S||A||D();P.push(N);let X=k-_.length,L={...ce,taskUUID:N,numberResults:X};this.send(L),O=this.listenToResponse({onPartialImages:I,taskUUID:N,groupKey:"REQUEST_IMAGES",requestPayload:Pe?L:void 0,startTime:Ne?Fe:void 0});let $=await this.getResponseWithSimilarTaskUUID({taskUUID:P,numberResults:k,lis:O,deliveryMethod:ue.deliveryMethod});return O.destroy(),$},{maxRetries:pe,callback:()=>{O?.destroy()}})}catch(E){if(de>=pe)return this.handleIncompleteImages({taskUUIDs:P,error:E});throw E}}async imageInference(e,t){return this.requestImages(e,t)}async ensureConnection(){if(this.connected()||this._url===Y.TEST)return;let t=2e3,s=200;try{if(this.isInvalidAPIKey())throw this._connectionError;return new Promise((n,o)=>{let r=0,a=30,i=D(),d,m,g=()=>{this.ensureConnectionUUID=null,clearInterval(d),clearInterval(m)};this._sdkType==="SERVER"&&(d=setInterval(async()=>{try{let p=this.connected(),u=!1;(!this.ensureConnectionUUID||i===this.ensureConnectionUUID)&&(this.ensureConnectionUUID||(this.ensureConnectionUUID=i),u=!0);let c=r%10===0&&u;p?(g(),n(!0)):r>=a?(g(),o(new Error("Retry timed out"))):(c&&this.connect(),r++)}catch(p){g(),o(p)}},t)),m=setInterval(async()=>{if(this.connected()){g(),n(!0);return}if(this.isInvalidAPIKey()){g(),o(this._connectionError);return}},s)})}catch{throw this.ensureConnectionUUID=null,this._connectionError=void 0,this._connectionError??"Could not connect to server. Ensure your API key is correct"}}async getResponseWithSimilarTaskUUID({taskUUID:e,numberResults:t,shouldThrowError:s,lis:n,deliveryMethod:o}){return await M(({resolve:r,reject:a,intervalId:i})=>{let d=Array.isArray(e)?e:[e],m=this._globalImages.filter(u=>d.includes(u.taskUUID)),g=o==="async"&&m.length>0,p=this._globalErrors.filter(u=>d.includes(u.error.taskUUID));if(p.length>0){let u=p[0];return this._globalErrors=this._globalErrors.filter(c=>!d.includes(c.error.taskUUID)),clearInterval(i),a?.(u),!0}else if(m.length>=t||g)return clearInterval(i),this._globalImages=this._globalImages.filter(u=>!d.includes(u.taskUUID)),r([...m].slice(0,t)),!0},{debugKey:"getting images",shouldThrowError:s,timeoutDuration:this._timeoutDuration})}handleIncompleteImages({taskUUIDs:e,error:t}){let s=this._globalImages.filter(n=>e.includes(n.taskUUID));if(s.length>1)return this._globalImages=this._globalImages.filter(n=>!e.includes(n.taskUUID)),s;throw t}};var Ce=Je(Me(),1);var B=class extends C{constructor(e){let{shouldReconnect:t,...s}=e;super(s);let n=W(this._url||"");this._ws=new Ce.default(n),this.connect()}};import mt from"ws";var G=class extends C{constructor(t){super(t);this._instantiated=!1;this._listeners=[];this._reconnectingIntervalId=null;this.send=t=>{this._ws.send(JSON.stringify([t]))};this.resetConnection=()=>{this._ws&&(this._listeners.forEach(t=>{t?.destroy?.()}),this._ws.removeAllListeners(),this._ws.readyState===1&&(this._ws.terminate(),this._ws.close()),this._ws=null,this._listeners=[])};this._sdkType="SERVER",this.connect()}async connect(){if(!this._url)return;this.resetConnection();let t=W(this._url);this._ws=new mt(t,{perMessageDeflate:!1,headers:{"X-SDK-Name":"js","X-SDK-Version":q}}),this._ws.on("error",()=>{}),this._ws.on("close",()=>{this.handleClose()}),this._ws.on("open",()=>{this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._connectionSessionUUID&&this.isWebsocketReadyState()?this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.isWebsocketReadyState()&&this.send({apiKey:this._apiKey,taskType:"authentication"}),this.addListener({taskUUID:"authentication",lis:s=>{if(s?.error){this._connectionError=s;return}this._connectionSessionUUID=s?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0}})}),this._ws.on("message",(s,n)=>{let o=n?s:s?.toString();if(!o)return;let r=JSON.parse(o);this._listeners.forEach(a=>{a.listener(r)})})}handleClose(){this.isInvalidAPIKey()||(this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._shouldReconnect&&setTimeout(()=>this.connect(),1e3))}heartBeat(){clearTimeout(this._pingTimeout),this._pingTimeout=setTimeout(()=>{this.isWebsocketReadyState()&&this.send({ping:!0})},5e3)}};var Oe;typeof window>"u"?Oe=G:Oe=B;export{Ie as EControlMode,et as EModelArchitecture,st as EModelConditioning,Ye as EModelFormat,tt as EModelType,Ze as EOpenPosePreProcessor,nt as EPhotoMakerEnum,he as EPreProcessor,ye as EPreProcessorGroup,Z as ETaskType,me as Environment,Oe as Runware,B as RunwareClient,G as RunwareServer,q as SDK_VERSION,J as SdkType};
|
|
1
|
+
var ze=Object.create;var Ie=Object.defineProperty;var Ye=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var Je=Object.getPrototypeOf,Ze=Object.prototype.hasOwnProperty;var et=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var tt=(a,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Xe(e))!Ze.call(a,o)&&o!==t&&Ie(a,o,{get:()=>e[o],enumerable:!(n=Ye(e,o))||n.enumerable});return a};var nt=(a,e,t)=>(t=a!=null?ze(Je(a)):{},tt(e||!a||!a.__esModule?Ie(t,"default",{value:a,enumerable:!0}):t,a));var Pe=et((Wn,Me)=>{"use strict";var Oe=a=>a&&a.CLOSING===2,bt=()=>typeof WebSocket<"u"&&Oe(WebSocket),Ut=()=>({constructor:bt()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),ft=(a,e,t)=>{Object.defineProperty(e,t,{get:()=>a[t],set:n=>{a[t]=n},enumerable:!0,configurable:!0})},Le=a=>a.minReconnectionDelay+Math.random()*a.minReconnectionDelay,Tt=(a,e)=>{let t=e*a.reconnectionDelayGrowFactor;return t>a.maxReconnectionDelay?a.maxReconnectionDelay:t},Rt=["onopen","onclose","onmessage","onerror"],_t=(a,e,t)=>{Object.keys(t).forEach(n=>{t[n].forEach(([o,s])=>{a.addEventListener(n,o,s)})}),e&&Rt.forEach(n=>{a[n]=e[n]})},Ne=function(a,e,t={}){let n,o,s=0,r=0,i=!0,l={};if(!(this instanceof Ne))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let g=Ut();if(Object.keys(g).filter(p=>t.hasOwnProperty(p)).forEach(p=>g[p]=t[p]),!Oe(g.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");let c=g.debug?(...p)=>console.log("RWS:",...p):()=>{},m=(p,h)=>setTimeout(()=>{let U=new Error(h);U.code=p,Array.isArray(l.error)&&l.error.forEach(([f])=>f(U)),n.onerror&&n.onerror(U)},0),d=()=>{if(c("close"),r++,c("retries count:",r),r>g.maxRetries){m("EHOSTDOWN","Too many failed connection attempts");return}s?s=Tt(g,s):s=Le(g),c("reconnectDelay:",s),i&&setTimeout(u,s)},u=()=>{c("connect");let p=n;n=new g.constructor(a,e),o=setTimeout(()=>{c("timeout"),n.close(),m("ETIMEDOUT","Connection timeout")},g.connectionTimeout),c("bypass properties");for(let h in n)["addEventListener","removeEventListener","close","send"].indexOf(h)<0&&ft(n,this,h);n.addEventListener("open",()=>{clearTimeout(o),c("open"),s=Le(g),c("reconnectDelay:",s),r=0}),n.addEventListener("close",d),_t(n,p,l)};c("init"),u(),this.close=(p=1e3,h="",{keepClosed:U=!1,fastClose:f=!0,delay:R=0}={})=>{if(R&&(s=R),i=!U,n.close(p,h),f){let b={code:p,reason:h,wasClean:!0};d(),Array.isArray(l.close)&&l.close.forEach(([k,y])=>{k(b),n.removeEventListener("close",k,y)}),n.onclose&&(n.onclose(b),n.onclose=null)}},this.send=p=>{n.send(p)},this.addEventListener=(p,h,U)=>{Array.isArray(l[p])?l[p].some(([f])=>f===h)||l[p].push([h,U]):l[p]=[[h,U]],n.addEventListener(p,h,U)},this.removeEventListener=(p,h,U)=>{Array.isArray(l[p])&&(l[p]=l[p].filter(([f])=>f!==h)),n.removeEventListener(p,h,U)}};Me.exports=Ne});var ye=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))(ye||{}),Z=(t=>(t.CLIENT="CLIENT",t.SERVER="SERVER",t))(Z||{}),ee=(b=>(b.IMAGE_INFERENCE="imageInference",b.IMAGE_UPLOAD="imageUpload",b.UPSCALE="upscale",b.REMOVE_BACKGROUND="removeBackground",b.VIDEO_INFERENCE="videoInference",b.CAPTION="caption",b.AUDIO_INFERENCE="audioInference",b.THREE_D_INFERENCE="3dInference",b.GET_RESPONSE="getResponse",b.PHOTO_MAKER="photoMaker",b.IMAGE_CONTROL_NET_PRE_PROCESS="imageControlNetPreProcess",b.IMAGE_MASKING="imageMasking",b.PROMPT_ENHANCE="promptEnhance",b.AUTHENTICATION="authentication",b.MODEL_UPLOAD="modelUpload",b.MODEL_SEARCH="modelSearch",b.MEDIA_STORAGE="mediaStorage",b.VECTORIZE="vectorize",b.TEXT_INFERENCE="textInference",b))(ee||{}),be=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(be||{}),Ue=(d=>(d.canny="canny",d.depth="depth",d.mlsd="mlsd",d.normalbae="normalbae",d.openpose="openpose",d.tile="tile",d.seg="seg",d.lineart="lineart",d.lineart_anime="lineart_anime",d.shuffle="shuffle",d.scribble="scribble",d.softedge="softedge",d))(Ue||{}),fe=(T=>(T.canny="canny",T.depth_leres="depth_leres",T.depth_midas="depth_midas",T.depth_zoe="depth_zoe",T.inpaint_global_harmonious="inpaint_global_harmonious",T.lineart_anime="lineart_anime",T.lineart_coarse="lineart_coarse",T.lineart_realistic="lineart_realistic",T.lineart_standard="lineart_standard",T.mlsd="mlsd",T.normal_bae="normal_bae",T.scribble_hed="scribble_hed",T.scribble_pidinet="scribble_pidinet",T.seg_ofade20k="seg_ofade20k",T.seg_ofcoco="seg_ofcoco",T.seg_ufade20k="seg_ufade20k",T.shuffle="shuffle",T.softedge_hed="softedge_hed",T.softedge_hedsafe="softedge_hedsafe",T.softedge_pidinet="softedge_pidinet",T.softedge_pidisafe="softedge_pidisafe",T.tile_gaussian="tile_gaussian",T.openpose="openpose",T.openpose_face="openpose_face",T.openpose_faceonly="openpose_faceonly",T.openpose_full="openpose_full",T.openpose_hand="openpose_hand",T))(fe||{}),st=(s=>(s.openpose="openpose",s.openpose_face="openpose_face",s.openpose_faceonly="openpose_faceonly",s.openpose_full="openpose_full",s.openpose_hand="openpose_hand",s))(st||{}),rt=(t=>(t.safetensors="safetensors",t.pickletensor="pickletensor",t))(rt||{}),ot=(u=>(u.flux1d="flux1d",u.flux1s="flux1s",u.pony="pony",u.sdhyper="sdhyper",u.sd1x="sd1x",u.sd1xlcm="sd1xlcm",u.sd3="sd3",u.sdxl="sdxl",u.sdxllcm="sdxllcm",u.sdxldistilled="sdxldistilled",u.sdxlhyper="sdxlhyper",u.sdxllightning="sdxllightning",u.sdxlturbo="sdxlturbo",u))(ot||{}),it=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))(it||{}),at=(y=>(y.canny="canny",y.depth="depth",y.qrcode="qrcode",y.hed="hed",y.scrible="scrible",y.openpose="openpose",y.seg="segmentation",y.openmlsd="openmlsd",y.softedge="softedge",y.normal="normal bae",y.shuffle="shuffle",y.pix2pix="pix2pix",y.inpaint="inpaint",y.lineart="line art",y.sketch="sketch",y.inpaintdepth="inpaint depth",y.tile="tile",y.outfit="outfit",y.blur="blur",y.gray="gray",y.lowquality="low quality",y))(at||{}),lt=(m=>(m.NoStyle="No style",m.Cinematic="Cinematic",m.DisneyCharacter="Disney Character",m.DigitalArt="Digital Art",m.Photographic="Photographic",m.FantasyArt="Fantasy art",m.Neonpunk="Neonpunk",m.Enhance="Enhance",m.ComicBook="Comic book",m.Lowpoly="Lowpoly",m.LineArt="Line art",m))(lt||{});import{v4 as ct,validate as gt}from"uuid";var Te={name:"@runware/sdk-js",version:"1.2.8",description:"The SDK is used to run image inference with the Runware API, powered by the RunWare inference platform. It can be used to generate imaged with text-to-image and image-to-image. It also allows the use of an existing gallery of models or selecting any model or LoRA from the CivitAI gallery. The API also supports upscaling, background removal, inpainting and outpainting, and a series of other ControlNet models.",main:"dist/index.js",module:"dist/index.js",types:"dist/index.d.ts",type:"module",exports:{".":{types:"./dist/index.d.ts",require:"./dist/index.cjs",import:"./dist/index.js"}},files:["dist/"],scripts:{build:"tsup",lint:"tsc",pkg:"npx pkgfiles","dev:test":"vitest --reporter verbose",test:"vitest run --reporter verbose","test:single":"vitest run --reporter verbose tests/Runware/upscale-gan.test.ts",debug:"tsx tests/script.ts","beta:tag":"npm publish --tag beta"},keywords:["runware","sdk","ai"],author:"",license:"ISC",devDependencies:{"@types/uuid":"^9.0.6","@types/ws":"^8.5.8",dotenv:"^16.4.5","mock-socket":"^9.3.1",tsup:"^8.3.5",typescript:"^5.2.2",vitest:"^0.34.6"},dependencies:{uuid:"^9.0.1",ws:"^8.18.0"},optionalDependencies:{bufferutil:"^4.0.8"},directories:{test:"tests"}};var V=Te.version;function B(a){let e=a.includes("?")?"&":"?";return`${a}${e}sdk=js&version=${V}`}var G=6e4,K=1e3,Re=100,te={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},_e=(a,e)=>{if(a==null)return;let t=a.indexOf(e);t!==-1&&a.splice(t,1)},L=(a,{debugKey:e="debugKey",timeoutDuration:t=G,shouldThrowError:n=!0,pollingInterval:o=Re})=>(t=t<K?K:t,new Promise((s,r)=>{let i=setTimeout(()=>{l&&clearInterval(l),clearTimeout(i),n?r(`Response could not be received from server for ${e}`):s(void 0)},t),l=setInterval(async()=>{try{a({resolve:s,reject:r,intervalId:l})&&(clearInterval(l),clearTimeout(i))}catch(g){clearInterval(l),clearTimeout(i),r(g)}},o)})),ke=a=>new Promise(e=>{let t=new FileReader;t.readAsDataURL(a),t.onload=function(){e(t.result)}}),D=()=>ct(),De=a=>gt(a);var ve=({key:a,data:e,useZero:t=!0,shouldReturnString:n=!1})=>a.split(/\.|\[/).map(r=>r.replace(/\]$/,"")).reduce((r,i)=>{let l=t?0:void 0,g=r?.[i];if(!g)return l;if(Array.isArray(g)&&/^\d+$/.test(i)){let c=parseInt(i,10);return c>=0&&c<g.length?r[i]=g[c]:r[i]??l}else return r[i]??l},e||{})??{},xe=(a,e=1e3)=>new Promise(t=>setTimeout(t,a*e));var Se=(a,e)=>a.filter(t=>t.key!==e.key);var _=({key:a,value:e})=>e||e===0||e===!1?{[a]:e}:{},dt=(a,e)=>Math.floor(Math.random()*(e-a+1))+a,Ee=()=>dt(1,Number.MAX_SAFE_INTEGER),we=(a,{debugKey:e="debugKey",timeoutDuration:t=G,shouldThrowError:n=!0,pollingInterval:o=Re})=>(t=t<K?K:t,new Promise((s,r)=>{let i=setTimeout(()=>{l&&(clearInterval(l),n&&r(`Response could not be received from server for ${e}`)),clearTimeout(i)},t),l=setInterval(async()=>{try{await a({resolve:s,reject:r,intervalId:l})&&(clearInterval(l),clearTimeout(i))}catch(g){clearInterval(l),clearTimeout(i),r(g)}},o)}));var x=async(a,e={})=>{let{delayInSeconds:t=1,callback:n,logger:o}=e,s=e.maxRetries??1,r=s;if(s<=0)return await a();for(;s;)try{let i=await a();return s<r&&o?.retrySuccess(r-s+1),i}catch(i){if(i?.error)throw o?.retrySkippedApiError(i.error?.code||"unknown"),i;if(n?.(),s--,s>0)return o?.retryAttempt(r-s,r,t*1e3),await xe(t),await x(a,{...e,maxRetries:s});throw o?.retryExhausted(r),i}};var I={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",black:"\x1B[30m",white:"\x1B[37m",gray:"\x1B[90m",green:"\x1B[92m",yellow:"\x1B[93m",blue:"\x1B[94m",magenta:"\x1B[95m",cyan:"\x1B[96m",red:"\x1B[91m",bgGreen:"\x1B[42m",bgYellow:"\x1B[43m",bgBlue:"\x1B[44m",bgMagenta:"\x1B[45m",bgCyan:"\x1B[46m",bgRed:"\x1B[41m",bgWhite:"\x1B[47m"},Ae=(c=>(c.CONNECTION="CONNECTION",c.AUTH="AUTH",c.HEARTBEAT="HEARTBEAT",c.SEND="SEND",c.RECEIVE="RECEIVE",c.RETRY="RETRY",c.REQUEST="REQUEST",c.ERROR="ERROR",c.WARN="WARN",c.INFO="INFO",c))(Ae||{}),Ce={CONNECTION:{bg:I.bgBlue,fg:I.blue,icon:"\u{1F50C}"},AUTH:{bg:I.bgGreen,fg:I.green,icon:"\u{1F511}"},HEARTBEAT:{bg:I.bgMagenta,fg:I.magenta,icon:"\u{1F493}"},SEND:{bg:I.bgCyan,fg:I.cyan,icon:"\u{1F4E4}"},RECEIVE:{bg:I.bgCyan,fg:I.cyan,icon:"\u{1F4E5}"},RETRY:{bg:I.bgYellow,fg:I.yellow,icon:"\u{1F504}"},REQUEST:{bg:I.bgBlue,fg:I.blue,icon:"\u{1F4E1}"},ERROR:{bg:I.bgRed,fg:I.red,icon:"\u274C"},WARN:{bg:I.bgYellow,fg:I.yellow,icon:"\u26A0\uFE0F"},INFO:{bg:I.bgWhite,fg:I.gray,icon:"\u2139\uFE0F"}},pt=`${I.bold}${I.magenta}[RUNWARE]${I.reset}`;function mt(){return`${I.dim}${new Date().toISOString()}${I.reset}`}function ht(a){return`${Ce[a].bg}${I.bold}${I.black} ${a} ${I.reset}`}function It(a){if(a==null)return"";if(typeof a=="string")return`${I.dim}${a}${I.reset}`;try{let e=JSON.stringify(a,null,2);return`${I.dim}${e}${I.reset}`}catch{return`${I.dim}[unserializable]${I.reset}`}}var P=class{constructor(e=!1){this.enabled=e}log(e,t,n){if(!this.enabled)return;let o=Ce[e],s=["",`${pt} ${ht(e)} ${o.icon} ${o.fg}${I.bold}${t}${I.reset}`,` ${mt()}`];n!==void 0&&s.push(` ${It(n)}`),s.push(""),e==="ERROR"?console.error(s.join(`
|
|
2
|
+
`)):e==="WARN"?console.warn(s.join(`
|
|
3
|
+
`)):console.log(s.join(`
|
|
4
|
+
`))}connecting(e){this.log("CONNECTION","Connecting to WebSocket",{url:e})}connected(e){this.log("CONNECTION","WebSocket connection established",{connectionSessionUUID:e})}reconnecting(e){this.log("CONNECTION",`Reconnecting... attempt #${e}`)}reconnectScheduled(e){this.log("CONNECTION",`Reconnect scheduled in ${e}ms`)}disconnected(e){this.log("CONNECTION",`WebSocket disconnected${e?`: ${e}`:""}`)}connectionClosed(e){this.log("CONNECTION","WebSocket closed",{code:e})}connectionError(e){this.log("ERROR","WebSocket error",e)}ensureConnectionStart(){this.log("CONNECTION","Connection lost \u2014 waiting for reconnection...")}ensureConnectionSuccess(){this.log("CONNECTION","Reconnection successful")}ensureConnectionTimeout(){this.log("ERROR","Reconnection timed out after max retries")}authenticating(e){this.log("AUTH",e?"Re-authenticating with existing session":"Authenticating with API key")}authenticated(e){this.log("AUTH","Authentication successful",{connectionSessionUUID:e})}authError(e){this.log("ERROR","Authentication failed",e)}heartbeatStarted(e){this.log("HEARTBEAT",`Heartbeat started \u2014 ping every ${e/1e3}s, 3 missed pongs before close`)}heartbeatPingSent(){this.log("HEARTBEAT","Ping sent")}heartbeatPongReceived(){this.log("HEARTBEAT","Pong received \u2014 connection alive")}heartbeatPongMissed(e,t){this.log("WARN",`Pong missed (${e}/${t}) \u2014 ${e>=t?"connection dead, terminating":"will retry next cycle"}`)}heartbeatStopped(){this.log("HEARTBEAT","Heartbeat stopped")}messageSent(e,t){this.log("SEND","Message sent",{taskType:e,...t?{taskUUID:t}:{}})}messageReceived(e,t){this.log("RECEIVE","Message received",{...e?{taskType:e}:{},...t?{taskUUID:t}:{}})}sendReconnecting(){this.log("WARN","Send failed \u2014 WebSocket not ready, attempting reconnection before retry")}sendFailed(e){this.log("ERROR",`Send failed \u2014 ${e}`)}requestStart(e,t){this.log("REQUEST","Request started",{taskType:e,taskUUID:t})}requestComplete(e,t,n){this.log("REQUEST",`Request complete in ${n}ms`,{taskType:e,taskUUID:t})}requestTimeout(e,t){this.log("ERROR",`Request timed out after ${t}ms`,{taskUUID:e})}requestError(e,t){this.log("ERROR","Request failed",{taskUUID:e,error:t?.message||t?.error||t})}retryAttempt(e,t,n){this.log("RETRY",`Retry ${e}/${t} \u2014 waiting ${n}ms before next attempt`)}retrySuccess(e){this.log("RETRY",`Retry succeeded on attempt #${e}`)}retryExhausted(e){this.log("ERROR",`All ${e} retries exhausted \u2014 giving up`)}retrySkippedApiError(e){this.log("ERROR","API error \u2014 skipping retry (not retryable)",{code:e})}info(e,t){this.log("INFO",e,t)}warn(e,t){this.log("WARN",e,t)}error(e,t){this.log("ERROR",e,t)}},yt=new P(!1);function ne(a){return a?new P(!0):yt}var O=class{constructor({apiKey:e,url:t=te.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:o=2,timeoutDuration:s=G,heartbeatInterval:r=45e3,enableLogging:i=!1}){this._listeners=[];this._globalMessages={};this._globalImages=[];this._globalErrors=[];this._heartbeatIntervalId=null;this._pongTimeoutId=null;this._missedPongCount=0;this._maxMissedPongs=3;this.ensureConnectionUUID=null;this.isWebsocketReadyState=()=>this._ws?.readyState===1;this.isInvalidAPIKey=()=>this._connectionError?.error?.code==="invalidApiKey";this.send=async e=>{if(!this.isWebsocketReadyState()){if(this._logger.sendReconnecting(),this._ws)try{typeof this._ws.terminate=="function"?this._ws.terminate():this._ws.close()}catch{}this._connectionSessionUUID=void 0,await this.ensureConnection()}let t=e?.taskType,n=e?.taskUUID;this._logger.messageSent(t,n),this._ws.send(JSON.stringify([e]))};this.uploadImage=async e=>{try{return await x(async()=>{let t=D();if(typeof e=="string"&&De(e))return{imageURL:e,imageUUID:e,taskUUID:t,taskType:"imageUpload"};let n=typeof e=="string"?e:await ke(e);return{imageURL:n,imageUUID:n,taskUUID:t,taskType:"imageUpload"}})}catch(t){throw t}};this.controlNetPreProcess=async({inputImage:e,preProcessorType:t,height:n,width:o,outputType:s,outputFormat:r,highThresholdCanny:i,lowThresholdCanny:l,includeHandsAndFaceOpenPose:g,includeCost:c,outputQuality:m,customTaskUUID:d,taskUUID:u,retry:p,includeGenerationTime:h,includePayload:U})=>{let f=p||this._globalMaxRetries,R,b=Date.now();try{return await x(async()=>{await this.ensureConnection();let k=await this.uploadImage(e);if(!k?.imageUUID)return null;let y=u||d||D(),w={inputImage:k.imageUUID,taskType:"imageControlNetPreProcess",taskUUID:y,preProcessorType:t,..._({key:"height",value:n}),..._({key:"width",value:o}),..._({key:"outputType",value:s}),..._({key:"outputFormat",value:r}),..._({key:"includeCost",value:c}),..._({key:"highThresholdCanny",value:i}),..._({key:"lowThresholdCanny",value:l}),..._({key:"includeHandsAndFaceOpenPose",value:g}),...m?{outputQuality:m}:{}};await this.send({...w}),R=this.globalListener({taskUUID:y});let A=await L(({resolve:S,reject:Q})=>{let E=this.getSingleMessage({taskUUID:y});if(E){if(E?.error)return Q(E),!0;if(E)return S(E),!0}},{debugKey:"unprocessed-image",timeoutDuration:this._timeoutDuration});return R.destroy(),this.insertAdditionalResponse({response:A,payload:U?w:void 0,startTime:h?b:void 0}),A},{maxRetries:f,callback:()=>{R?.destroy()}})}catch(k){throw k}};this.controlNetPreprocess=async e=>this.controlNetPreProcess(e);this.requestImageToText=async({inputImage:e,inputs:t,includeCost:n,customTaskUUID:o,taskUUID:s,retry:r,includePayload:i,includeGenerationTime:l,deliveryMethod:g,skipResponse:c,model:m})=>{try{let d;e&&(d=await this.uploadImage(e));let p={taskUUID:s||o||D(),taskType:"caption",model:m,inputImage:d?.imageUUID,inputs:t,..._({key:"includeCost",value:n}),retry:r,includePayload:i,includeGenerationTime:l},h=await this.baseSingleRequest({payload:{...p,taskType:"caption"},debugKey:"caption"});if(c)return h;if(g==="async"){let U=h?.taskUUID;return(await this.pollForAsyncResults({taskUUID:U}))[0]}return h}catch(d){throw d}};this.caption=async e=>this.requestImageToText(e);this.removeImageBackground=async e=>{let{skipResponse:t,...n}=e;try{let o=n.deliveryMethod,s=await this.baseSingleRequest({payload:{...n,taskType:"removeBackground"},debugKey:"remove-background"});if(t)return s;if(o==="async"){let r=s?.taskUUID;return(await this.pollForAsyncResults({taskUUID:r}))[0]}return s}catch(o){throw o}};this.removeBackground=async e=>this.removeImageBackground(e);this.vectorize=async e=>this.baseSingleRequest({payload:{...e,taskType:"vectorize"},debugKey:"vectorize"});this.videoInference=async e=>{let{skipResponse:t,inputAudios:n,referenceVideos:o,...s}=e;try{let r=await this.baseSingleRequest({payload:{...s,...n?.length&&{inputAudios:n},...o?.length&&{referenceVideos:o},deliveryMethod:"async",taskType:"videoInference"},debugKey:"video-inference"});if(t)return r;let i=r?.taskUUID;return this.pollForAsyncResults({taskUUID:i,numberResults:e?.numberResults})}catch(r){throw r}};this.audioInference=async e=>{let{skipResponse:t,deliveryMethod:n="sync",...o}=e;try{let r=await(n==="sync"?this.baseSyncRequest:this.baseSingleRequest)({payload:{...o,numberResults:o.numberResults||1,taskType:"audioInference",deliveryMethod:n},groupKey:"REQUEST_AUDIO",debugKey:"audio-inference",skipResponse:t});if(t)return r;let i=r?.taskUUID;return n==="async"?this.pollForAsyncResults({taskUUID:i,numberResults:e?.numberResults}):r}catch(s){throw s}};this.threeDInference=async e=>{let{skipResponse:t,deliveryMethod:n="sync",...o}=e;try{let r=await(n==="sync"?this.baseSyncRequest:this.baseSingleRequest)({payload:{...o,numberResults:o.numberResults||1,taskType:"3dInference",deliveryMethod:n},groupKey:"REQUEST_IMAGES",debugKey:"three-d-inference",skipResponse:t});if(t)return r;let i=r?.taskUUID;return n==="async"?this.pollForAsyncResults({taskUUID:i,numberResults:e?.numberResults}):r}catch(s){throw s}};this.textInference=async e=>{let{skipResponse:t,deliveryMethod:n="sync",...o}=e;try{let r=await(n==="sync"?this.baseSyncRequest:this.baseSingleRequest)({payload:{...o,numberResults:o.numberResults||1,taskType:"textInference",deliveryMethod:n},groupKey:"REQUEST_TEXT",debugKey:"text-inference",skipResponse:t});if(t)return r;let i=r?.taskUUID;return n==="async"?this.pollForAsyncResults({taskUUID:i,numberResults:e?.numberResults}):r}catch(s){throw s}};this.getResponse=async e=>{let t=e.taskUUID;return this.baseSingleRequest({payload:{...e,customTaskUUID:t,taskType:"getResponse"},isMultiple:!0,debugKey:"async-results"})};this.upscaleGan=async e=>{let{inputImage:t,skipResponse:n,deliveryMethod:o="sync",...s}=e;try{let r;t&&(r=await this.uploadImage(t));let i=await this.baseSingleRequest({payload:{...s,...r?.imageUUID?{inputImage:r.imageUUID}:{},taskType:"upscale",deliveryMethod:o},debugKey:"upscale"});if(n)return i;if(o==="async"){let l=i?.taskUUID;return(await this.pollForAsyncResults({taskUUID:l}))[0]}return i}catch(r){throw r}};this.upscale=async e=>this.upscaleGan(e);this.enhancePrompt=async({prompt:e,promptMaxLength:t=380,promptVersions:n=1,includeCost:o,customTaskUUID:s,taskUUID:r,retry:i,includeGenerationTime:l,includePayload:g})=>{let c=i||this._globalMaxRetries,m,d=Date.now();try{return await x(async()=>{await this.ensureConnection();let u=r||s||D(),p={prompt:e,taskUUID:u,promptMaxLength:t,promptVersions:n,..._({key:"includeCost",value:o}),taskType:"promptEnhance"};await this.send(p),m=this.globalListener({taskUUID:u});let h=await L(({resolve:U,reject:f})=>{let R=this._globalMessages[u];if(R?.error)return f(R),!0;if(R?.length>=n)return delete this._globalMessages[u],U(R),!0},{debugKey:"enhance-prompt",timeoutDuration:this._timeoutDuration});return m.destroy(),this.insertAdditionalResponse({response:h,payload:g?p:void 0,startTime:l?d:void 0}),h},{maxRetries:c,callback:()=>{m?.destroy()}})}catch(u){throw u}};this.promptEnhance=async e=>this.enhancePrompt(e);this.modelUpload=async e=>{let{onUploadStream:t,retry:n,customTaskUUID:o,taskUUID:s,...r}=e,i=n||this._globalMaxRetries,l;try{return await x(async()=>{await this.ensureConnection();let g=s||o||D();await this.send({...r,taskUUID:g,taskType:"modelUpload"});let c,m;l=this.listenToUpload({taskUUID:g,onUploadStream:(u,p)=>{t?.(u,p),u?.status==="ready"?c=u:p&&(m=p)}});let d=await L(({resolve:u,reject:p})=>{if(c)return u(c),!0;if(m)return p(m),!0},{shouldThrowError:!1,timeoutDuration:60*60*1e3});return l?.destroy(),d},{maxRetries:i,callback:()=>{l?.destroy()}})}catch(g){throw g}};this.photoMaker=async(e,t)=>{let{onPartialImages:n,retry:o,customTaskUUID:s,taskUUID:r,numberResults:i,includeGenerationTime:l,includePayload:g,...c}=e,m=o||this._globalMaxRetries,d,u=[],p=0,h=Date.now();try{return await x(async()=>{await this.ensureConnection(),p++;let U=this._globalImages.filter(y=>u.includes(y.taskUUID)),f=r||s||D();u.push(f);let R=i-U.length,b={...c,...c.seed?{seed:c.seed}:{seed:Ee()},...t??{},taskUUID:f,taskType:"photoMaker",numberResults:i};await this.send({...b,numberResults:R}),d=this.listenToResponse({onPartialImages:n,taskUUID:f,groupKey:"REQUEST_IMAGES",requestPayload:g?b:void 0,startTime:l?h:void 0});let k=await this.getResponseWithSimilarTaskUUID({taskUUID:u,numberResults:i,lis:d});return d.destroy(),k},{maxRetries:m,callback:()=>{d?.destroy()}})}catch(U){if(U.taskUUID)throw U;if(p>=m)return this.handleIncompleteImages({taskUUIDs:u,error:U})}};this.modelSearch=async e=>this.baseSingleRequest({payload:{...e,taskType:"modelSearch"},debugKey:"model-search"});this.imageMasking=async e=>this.baseSingleRequest({payload:{...e,taskType:"imageMasking"},debugKey:"image-masking"});this.imageUpload=async e=>this.baseSingleRequest({payload:{...e,taskType:"imageUpload"},debugKey:"image-upload"});this.mediaStorage=async e=>this.baseSingleRequest({payload:{...e,operation:e.operation||"upload",taskType:"mediaStorage"},debugKey:"media-storage"});this.baseSingleRequest=async({payload:e,debugKey:t,isMultiple:n})=>{let{retry:o,customTaskUUID:s,taskUUID:r,includePayload:i,includeGenerationTime:l,...g}=e,c=o||this._globalMaxRetries,m,d=Date.now();try{return await x(async()=>{await this.ensureConnection();let u=r||s||D(),p={...g,taskUUID:u};this._logger.requestStart(t,u),await this.send(p),m=this.globalListener({taskUUID:u});let h=await L(({resolve:U,reject:f})=>{let R=n?this.getMultipleMessages({taskUUID:u}):this.getSingleMessage({taskUUID:u});if(R){if(R?.error)return this._logger.requestError(u,R),f(R),!0;if(R)return delete this._globalMessages[u],this._logger.requestComplete(t,u,Date.now()-d),U(R),!0}},{debugKey:t,timeoutDuration:this._timeoutDuration});return this.insertAdditionalResponse({response:h,payload:i?p:void 0,startTime:l?d:void 0}),m.destroy(),h},{maxRetries:c,callback:()=>{m?.destroy()},logger:this._logger})}catch(u){throw u}};this.baseSyncRequest=async({payload:e,groupKey:t,skipResponse:n=!1})=>{let{retry:o,customTaskUUID:s,includePayload:r,numberResults:i=1,onPartialResponse:l,includeGenerationTime:g,...c}=e,m=o||this._globalMaxRetries,d,u=[],p=0,h=Date.now();try{return await x(async()=>{await this.ensureConnection(),p++;let U=this._globalImages.filter(y=>u.includes(y.taskUUID)),f=s||D();u.push(f);let R=i-U.length,b={...c,taskUUID:f,numberResults:R};if(this._logger.requestStart(c.taskType||t,f),await this.send(b),n)return this._logger.info("Async mode (skipResponse) \u2014 waiting for server acknowledgement",{taskUUID:f}),new Promise((y,w)=>{let A=this.addListener({taskUUID:f,groupKey:t,lis:S=>{A.destroy(),S.error?(this._logger.requestError(f,S.error),w(S.error)):(this._logger.requestComplete(c.taskType||t,f,Date.now()-h),y(S[f]))}})});d=this.listenToResponse({onPartialImages:l,taskUUID:f,groupKey:t,requestPayload:r?b:void 0,startTime:g?h:void 0});let k=await this.getResponseWithSimilarTaskUUID({taskUUID:u,numberResults:i,lis:d});return this._logger.requestComplete(c.taskType||t,f,Date.now()-h),d.destroy(),k},{maxRetries:m,callback:()=>{d?.destroy()},logger:this._logger})}catch(U){throw U}};this.getSingleMessage=({taskUUID:e})=>{let t=this._globalMessages[e]?.[0],n=this._globalMessages[e];return!t&&!n?null:n?.error?n:t};this.getMultipleMessages=({taskUUID:e})=>{let t=this._globalMessages[e]?.[0],n=this._globalMessages[e];return!t&&!n?null:n};this.insertAdditionalResponse=({response:e,payload:t,startTime:n})=>{if(!t&&!n)return;let o=e;o.additionalResponse={},t&&(e.additionalResponse.payload=t),n&&(e.additionalResponse.generationTime=Date.now()-n)};this.disconnect=async()=>{this._logger.disconnected("user initiated"),this._shouldReconnect=!1,this._connectionSessionUUID=void 0,this.stopHeartbeat(),this._ws?.terminate?.(),this._ws?.close?.()};this.connected=()=>this.isWebsocketReadyState()&&!!this._connectionSessionUUID;this._apiKey=e,this._url=t,this._sdkType="CLIENT",this._shouldReconnect=n,this._globalMaxRetries=o,this._timeoutDuration=s,this._heartbeatInterval=Math.max(1e4,Math.min(12e4,r)),this._logger=ne(i)}getUniqueUUID(e){return e.mediaUUID||e.audioUUID||e.imageUUID||e.videoUUID||e.outputs?.files?.map(t=>t.uuid).join("-")||e.text}async pollForAsyncResults({taskUUID:e,numberResults:t=1}){let n=new Map;return await we(async({resolve:o,reject:s})=>{try{let r=await this.getResponse({taskUUID:e});for(let l of r||[])if(l.status==="success"){let g=this.getUniqueUUID(l);g&&n.set(g,l)}return n.size===t?(o(Array.from(n.values())),!0):!1}catch(r){return s(r),!0}},{debugKey:"async-response",pollingInterval:2*1e3,timeoutDuration:10*60*1e3}),Array.from(n.values())}static async initialize(e){try{let t=new this(e);return await t.ensureConnection(),t}catch(t){throw t}}startHeartbeat(){this.stopHeartbeat(),this._logger.heartbeatStarted(this._heartbeatInterval),this._heartbeatIntervalId=setInterval(()=>{if(!this.isWebsocketReadyState()){this.stopHeartbeat();return}try{this._ws.send(JSON.stringify([{taskType:"ping",ping:!0}])),this._logger.heartbeatPingSent()}catch{this.stopHeartbeat();return}this._pongTimeoutId&&(clearTimeout(this._pongTimeoutId),this._pongTimeoutId=null),this._pongTimeoutId=setTimeout(()=>{this._missedPongCount++,this._logger.heartbeatPongMissed(this._missedPongCount,this._maxMissedPongs),this._missedPongCount>=this._maxMissedPongs&&this._ws&&(typeof this._ws.terminate=="function"?this._ws.terminate():this._ws.close())},1e4)},this._heartbeatInterval)}stopHeartbeat(){this._heartbeatIntervalId&&(clearInterval(this._heartbeatIntervalId),this._heartbeatIntervalId=null,this._logger.heartbeatStopped()),this._pongTimeoutId&&(clearTimeout(this._pongTimeoutId),this._pongTimeoutId=null),this._missedPongCount=0}handlePongMessage(e){let t=Array.isArray(e?.data)?e.data:[];for(let n of t)if(n?.taskType==="ping"&&n?.pong===!0)return this._missedPongCount=0,this._pongTimeoutId&&(clearTimeout(this._pongTimeoutId),this._pongTimeoutId=null),this._logger.heartbeatPongReceived(),!0;return!1}addListener({lis:e,groupKey:t,taskUUID:n}){let o=i=>{let l=Array.isArray(i?.data)?i.data:[i.data],g=i?.[0]?.errors?i?.[0]?.errors:Array.isArray(i?.errors)?i.errors:[i.errors],c=l.filter(d=>(d?.taskUUID||d?.taskType)===n);if(g.filter(d=>(d?.taskUUID||d?.taskType)===n).length){e({error:{...g[0]??{}}});return}if(c.length){e({[n]:l});return}},s={key:n||D(),listener:o,groupKey:t};return this._listeners.push(s),{destroy:()=>{this._listeners=Se(this._listeners,s)}}}connect(){this._logger.connecting(this._url||"unknown"),this._ws.onopen=async e=>{this._logger.authenticating(!!this._connectionSessionUUID);try{this._connectionSessionUUID?await this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):await this.send({apiKey:this._apiKey,taskType:"authentication"})}catch(n){this._logger.error("Failed to send auth message",n);return}let t=this.addListener({taskUUID:"authentication",lis:n=>{if(n?.error){this._connectionError=n,this._logger.authError(n),t?.destroy?.();return}this._connectionSessionUUID=n?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0,this._logger.authenticated(this._connectionSessionUUID||""),t?.destroy?.(),this.startHeartbeat()}})},this._ws.onmessage=e=>{let t;try{t=JSON.parse(e.data)}catch(n){this._logger.error("Failed to parse WebSocket message",n);return}if(!this.handlePongMessage(t)){for(let n of this._listeners)if(n?.listener?.(t))return}},this._ws.onclose=e=>{this._logger.connectionClosed(e?.code),this._connectionSessionUUID=void 0,this.stopHeartbeat(),this.isInvalidAPIKey()},this._ws.onerror=e=>{this._logger.connectionError(e?.message||e)}}destroy(e){_e(this._listeners,e)}listenToResponse({onPartialImages:e,taskUUID:t,groupKey:n,requestPayload:o,startTime:s}){return this.addListener({taskUUID:t,lis:r=>{let i=r?.[t]?.filter(l=>l.taskUUID===t);r.error?(e?.(i,r?.error&&r),this._globalErrors.push(r)):(i=i.map(l=>(this.insertAdditionalResponse({response:l,payload:o||void 0,startTime:s||void 0}),{...l})),e?.(i,r?.error&&r),this._sdkType==="CLIENT"?this._globalImages=[...this._globalImages,...(r?.[t]??[]).map(l=>(this.insertAdditionalResponse({response:l,payload:o||void 0,startTime:s||void 0}),{...l}))]:this._globalImages=[...this._globalImages,...i])},groupKey:n})}listenToUpload({onUploadStream:e,taskUUID:t}){return this.addListener({taskUUID:t,lis:n=>{let o=n?.error,s=n?.[t]?.[0],r=s?.taskUUID===t?s:null;(r||o)&&e?.(r||void 0,o)}})}globalListener({taskUUID:e}){return this.addListener({taskUUID:e,lis:t=>{if(t.error){this._globalMessages[e]=t;return}let n=ve({key:e,data:t,useZero:!1});Array.isArray(n)?n.forEach(o=>{this._globalMessages[o.taskUUID]=[...this._globalMessages[o.taskUUID]??[],o]}):this._globalMessages[n.taskUUID]=n}})}async requestImages({outputType:e,outputFormat:t,uploadEndpoint:n,checkNSFW:o,positivePrompt:s,negativePrompt:r,seedImage:i,maskImage:l,strength:g,height:c,width:m,model:d,steps:u,scheduler:p,seed:h,CFGScale:U,clipSkip:f,usePromptWeighting:R,promptWeighting:b,numberResults:k=1,onPartialImages:y,includeCost:w,customTaskUUID:A,taskUUID:S,retry:Q,refiner:E,maskMargin:T,outputQuality:se,controlNet:j,lora:re,embeddings:oe,ipAdapters:ie,providerSettings:ae,outpaint:le,acceleratorOptions:ue,advancedFeatures:ce,referenceImages:ge,includeGenerationTime:qe,includePayload:Ke,...de},Ve){let N,pe,F=[],me=0,he=Q||this._globalMaxRetries;try{await this.ensureConnection();let C=null,z=null,Y=[];if(i){let v=await this.uploadImage(i);if(!v)return[];C=v.imageUUID}if(l){let v=await this.uploadImage(l);if(!v)return[];z=v.imageUUID}if(j?.length)for(let v=0;v<j.length;v++){let M=j[v],{endStep:X,startStep:W,weight:J,guideImage:q,controlMode:Ge,startStepPercentage:$e,endStepPercentage:He,model:Qe}=M,je=q?await this.uploadImage(q):null;Y.push({guideImage:je?.imageUUID,model:Qe,endStep:X,startStep:W,weight:J,..._({key:"startStepPercentage",value:$e}),..._({key:"endStepPercentage",value:He}),controlMode:Ge||"controlnet"})}pe={taskType:"imageInference",model:d,positivePrompt:s,...r?{negativePrompt:r}:{},...c?{height:c}:{},...m?{width:m}:{},numberResults:k,...e?{outputType:e}:{},...t?{outputFormat:t}:{},...n?{uploadEndpoint:n}:{},..._({key:"checkNSFW",value:o}),..._({key:"strength",value:g}),..._({key:"CFGScale",value:U}),..._({key:"clipSkip",value:f}),..._({key:"maskMargin",value:T}),..._({key:"usePromptWeighting",value:R}),..._({key:"steps",value:u}),...b?{promptWeighting:b}:{},...h?{seed:h}:{},...p?{scheduler:p}:{},...E?{refiner:E}:{},...le?{outpaint:le}:{},..._({key:"includeCost",value:w}),...C?{seedImage:C}:{},...z?{maskImage:z}:{},...se?{outputQuality:se}:{},...Y.length?{controlNet:Y}:{},...re?.length?{lora:re}:{},...oe?.length?{embeddings:oe}:{},...ie?.length?{ipAdapters:ie}:{},...ae?{providerSettings:ae}:{},...ue?{acceleratorOptions:ue}:{},...ce?{advancedFeatures:ce}:{},...ge?.length?{referenceImages:ge}:{},...de,...Ve??{}};let Be=Date.now();return await x(async()=>{me++,N?.destroy();let v=this._globalImages.filter(q=>F.includes(q.taskUUID)),M=S||A||D();F.push(M);let X=k-v.length,W={...pe,taskUUID:M,numberResults:X};await this.send(W),N=this.listenToResponse({onPartialImages:y,taskUUID:M,groupKey:"REQUEST_IMAGES",requestPayload:Ke?W:void 0,startTime:qe?Be:void 0});let J=await this.getResponseWithSimilarTaskUUID({taskUUID:F,numberResults:k,lis:N,deliveryMethod:de.deliveryMethod});return N.destroy(),J},{maxRetries:he,callback:()=>{N?.destroy()}})}catch(C){if(me>=he)return this.handleIncompleteImages({taskUUIDs:F,error:C});throw C}}async imageInference(e,t){return this.requestImages(e,t)}async ensureConnection(){if(this.connected()||this._url===te.TEST)return;this._logger.ensureConnectionStart();let t=2e3,n=200;try{if(this.isInvalidAPIKey())throw this._connectionError;return new Promise((o,s)=>{let r=0,i=30,l=D(),g,c,m=()=>{this.ensureConnectionUUID=null,clearInterval(g),clearInterval(c)};this._sdkType==="SERVER"&&(g=setInterval(async()=>{try{let d=this.connected(),u=!1;(!this.ensureConnectionUUID||l===this.ensureConnectionUUID)&&(this.ensureConnectionUUID||(this.ensureConnectionUUID=l),u=!0);let p=r%10===0&&u;d?(m(),this._logger.ensureConnectionSuccess(),o(!0)):r>=i?(m(),this._logger.ensureConnectionTimeout(),s(new Error("Retry timed out"))):(p&&(this._logger.reconnecting(r+1),this.connect()),r++)}catch(d){m(),s(d)}},t)),c=setInterval(async()=>{if(this.connected()){m(),this._logger.ensureConnectionSuccess(),o(!0);return}if(this.isInvalidAPIKey()){m(),this._logger.error("Connection failed \u2014 invalid API key"),s(this._connectionError);return}},n)})}catch{throw this.ensureConnectionUUID=null,this._connectionError=void 0,this._connectionError??"Could not connect to server. Ensure your API key is correct"}}async getResponseWithSimilarTaskUUID({taskUUID:e,numberResults:t,shouldThrowError:n,lis:o,deliveryMethod:s}){return await L(({resolve:r,reject:i,intervalId:l})=>{let g=Array.isArray(e)?e:[e],c=this._globalImages.filter(u=>g.includes(u.taskUUID)),m=s==="async"&&c.length>0,d=this._globalErrors.filter(u=>g.includes(u.error.taskUUID));if(d.length>0){let u=d[0];return this._globalErrors=this._globalErrors.filter(p=>!g.includes(p.error.taskUUID)),clearInterval(l),i?.(u),!0}else if(c.length>=t||m)return clearInterval(l),this._globalImages=this._globalImages.filter(u=>!g.includes(u.taskUUID)),r([...c].slice(0,t)),!0},{debugKey:"getting images",shouldThrowError:n,timeoutDuration:this._timeoutDuration})}handleIncompleteImages({taskUUIDs:e,error:t}){let n=this._globalImages.filter(o=>e.includes(o.taskUUID));if(n.length>1)return this._globalImages=this._globalImages.filter(o=>!e.includes(o.taskUUID)),n;throw t}};var Fe=nt(Pe(),1);var $=class extends O{constructor(e){let{shouldReconnect:t,...n}=e;super(n);let o=B(this._url||"");this._ws=new Fe.default(o),this.connect()}};import kt from"ws";var H=class extends O{constructor(t){super(t);this._instantiated=!1;this._listeners=[];this._reconnectingIntervalId=null;this._connecting=!1;this.send=async t=>{if(!this.isWebsocketReadyState()){if(this._logger.sendReconnecting(),this._ws)try{typeof this._ws.terminate=="function"?this._ws.terminate():this._ws.close()}catch{}this._connectionSessionUUID=void 0,await this.ensureConnection()}let n=t?.taskType,o=t?.taskUUID;this._logger.messageSent(n,o),this._ws.send(JSON.stringify([t]))};this.resetConnection=()=>{this.stopHeartbeat(),this._ws&&(this._listeners.forEach(t=>{t?.destroy?.()}),this._ws.removeAllListeners(),this._ws.readyState===1&&(this._ws.terminate(),this._ws.close()),this._ws=null,this._listeners=[])};this._sdkType="SERVER",this.connect()}async connect(){if(this._url&&!this._connecting){this._connecting=!0,this.resetConnection();try{let t=B(this._url);this._logger.connecting(t),this._ws=new kt(t,{perMessageDeflate:!1,headers:{"X-SDK-Name":"js","X-SDK-Version":V}})}catch(t){this._connecting=!1,this._logger.connectionError(t);return}this._ws.on("error",t=>{this._connecting=!1,this._logger.connectionError(t?.message||t)}),this._ws.on("close",()=>{this.handleClose()}),this._ws.on("open",async()=>{this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._logger.authenticating(!!this._connectionSessionUUID);try{this._connectionSessionUUID&&this.isWebsocketReadyState()?await this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.isWebsocketReadyState()&&await this.send({apiKey:this._apiKey,taskType:"authentication"})}catch(n){this._connecting=!1,this._logger.error("Failed to send auth message",n);return}let t=this.addListener({taskUUID:"authentication",lis:n=>{if(this._connecting=!1,n?.error){this._connectionError=n,this._logger.authError(n),t?.destroy?.();return}this._connectionSessionUUID=n?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0,this._logger.authenticated(this._connectionSessionUUID||""),t?.destroy?.(),this.startHeartbeat()}})}),this._ws.on("message",(t,n)=>{let o=n?t:t?.toString();if(!o)return;let s;try{s=JSON.parse(o)}catch(r){this._logger.error("Failed to parse WebSocket message",r);return}this.handlePongMessage(s)||this._listeners.forEach(r=>{r.listener(s)})})}}handleClose(){this._connecting=!1,this._logger.connectionClosed(),this._connectionSessionUUID=void 0,this.stopHeartbeat(),!this.isInvalidAPIKey()&&(this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._shouldReconnect&&(this._logger.reconnectScheduled(1e3),setTimeout(()=>this.connect(),1e3)))}};var We;typeof window>"u"?We=H:We=$;export{be as EControlMode,ot as EModelArchitecture,at as EModelConditioning,rt as EModelFormat,it as EModelType,st as EOpenPosePreProcessor,lt as EPhotoMakerEnum,fe as EPreProcessor,Ue as EPreProcessorGroup,ee as ETaskType,ye as Environment,Ae as LogLevel,We as Runware,$ as RunwareClient,P as RunwareLogger,H as RunwareServer,V as SDK_VERSION,Z as SdkType,ne as createLogger};
|
|
2
5
|
//# sourceMappingURL=index.js.map
|