@runware/sdk-js 1.2.1-beta.2 → 1.2.2-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var Ye=Object.create;var F=Object.defineProperty;var $e=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var et=Object.getPrototypeOf,tt=Object.prototype.hasOwnProperty;var nt=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),st=(i,e)=>{for(var t in e)F(i,t,{get:e[t],enumerable:!0})},he=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Xe(e))!tt.call(i,s)&&s!==t&&F(i,s,{get:()=>e[s],enumerable:!(n=$e(e,s))||n.enumerable});return i};var Ue=(i,e,t)=>(t=i!=null?Ye(et(i)):{},he(e||!i||!i.__esModule?F(t,"default",{value:i,enumerable:!0}):t,i)),rt=i=>he(F({},"__esModule",{value:!0}),i);var Ke=nt((mn,Pe)=>{"use strict";var Ne=i=>i&&i.CLOSING===2,ot=()=>typeof WebSocket<"u"&&Ne(WebSocket),it=()=>({constructor:ot()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),lt=(i,e,t)=>{Object.defineProperty(e,t,{get:()=>i[t],set:n=>{i[t]=n},enumerable:!0,configurable:!0})},Me=i=>i.minReconnectionDelay+Math.random()*i.minReconnectionDelay,ut=(i,e)=>{let t=e*i.reconnectionDelayGrowFactor;return t>i.maxReconnectionDelay?i.maxReconnectionDelay:t},ct=["onopen","onclose","onmessage","onerror"],dt=(i,e,t)=>{Object.keys(t).forEach(n=>{t[n].forEach(([s,r])=>{i.addEventListener(n,s,r)})}),e&&ct.forEach(n=>{i[n]=e[n]})},Le=function(i,e,t={}){let n,s,r=0,a=0,l=!0,o={};if(!(this instanceof Le))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let d=it();if(Object.keys(d).filter(c=>t.hasOwnProperty(c)).forEach(c=>d[c]=t[c]),!Ne(d.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");let g=d.debug?(...c)=>console.log("RWS:",...c):()=>{},I=(c,y)=>setTimeout(()=>{let p=new Error(y);p.code=c,Array.isArray(o.error)&&o.error.forEach(([b])=>b(p)),n.onerror&&n.onerror(p)},0),m=()=>{if(g("close"),a++,g("retries count:",a),a>d.maxRetries){I("EHOSTDOWN","Too many failed connection attempts");return}r?r=ut(d,r):r=Me(d),g("reconnectDelay:",r),l&&setTimeout(u,r)},u=()=>{g("connect");let c=n;n=new d.constructor(i,e),s=setTimeout(()=>{g("timeout"),n.close(),I("ETIMEDOUT","Connection timeout")},d.connectionTimeout),g("bypass properties");for(let y in n)["addEventListener","removeEventListener","close","send"].indexOf(y)<0&&lt(n,this,y);n.addEventListener("open",()=>{clearTimeout(s),g("open"),r=Me(d),g("reconnectDelay:",r),a=0}),n.addEventListener("close",m),dt(n,c,o)};g("init"),u(),this.close=(c=1e3,y="",{keepClosed:p=!1,fastClose:b=!0,delay:f=0}={})=>{if(f&&(r=f),l=!p,n.close(c,y),b){let k={code:c,reason:y,wasClean:!0};m(),Array.isArray(o.close)&&o.close.forEach(([R,h])=>{R(k),n.removeEventListener("close",R,h)}),n.onclose&&(n.onclose(k),n.onclose=null)}},this.send=c=>{n.send(c)},this.addEventListener=(c,y,p)=>{Array.isArray(o[c])?o[c].some(([b])=>b===y)||o[c].push([y,p]):o[c]=[[y,p]],n.addEventListener(c,y,p)},this.removeEventListener=(c,y,p)=>{Array.isArray(o[c])&&(o[c]=o[c].filter(([b])=>b!==y)),n.removeEventListener(c,y,p)}};Pe.exports=Le});var pt={};st(pt,{EControlMode:()=>ee,EModelArchitecture:()=>be,EModelConditioning:()=>ke,EModelFormat:()=>Te,EModelType:()=>Re,EOpenPosePreProcessor:()=>fe,EPhotoMakerEnum:()=>_e,EPreProcessor:()=>ne,EPreProcessorGroup:()=>te,ETaskType:()=>B,Environment:()=>X,Runware:()=>re,RunwareClient:()=>O,RunwareServer:()=>M,SdkType:()=>V});module.exports=rt(pt);var X=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))(X||{}),V=(t=>(t.CLIENT="CLIENT",t.SERVER="SERVER",t))(V||{}),B=(p=>(p.IMAGE_INFERENCE="imageInference",p.IMAGE_UPLOAD="imageUpload",p.UPSCALE="upscale",p.REMOVE_BACKGROUND="removeBackground",p.VIDEO_INFERENCE="videoInference",p.CAPTION="caption",p.GET_RESPONSE="getResponse",p.PHOTO_MAKER="photoMaker",p.IMAGE_CONTROL_NET_PRE_PROCESS="imageControlNetPreProcess",p.IMAGE_MASKING="imageMasking",p.PROMPT_ENHANCE="promptEnhance",p.AUTHENTICATION="authentication",p.MODEL_UPLOAD="modelUpload",p.MODEL_SEARCH="modelSearch",p.MEDIA_STORAGE="mediaStorage",p.VECTORIZE="vectorize",p))(B||{}),ee=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(ee||{}),te=(m=>(m.canny="canny",m.depth="depth",m.mlsd="mlsd",m.normalbae="normalbae",m.openpose="openpose",m.tile="tile",m.seg="seg",m.lineart="lineart",m.lineart_anime="lineart_anime",m.shuffle="shuffle",m.scribble="scribble",m.softedge="softedge",m))(te||{}),ne=(U=>(U.canny="canny",U.depth_leres="depth_leres",U.depth_midas="depth_midas",U.depth_zoe="depth_zoe",U.inpaint_global_harmonious="inpaint_global_harmonious",U.lineart_anime="lineart_anime",U.lineart_coarse="lineart_coarse",U.lineart_realistic="lineart_realistic",U.lineart_standard="lineart_standard",U.mlsd="mlsd",U.normal_bae="normal_bae",U.scribble_hed="scribble_hed",U.scribble_pidinet="scribble_pidinet",U.seg_ofade20k="seg_ofade20k",U.seg_ofcoco="seg_ofcoco",U.seg_ufade20k="seg_ufade20k",U.shuffle="shuffle",U.softedge_hed="softedge_hed",U.softedge_hedsafe="softedge_hedsafe",U.softedge_pidinet="softedge_pidinet",U.softedge_pidisafe="softedge_pidisafe",U.tile_gaussian="tile_gaussian",U.openpose="openpose",U.openpose_face="openpose_face",U.openpose_faceonly="openpose_faceonly",U.openpose_full="openpose_full",U.openpose_hand="openpose_hand",U))(ne||{}),fe=(r=>(r.openpose="openpose",r.openpose_face="openpose_face",r.openpose_faceonly="openpose_faceonly",r.openpose_full="openpose_full",r.openpose_hand="openpose_hand",r))(fe||{}),Te=(t=>(t.safetensors="safetensors",t.pickletensor="pickletensor",t))(Te||{}),be=(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))(be||{}),Re=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))(Re||{}),ke=(h=>(h.canny="canny",h.depth="depth",h.qrcode="qrcode",h.hed="hed",h.scrible="scrible",h.openpose="openpose",h.seg="segmentation",h.openmlsd="openmlsd",h.softedge="softedge",h.normal="normal bae",h.shuffle="shuffle",h.pix2pix="pix2pix",h.inpaint="inpaint",h.lineart="line art",h.sketch="sketch",h.inpaintdepth="inpaint depth",h.tile="tile",h.outfit="outfit",h.blur="blur",h.gray="gray",h.lowquality="low quality",h))(ke||{}),_e=(I=>(I.NoStyle="No style",I.Cinematic="Cinematic",I.DisneyCharacter="Disney Character",I.DigitalArt="Digital Art",I.Photographic="Photographic",I.FantasyArt="Fantasy art",I.Neonpunk="Neonpunk",I.Enhance="Enhance",I.ComicBook="Comic book",I.Lowpoly="Lowpoly",I.LineArt="Line art",I))(_e||{});var q=require("uuid"),H=6e4,G=1e3,De=100,se={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},xe=(i,e)=>{if(i==null)return;let t=i.indexOf(e);t!==-1&&i.splice(t,1)},w=(i,{debugKey:e="debugKey",timeoutDuration:t=H,shouldThrowError:n=!0,pollingInterval:s=De})=>(t=t<G?G:t,new Promise((r,a)=>{let l=setTimeout(()=>{o&&(clearInterval(o),n&&a(`Response could not be received from server for ${e}`)),clearTimeout(l)},t),o=setInterval(async()=>{i({resolve:r,reject:a,intervalId:o})&&(clearInterval(o),clearTimeout(l))},s)})),ve=i=>new Promise(e=>{let t=new FileReader;t.readAsDataURL(i),t.onload=function(){e(t.result)}}),_=()=>(0,q.v4)(),Se=i=>(0,q.validate)(i);var we=({key:i,data:e,useZero:t=!0,shouldReturnString:n=!1})=>i.split(/\.|\[/).map(a=>a.replace(/\]$/,"")).reduce((a,l)=>{let o=t?0:void 0,d=a?.[l];if(!d)return o;if(Array.isArray(d)&&/^\d+$/.test(l)){let g=parseInt(l,10);return g>=0&&g<d.length?a[l]=d[g]:a[l]??o}else return a[l]??o},e||{})??{},Ae=(i,e=1e3)=>new Promise(t=>setTimeout(t,i*e));var Ce=(i,e)=>i.filter(t=>t.key!==e.key);var T=({key:i,value:e})=>e||e===0||e===!1?{[i]:e}:{},at=(i,e)=>Math.floor(Math.random()*(e-i+1))+i,Ee=()=>at(1,Number.MAX_SAFE_INTEGER),Oe=(i,{debugKey:e="debugKey",timeoutDuration:t=H,shouldThrowError:n=!0,pollingInterval:s=De})=>(t=t<G?G:t,new Promise((r,a)=>{let l=setTimeout(()=>{o&&(clearInterval(o),n&&a(`Response could not be received from server for ${e}`)),clearTimeout(l)},t),o=setInterval(async()=>{try{await i({resolve:r,reject:a,intervalId:o})&&(clearInterval(o),clearTimeout(l))}catch(d){clearInterval(o),clearTimeout(l),a(d)}},s)}));var x=async(i,e={})=>{let{delayInSeconds:t=1,callback:n}=e,s=e.maxRetries??1;for(;s;)try{return await i()}catch(r){if(n?.(),r?.error)throw r;if(s--,s>0)await Ae(t),await x(i,{...e,maxRetries:s});else throw r}};var A=class{constructor({apiKey:e,url:t=se.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:s=2,timeoutDuration:r=H}){this._listeners=[];this._globalMessages={};this._globalImages=[];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=_();if(typeof e=="string"&&Se(e))return{imageURL:e,imageUUID:e,taskUUID:t,taskType:"imageUpload"};let n=typeof e=="string"?e:await ve(e);return{imageURL:n,imageUUID:n,taskUUID:t,taskType:"imageUpload"}})}catch(t){throw t}};this.controlNetPreProcess=async({inputImage:e,preProcessorType:t,height:n,width:s,outputType:r,outputFormat:a,highThresholdCanny:l,lowThresholdCanny:o,includeHandsAndFaceOpenPose:d,includeCost:g,outputQuality:I,customTaskUUID:m,taskUUID:u,retry:c,includeGenerationTime:y,includePayload:p})=>{let b=c||this._globalMaxRetries,f,k=Date.now();try{return await x(async()=>{await this.ensureConnection();let R=await this.uploadImage(e);if(!R?.imageUUID)return null;let h=u||m||_(),N={inputImage:R.imageUUID,taskType:"imageControlNetPreProcess",taskUUID:h,preProcessorType:t,...T({key:"height",value:n}),...T({key:"width",value:s}),...T({key:"outputType",value:r}),...T({key:"outputFormat",value:a}),...T({key:"includeCost",value:g}),...T({key:"highThresholdCanny",value:l}),...T({key:"lowThresholdCanny",value:o}),...T({key:"includeHandsAndFaceOpenPose",value:d}),...I?{outputQuality:I}:{}};this.send({...N}),f=this.globalListener({taskUUID:h});let L=await w(({resolve:z,reject:j})=>{let v=this.getSingleMessage({taskUUID:h});if(v){if(v?.error)return j(v),!0;if(v)return z(v),!0}},{debugKey:"unprocessed-image",timeoutDuration:this._timeoutDuration});return f.destroy(),this.insertAdditionalResponse({response:L,payload:p?N:void 0,startTime:y?k:void 0}),L},{maxRetries:b,callback:()=>{f?.destroy()}})}catch(R){throw R}};this.controlNetPreprocess=async e=>this.controlNetPreProcess(e);this.requestImageToText=async({inputImage:e,inputs:t,includeCost:n,customTaskUUID:s,taskUUID:r,retry:a,includePayload:l,includeGenerationTime:o,deliveryMethod:d,skipResponse:g,model:I})=>{try{let m;e&&(m=await this.uploadImage(e));let c={taskUUID:r||s||_(),taskType:"caption",model:I,inputImage:m?.imageUUID,inputs:t,...T({key:"includeCost",value:n}),retry:a,includePayload:l,includeGenerationTime:o},y=await this.baseSingleRequest({payload:{...c,taskType:"caption"},debugKey:"caption"});if(g)return y;if(d==="async"){let p=y?.taskUUID;return(await this.pollForAsyncResults({taskUUID:p,resultKeys:["text"]}))[0]}return y}catch(m){throw m}};this.caption=async e=>this.requestImageToText(e);this.removeImageBackground=async e=>{let{skipResponse:t,...n}=e;try{let s=n.deliveryMethod,r=await this.baseSingleRequest({payload:{...n,taskType:"removeBackground"},debugKey:"remove-background"});if(t)return r;if(s==="async"){let a=r?.taskUUID;return(await this.pollForAsyncResults({taskUUID:a}))[0]}return r}catch(s){throw s}};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:s,...r}=e;try{let a=await this.baseSingleRequest({payload:{...r,...n?.length&&{inputAudios:n},...s?.length&&{referenceVideos:s},deliveryMethod:"async",taskType:"videoInference"},debugKey:"video-inference"});if(t)return a;let l=a?.taskUUID;return this.pollForAsyncResults({taskUUID:l,numberResults:e?.numberResults})}catch(a){throw a}};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({inputImage:e,inputs:t,model:n,upscaleFactor:s,outputType:r,outputFormat:a,includeCost:l,outputQuality:o,customTaskUUID:d,taskUUID:g,retry:I,includeGenerationTime:m,includePayload:u,skipResponse:c,deliveryMethod:y})=>{try{let p;e&&(p=await this.uploadImage(e));let f={taskUUID:g||d||_(),inputImage:p?.imageUUID,taskType:"upscale",inputs:t,model:n,upscaleFactor:s,...T({key:"includeCost",value:l}),...r?{outputType:r}:{},...o?{outputQuality:o}:{},...a?{outputFormat:a}:{},includePayload:u,includeGenerationTime:m,retry:I,deliveryMethod:y},k=await this.baseSingleRequest({payload:{...f,taskType:"upscale"},debugKey:"upscale"});if(c)return k;if(y==="async"){let R=k?.taskUUID;return(await this.pollForAsyncResults({taskUUID:R}))[0]}return k}catch(p){throw p}};this.upscale=async e=>this.upscaleGan(e);this.enhancePrompt=async({prompt:e,promptMaxLength:t=380,promptVersions:n=1,includeCost:s,customTaskUUID:r,taskUUID:a,retry:l,includeGenerationTime:o,includePayload:d})=>{let g=l||this._globalMaxRetries,I,m=Date.now();try{return await x(async()=>{await this.ensureConnection();let u=a||r||_(),c={prompt:e,taskUUID:u,promptMaxLength:t,promptVersions:n,...T({key:"includeCost",value:s}),taskType:"promptEnhance"};this.send(c),I=this.globalListener({taskUUID:u});let y=await w(({resolve:p,reject:b})=>{let f=this._globalMessages[u];if(f?.error)return b(f),!0;if(f?.length>=n)return delete this._globalMessages[u],p(f),!0},{debugKey:"enhance-prompt",timeoutDuration:this._timeoutDuration});return I.destroy(),this.insertAdditionalResponse({response:y,payload:d?c:void 0,startTime:o?m:void 0}),y},{maxRetries:g,callback:()=>{I?.destroy()}})}catch(u){throw u}};this.promptEnhance=async e=>this.enhancePrompt(e);this.modelUpload=async e=>{let{onUploadStream:t,retry:n,customTaskUUID:s,taskUUID:r,...a}=e,l=n||this._globalMaxRetries,o;try{return await x(async()=>{await this.ensureConnection();let d=r||s||_();this.send({...a,taskUUID:d,taskType:"modelUpload"});let g,I;return o=this.listenToUpload({taskUUID:d,onUploadStream:(u,c)=>{t?.(u,c),u?.status==="ready"?g=u:c&&(I=c)}}),await w(({resolve:u,reject:c})=>{if(g)return u(g),!0;if(I)return c(I),!1},{shouldThrowError:!1,timeoutDuration:60*60*1e3})},{maxRetries:l,callback:()=>{o?.destroy()}})}catch(d){throw d}};this.photoMaker=async(e,t)=>{let{onPartialImages:n,retry:s,customTaskUUID:r,taskUUID:a,numberResults:l,includeGenerationTime:o,includePayload:d,...g}=e,I=s||this._globalMaxRetries,m,u=[],c=0,y=Date.now();try{return await x(async()=>{await this.ensureConnection(),c++;let p=this._globalImages.filter(h=>u.includes(h.taskUUID)),b=a||r||_();u.push(b);let f=l-p.length,k={...g,...g.seed?{seed:g.seed}:{seed:Ee()},...t??{},taskUUID:b,taskType:"photoMaker",numberResults:l};this.send({...k,numberResults:f}),m=this.listenToImages({onPartialImages:n,taskUUID:b,groupKey:"REQUEST_IMAGES",requestPayload:d?k:void 0,startTime:o?y:void 0});let R=await this.getSimilarImages({taskUUID:u,numberResults:l,lis:m});return m.destroy(),R},{maxRetries:I,callback:()=>{m?.destroy()}})}catch(p){if(p.taskUUID)throw p;if(c>=I)return this.handleIncompleteImages({taskUUIDs:u,error:p})}};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:s,customTaskUUID:r,taskUUID:a,includePayload:l,includeGenerationTime:o,...d}=e,g=s||this._globalMaxRetries,I,m=Date.now();try{return await x(async()=>{await this.ensureConnection();let u=a||r||_(),c={...d,taskUUID:u};this.send(c),I=this.globalListener({taskUUID:u});let y=await w(({resolve:p,reject:b})=>{let f=n?this.getMultipleMessages({taskUUID:u}):this.getSingleMessage({taskUUID:u});if(f){if(f?.error)return b(f),!0;if(f)return delete this._globalMessages[u],p(f),!0}},{debugKey:t,timeoutDuration:this._timeoutDuration});return this.insertAdditionalResponse({response:y,payload:l?c:void 0,startTime:o?m:void 0}),I.destroy(),y},{maxRetries:g,callback:()=>{I?.destroy()}})}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 s=e;s.additionalResponse={},t&&(e.additionalResponse.payload=t),n&&(e.additionalResponse.generationTime=Date.now()-n)};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=n,this._globalMaxRetries=s,this._timeoutDuration=r}getResultValue(e,t=["mediaUUID","imageUUID","videoUUID"]){for(let n of t)if(typeof e[n]=="string")return e[n]}async pollForAsyncResults({taskUUID:e,resultKeys:t,numberResults:n=1}){let s=new Map;return await Oe(async({resolve:r,reject:a})=>{try{let l=await this.getResponse({taskUUID:e});for(let d of l||[]){let g=this.getResultValue(d,t);g&&s.set(g,d)}return s.size===n?(r(Array.from(s.values())),!0):!1}catch(l){return a(l),!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:n}){let s=l=>{let o=Array.isArray(l?.data)?l.data:[l.data],d=l?.[0]?.errors?l?.[0]?.errors:Array.isArray(l?.errors)?l.errors:[l.errors],g=o.filter(m=>(m?.taskUUID||m?.taskType)===n);if(d.filter(m=>(m?.taskUUID||m?.taskType)===n).length){e({error:{...d[0]??{}}});return}if(g.length){e({[n]:o});return}},r={key:n||_(),listener:s,groupKey:t};return this._listeners.push(r),{destroy:()=>{this._listeners=Ce(this._listeners,r)}}}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 n of this._listeners)if(n?.listener?.(t))return},this._ws.onclose=e=>{this.isInvalidAPIKey()}}destroy(e){xe(this._listeners,e)}listenToImages({onPartialImages:e,taskUUID:t,groupKey:n,requestPayload:s,startTime:r}){return this.addListener({taskUUID:t,lis:a=>{let l=a?.[t]?.filter(o=>o.taskUUID===t);a.error?(e?.(l,a?.error&&a),this._globalError=a):(l=l.map(o=>(this.insertAdditionalResponse({response:o,payload:s||void 0,startTime:r||void 0}),{...o})),e?.(l,a?.error&&a),this._sdkType==="CLIENT"?this._globalImages=[...this._globalImages,...(a?.[t]??[]).map(o=>(this.insertAdditionalResponse({response:o,payload:s||void 0,startTime:r||void 0}),{...o}))]:this._globalImages=[...this._globalImages,...l])},groupKey:n})}listenToUpload({onUploadStream:e,taskUUID:t}){return this.addListener({taskUUID:t,lis:n=>{let s=n?.error,r=n?.[t]?.[0],a=r?.taskUUID===t?r:null;(a||s)&&e?.(a||void 0,s)}})}globalListener({taskUUID:e}){return this.addListener({taskUUID:e,lis:t=>{if(t.error){this._globalMessages[e]=t;return}let n=we({key:e,data:t,useZero:!1});Array.isArray(n)?n.forEach(s=>{this._globalMessages[s.taskUUID]=[...this._globalMessages[s.taskUUID]??[],s]}):this._globalMessages[n.taskUUID]=n}})}async requestImages({outputType:e,outputFormat:t,uploadEndpoint:n,checkNSFW:s,positivePrompt:r,negativePrompt:a,seedImage:l,maskImage:o,strength:d,height:g,width:I,model:m,steps:u,scheduler:c,seed:y,CFGScale:p,clipSkip:b,usePromptWeighting:f,promptWeighting:k,numberResults:R=1,onPartialImages:h,includeCost:N,customTaskUUID:L,taskUUID:z,retry:j,refiner:v,maskMargin:U,outputQuality:ae,controlNet:Q,lora:oe,embeddings:ie,ipAdapters:le,providerSettings:ue,outpaint:ce,acceleratorOptions:de,advancedFeatures:pe,referenceImages:ge,includeGenerationTime:Ve,includePayload:Be,...Ge},qe){let C,me,P=[],Ie=0,ye=j||this._globalMaxRetries;try{await this.ensureConnection();let S=null,J=null,Z=[];if(l){let D=await this.uploadImage(l);if(!D)return[];S=D.imageUUID}if(o){let D=await this.uploadImage(o);if(!D)return[];J=D.imageUUID}if(Q?.length)for(let D=0;D<Q.length;D++){let E=Q[D],{endStep:Y,startStep:K,weight:$,guideImage:W,controlMode:ze,startStepPercentage:je,endStepPercentage:Qe,model:Je}=E,Ze=W?await this.uploadImage(W):null;Z.push({guideImage:Ze?.imageUUID,model:Je,endStep:Y,startStep:K,weight:$,...T({key:"startStepPercentage",value:je}),...T({key:"endStepPercentage",value:Qe}),controlMode:ze||"controlnet"})}me={taskType:"imageInference",model:m,positivePrompt:r,...a?{negativePrompt:a}:{},...g?{height:g}:{},...I?{width:I}:{},numberResults:R,...e?{outputType:e}:{},...t?{outputFormat:t}:{},...n?{uploadEndpoint:n}:{},...T({key:"checkNSFW",value:s}),...T({key:"strength",value:d}),...T({key:"CFGScale",value:p}),...T({key:"clipSkip",value:b}),...T({key:"maskMargin",value:U}),...T({key:"usePromptWeighting",value:f}),...T({key:"steps",value:u}),...k?{promptWeighting:k}:{},...y?{seed:y}:{},...c?{scheduler:c}:{},...v?{refiner:v}:{},...ce?{outpaint:ce}:{},...T({key:"includeCost",value:N}),...S?{seedImage:S}:{},...J?{maskImage:J}:{},...ae?{outputQuality:ae}:{},...Z.length?{controlNet:Z}:{},...oe?.length?{lora:oe}:{},...ie?.length?{embeddings:ie}:{},...le?.length?{ipAdapters:le}:{},...ue?{providerSettings:ue}:{},...de?{acceleratorOptions:de}:{},...pe?{advancedFeatures:pe}:{},...ge?.length?{referenceImages:ge}:{},...Ge,...qe??{}};let He=Date.now();return await x(async()=>{Ie++,C?.destroy();let D=this._globalImages.filter(W=>P.includes(W.taskUUID)),E=z||L||_();P.push(E);let Y=R-D.length,K={...me,taskUUID:E,numberResults:Y};this.send(K),C=this.listenToImages({onPartialImages:h,taskUUID:E,groupKey:"REQUEST_IMAGES",requestPayload:Be?K:void 0,startTime:Ve?He:void 0});let $=await this.getSimilarImages({taskUUID:P,numberResults:R,lis:C});return C.destroy(),$},{maxRetries:ye,callback:()=>{C?.destroy()}})}catch(S){if(Ie>=ye)return this.handleIncompleteImages({taskUUIDs:P,error:S});throw S}}async imageInference(e,t){return this.requestImages(e,t)}async ensureConnection(){if(this.connected()||this._url===se.TEST)return;let t=2e3,n=200;try{if(this.isInvalidAPIKey())throw this._connectionError;return new Promise((s,r)=>{let a=0,l=30,o=_(),d,g,I=()=>{this.ensureConnectionUUID=null,clearInterval(d),clearInterval(g)};this._sdkType==="SERVER"&&(d=setInterval(async()=>{try{let m=this.connected(),u=!1;(!this.ensureConnectionUUID||o===this.ensureConnectionUUID)&&(this.ensureConnectionUUID||(this.ensureConnectionUUID=o),u=!0);let c=a%10===0&&u;m?(I(),s(!0)):a>=l?(I(),r(new Error("Retry timed out"))):(c&&this.connect(),a++)}catch(m){I(),r(m)}},t)),g=setInterval(async()=>{if(this.connected()){I(),s(!0);return}if(this.isInvalidAPIKey()){I(),r(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 getSimilarImages({taskUUID:e,numberResults:t,shouldThrowError:n,lis:s}){return await w(({resolve:r,reject:a,intervalId:l})=>{let o=Array.isArray(e)?e:[e],d=this._globalImages.filter(g=>o.includes(g.taskUUID));if(this._globalError){let g=this._globalError;return this._globalError=void 0,clearInterval(l),a?.(g),!0}else if(d.length>=t)return clearInterval(l),this._globalImages=this._globalImages.filter(g=>!o.includes(g.taskUUID)),r([...d].slice(0,t)),!0},{debugKey:"getting images",shouldThrowError:n,timeoutDuration:this._timeoutDuration})}handleIncompleteImages({taskUUIDs:e,error:t}){let n=this._globalImages.filter(s=>e.includes(s.taskUUID));if(n.length>1)return this._globalImages=this._globalImages.filter(s=>!e.includes(s.taskUUID)),n;throw t}};var We=Ue(Ke(),1),O=class extends A{constructor(e){let{shouldReconnect:t,...n}=e;super(n),this._ws=new We.default(this._url),this.connect()}};var Fe=Ue(require("ws"),1);var M=class extends A{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(){this._url&&(this.resetConnection(),this._ws=new Fe.default(this._url,{perMessageDeflate:!1}),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:t=>{if(t?.error){this._connectionError=t;return}this._connectionSessionUUID=t?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0}})}),this._ws.on("message",(t,n)=>{let s=n?t:t?.toString();if(!s)return;let r=JSON.parse(s);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 re;typeof window>"u"?re=M:re=O;0&&(module.exports={EControlMode,EModelArchitecture,EModelConditioning,EModelFormat,EModelType,EOpenPosePreProcessor,EPhotoMakerEnum,EPreProcessor,EPreProcessorGroup,ETaskType,Environment,Runware,RunwareClient,RunwareServer,SdkType});
1
+ "use strict";var $e=Object.create;var W=Object.defineProperty;var Ye=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var et=Object.getPrototypeOf,tt=Object.prototype.hasOwnProperty;var nt=(l,e)=>()=>(e||l((e={exports:{}}).exports,e),e.exports),st=(l,e)=>{for(var t in e)W(l,t,{get:e[t],enumerable:!0})},he=(l,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Xe(e))!tt.call(l,s)&&s!==t&&W(l,s,{get:()=>e[s],enumerable:!(n=Ye(e,s))||n.enumerable});return l};var Ue=(l,e,t)=>(t=l!=null?$e(et(l)):{},he(e||!l||!l.__esModule?W(t,"default",{value:l,enumerable:!0}):t,l)),rt=l=>he(W({},"__esModule",{value:!0}),l);var Ke=nt((hn,Le)=>{"use strict";var Ne=l=>l&&l.CLOSING===2,ot=()=>typeof WebSocket<"u"&&Ne(WebSocket),it=()=>({constructor:ot()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),lt=(l,e,t)=>{Object.defineProperty(e,t,{get:()=>l[t],set:n=>{l[t]=n},enumerable:!0,configurable:!0})},Me=l=>l.minReconnectionDelay+Math.random()*l.minReconnectionDelay,ut=(l,e)=>{let t=e*l.reconnectionDelayGrowFactor;return t>l.maxReconnectionDelay?l.maxReconnectionDelay:t},ct=["onopen","onclose","onmessage","onerror"],dt=(l,e,t)=>{Object.keys(t).forEach(n=>{t[n].forEach(([s,r])=>{l.addEventListener(n,s,r)})}),e&&ct.forEach(n=>{l[n]=e[n]})},Pe=function(l,e,t={}){let n,s,r=0,a=0,i=!0,o={};if(!(this instanceof Pe))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let d=it();if(Object.keys(d).filter(c=>t.hasOwnProperty(c)).forEach(c=>d[c]=t[c]),!Ne(d.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");let m=d.debug?(...c)=>console.log("RWS:",...c):()=>{},p=(c,y)=>setTimeout(()=>{let h=new Error(y);h.code=c,Array.isArray(o.error)&&o.error.forEach(([I])=>I(h)),n.onerror&&n.onerror(h)},0),g=()=>{if(m("close"),a++,m("retries count:",a),a>d.maxRetries){p("EHOSTDOWN","Too many failed connection attempts");return}r?r=ut(d,r):r=Me(d),m("reconnectDelay:",r),i&&setTimeout(u,r)},u=()=>{m("connect");let c=n;n=new d.constructor(l,e),s=setTimeout(()=>{m("timeout"),n.close(),p("ETIMEDOUT","Connection timeout")},d.connectionTimeout),m("bypass properties");for(let y in n)["addEventListener","removeEventListener","close","send"].indexOf(y)<0&&lt(n,this,y);n.addEventListener("open",()=>{clearTimeout(s),m("open"),r=Me(d),m("reconnectDelay:",r),a=0}),n.addEventListener("close",g),dt(n,c,o)};m("init"),u(),this.close=(c=1e3,y="",{keepClosed:h=!1,fastClose:I=!0,delay:f=0}={})=>{if(f&&(r=f),i=!h,n.close(c,y),I){let k={code:c,reason:y,wasClean:!0};g(),Array.isArray(o.close)&&o.close.forEach(([R,U])=>{R(k),n.removeEventListener("close",R,U)}),n.onclose&&(n.onclose(k),n.onclose=null)}},this.send=c=>{n.send(c)},this.addEventListener=(c,y,h)=>{Array.isArray(o[c])?o[c].some(([I])=>I===y)||o[c].push([y,h]):o[c]=[[y,h]],n.addEventListener(c,y,h)},this.removeEventListener=(c,y,h)=>{Array.isArray(o[c])&&(o[c]=o[c].filter(([I])=>I!==y)),n.removeEventListener(c,y,h)}};Le.exports=Pe});var pt={};st(pt,{EControlMode:()=>ee,EModelArchitecture:()=>Te,EModelConditioning:()=>ke,EModelFormat:()=>fe,EModelType:()=>Re,EOpenPosePreProcessor:()=>be,EPhotoMakerEnum:()=>_e,EPreProcessor:()=>ne,EPreProcessorGroup:()=>te,ETaskType:()=>V,Environment:()=>X,Runware:()=>re,RunwareClient:()=>O,RunwareServer:()=>M,SdkType:()=>q});module.exports=rt(pt);var X=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))(X||{}),q=(t=>(t.CLIENT="CLIENT",t.SERVER="SERVER",t))(q||{}),V=(I=>(I.IMAGE_INFERENCE="imageInference",I.IMAGE_UPLOAD="imageUpload",I.UPSCALE="upscale",I.REMOVE_BACKGROUND="removeBackground",I.VIDEO_INFERENCE="videoInference",I.CAPTION="caption",I.AUDIO_INFERENCE="audioInference",I.GET_RESPONSE="getResponse",I.PHOTO_MAKER="photoMaker",I.IMAGE_CONTROL_NET_PRE_PROCESS="imageControlNetPreProcess",I.IMAGE_MASKING="imageMasking",I.PROMPT_ENHANCE="promptEnhance",I.AUTHENTICATION="authentication",I.MODEL_UPLOAD="modelUpload",I.MODEL_SEARCH="modelSearch",I.MEDIA_STORAGE="mediaStorage",I.VECTORIZE="vectorize",I))(V||{}),ee=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(ee||{}),te=(g=>(g.canny="canny",g.depth="depth",g.mlsd="mlsd",g.normalbae="normalbae",g.openpose="openpose",g.tile="tile",g.seg="seg",g.lineart="lineart",g.lineart_anime="lineart_anime",g.shuffle="shuffle",g.scribble="scribble",g.softedge="softedge",g))(te||{}),ne=(b=>(b.canny="canny",b.depth_leres="depth_leres",b.depth_midas="depth_midas",b.depth_zoe="depth_zoe",b.inpaint_global_harmonious="inpaint_global_harmonious",b.lineart_anime="lineart_anime",b.lineart_coarse="lineart_coarse",b.lineart_realistic="lineart_realistic",b.lineart_standard="lineart_standard",b.mlsd="mlsd",b.normal_bae="normal_bae",b.scribble_hed="scribble_hed",b.scribble_pidinet="scribble_pidinet",b.seg_ofade20k="seg_ofade20k",b.seg_ofcoco="seg_ofcoco",b.seg_ufade20k="seg_ufade20k",b.shuffle="shuffle",b.softedge_hed="softedge_hed",b.softedge_hedsafe="softedge_hedsafe",b.softedge_pidinet="softedge_pidinet",b.softedge_pidisafe="softedge_pidisafe",b.tile_gaussian="tile_gaussian",b.openpose="openpose",b.openpose_face="openpose_face",b.openpose_faceonly="openpose_faceonly",b.openpose_full="openpose_full",b.openpose_hand="openpose_hand",b))(ne||{}),be=(r=>(r.openpose="openpose",r.openpose_face="openpose_face",r.openpose_faceonly="openpose_faceonly",r.openpose_full="openpose_full",r.openpose_hand="openpose_hand",r))(be||{}),fe=(t=>(t.safetensors="safetensors",t.pickletensor="pickletensor",t))(fe||{}),Te=(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))(Te||{}),Re=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))(Re||{}),ke=(U=>(U.canny="canny",U.depth="depth",U.qrcode="qrcode",U.hed="hed",U.scrible="scrible",U.openpose="openpose",U.seg="segmentation",U.openmlsd="openmlsd",U.softedge="softedge",U.normal="normal bae",U.shuffle="shuffle",U.pix2pix="pix2pix",U.inpaint="inpaint",U.lineart="line art",U.sketch="sketch",U.inpaintdepth="inpaint depth",U.tile="tile",U.outfit="outfit",U.blur="blur",U.gray="gray",U.lowquality="low quality",U))(ke||{}),_e=(p=>(p.NoStyle="No style",p.Cinematic="Cinematic",p.DisneyCharacter="Disney Character",p.DigitalArt="Digital Art",p.Photographic="Photographic",p.FantasyArt="Fantasy art",p.Neonpunk="Neonpunk",p.Enhance="Enhance",p.ComicBook="Comic book",p.Lowpoly="Lowpoly",p.LineArt="Line art",p))(_e||{});var G=require("uuid"),H=6e4,B=1e3,De=100,se={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},xe=(l,e)=>{if(l==null)return;let t=l.indexOf(e);t!==-1&&l.splice(t,1)},A=(l,{debugKey:e="debugKey",timeoutDuration:t=H,shouldThrowError:n=!0,pollingInterval:s=De})=>(t=t<B?B:t,new Promise((r,a)=>{let i=setTimeout(()=>{o&&(clearInterval(o),n&&a(`Response could not be received from server for ${e}`)),clearTimeout(i)},t),o=setInterval(async()=>{l({resolve:r,reject:a,intervalId:o})&&(clearInterval(o),clearTimeout(i))},s)})),ve=l=>new Promise(e=>{let t=new FileReader;t.readAsDataURL(l),t.onload=function(){e(t.result)}}),_=()=>(0,G.v4)(),Se=l=>(0,G.validate)(l);var Ae=({key:l,data:e,useZero:t=!0,shouldReturnString:n=!1})=>l.split(/\.|\[/).map(a=>a.replace(/\]$/,"")).reduce((a,i)=>{let o=t?0:void 0,d=a?.[i];if(!d)return o;if(Array.isArray(d)&&/^\d+$/.test(i)){let m=parseInt(i,10);return m>=0&&m<d.length?a[i]=d[m]:a[i]??o}else return a[i]??o},e||{})??{},we=(l,e=1e3)=>new Promise(t=>setTimeout(t,l*e));var Ee=(l,e)=>l.filter(t=>t.key!==e.key);var T=({key:l,value:e})=>e||e===0||e===!1?{[l]:e}:{},at=(l,e)=>Math.floor(Math.random()*(e-l+1))+l,Ce=()=>at(1,Number.MAX_SAFE_INTEGER),Oe=(l,{debugKey:e="debugKey",timeoutDuration:t=H,shouldThrowError:n=!0,pollingInterval:s=De})=>(t=t<B?B:t,new Promise((r,a)=>{let i=setTimeout(()=>{o&&(clearInterval(o),n&&a(`Response could not be received from server for ${e}`)),clearTimeout(i)},t),o=setInterval(async()=>{try{await l({resolve:r,reject:a,intervalId:o})&&(clearInterval(o),clearTimeout(i))}catch(d){clearInterval(o),clearTimeout(i),a(d)}},s)}));var x=async(l,e={})=>{let{delayInSeconds:t=1,callback:n}=e,s=e.maxRetries??1;for(;s;)try{return await l()}catch(r){if(n?.(),r?.error)throw r;if(s--,s>0)await we(t),await x(l,{...e,maxRetries:s});else throw r}};var w=class{constructor({apiKey:e,url:t=se.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:s=2,timeoutDuration:r=H}){this._listeners=[];this._globalMessages={};this._globalImages=[];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=_();if(typeof e=="string"&&Se(e))return{imageURL:e,imageUUID:e,taskUUID:t,taskType:"imageUpload"};let n=typeof e=="string"?e:await ve(e);return{imageURL:n,imageUUID:n,taskUUID:t,taskType:"imageUpload"}})}catch(t){throw t}};this.controlNetPreProcess=async({inputImage:e,preProcessorType:t,height:n,width:s,outputType:r,outputFormat:a,highThresholdCanny:i,lowThresholdCanny:o,includeHandsAndFaceOpenPose:d,includeCost:m,outputQuality:p,customTaskUUID:g,taskUUID:u,retry:c,includeGenerationTime:y,includePayload:h})=>{let I=c||this._globalMaxRetries,f,k=Date.now();try{return await x(async()=>{await this.ensureConnection();let R=await this.uploadImage(e);if(!R?.imageUUID)return null;let U=u||g||_(),N={inputImage:R.imageUUID,taskType:"imageControlNetPreProcess",taskUUID:U,preProcessorType:t,...T({key:"height",value:n}),...T({key:"width",value:s}),...T({key:"outputType",value:r}),...T({key:"outputFormat",value:a}),...T({key:"includeCost",value:m}),...T({key:"highThresholdCanny",value:i}),...T({key:"lowThresholdCanny",value:o}),...T({key:"includeHandsAndFaceOpenPose",value:d}),...p?{outputQuality:p}:{}};this.send({...N}),f=this.globalListener({taskUUID:U});let P=await A(({resolve:z,reject:Q})=>{let v=this.getSingleMessage({taskUUID:U});if(v){if(v?.error)return Q(v),!0;if(v)return z(v),!0}},{debugKey:"unprocessed-image",timeoutDuration:this._timeoutDuration});return f.destroy(),this.insertAdditionalResponse({response:P,payload:h?N:void 0,startTime:y?k:void 0}),P},{maxRetries:I,callback:()=>{f?.destroy()}})}catch(R){throw R}};this.controlNetPreprocess=async e=>this.controlNetPreProcess(e);this.requestImageToText=async({inputImage:e,inputs:t,includeCost:n,customTaskUUID:s,taskUUID:r,retry:a,includePayload:i,includeGenerationTime:o,deliveryMethod:d,skipResponse:m,model:p})=>{try{let g;e&&(g=await this.uploadImage(e));let c={taskUUID:r||s||_(),taskType:"caption",model:p,inputImage:g?.imageUUID,inputs:t,...T({key:"includeCost",value:n}),retry:a,includePayload:i,includeGenerationTime:o},y=await this.baseSingleRequest({payload:{...c,taskType:"caption"},debugKey:"caption"});if(m)return y;if(d==="async"){let h=y?.taskUUID;return(await this.pollForAsyncResults({taskUUID:h}))[0]}return y}catch(g){throw g}};this.caption=async e=>this.requestImageToText(e);this.removeImageBackground=async e=>{let{skipResponse:t,...n}=e;try{let s=n.deliveryMethod,r=await this.baseSingleRequest({payload:{...n,taskType:"removeBackground"},debugKey:"remove-background"});if(t)return r;if(s==="async"){let a=r?.taskUUID;return(await this.pollForAsyncResults({taskUUID:a}))[0]}return r}catch(s){throw s}};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:s,...r}=e;try{let a=await this.baseSingleRequest({payload:{...r,...n?.length&&{inputAudios:n},...s?.length&&{referenceVideos:s},deliveryMethod:"async",taskType:"videoInference"},debugKey:"video-inference"});if(t)return a;let i=a?.taskUUID;return this.pollForAsyncResults({taskUUID:i,numberResults:e?.numberResults})}catch(a){throw a}};this.audioInference=async e=>{let{skipResponse:t,deliveryMethod:n="sync",...s}=e;try{let a=await(n==="sync"?this.baseSyncRequest:this.baseSingleRequest)({payload:{...s,numberResults:s.numberResults||1,taskType:"audioInference",deliveryMethod:n},debugKey:"audio-inference"});if(t)return a;let i=a?.taskUUID;return n==="async"?this.pollForAsyncResults({taskUUID:i,numberResults:e?.numberResults}):a}catch(r){throw r}};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({inputImage:e,inputs:t,model:n,upscaleFactor:s,outputType:r,outputFormat:a,includeCost:i,outputQuality:o,customTaskUUID:d,taskUUID:m,retry:p,includeGenerationTime:g,includePayload:u,skipResponse:c,deliveryMethod:y})=>{try{let h;e&&(h=await this.uploadImage(e));let f={taskUUID:m||d||_(),inputImage:h?.imageUUID,taskType:"upscale",inputs:t,model:n,upscaleFactor:s,...T({key:"includeCost",value:i}),...r?{outputType:r}:{},...o?{outputQuality:o}:{},...a?{outputFormat:a}:{},includePayload:u,includeGenerationTime:g,retry:p,deliveryMethod:y},k=await this.baseSingleRequest({payload:{...f,taskType:"upscale"},debugKey:"upscale"});if(c)return k;if(y==="async"){let R=k?.taskUUID;return(await this.pollForAsyncResults({taskUUID:R}))[0]}return k}catch(h){throw h}};this.upscale=async e=>this.upscaleGan(e);this.enhancePrompt=async({prompt:e,promptMaxLength:t=380,promptVersions:n=1,includeCost:s,customTaskUUID:r,taskUUID:a,retry:i,includeGenerationTime:o,includePayload:d})=>{let m=i||this._globalMaxRetries,p,g=Date.now();try{return await x(async()=>{await this.ensureConnection();let u=a||r||_(),c={prompt:e,taskUUID:u,promptMaxLength:t,promptVersions:n,...T({key:"includeCost",value:s}),taskType:"promptEnhance"};this.send(c),p=this.globalListener({taskUUID:u});let y=await A(({resolve:h,reject:I})=>{let f=this._globalMessages[u];if(f?.error)return I(f),!0;if(f?.length>=n)return delete this._globalMessages[u],h(f),!0},{debugKey:"enhance-prompt",timeoutDuration:this._timeoutDuration});return p.destroy(),this.insertAdditionalResponse({response:y,payload:d?c:void 0,startTime:o?g:void 0}),y},{maxRetries:m,callback:()=>{p?.destroy()}})}catch(u){throw u}};this.promptEnhance=async e=>this.enhancePrompt(e);this.modelUpload=async e=>{let{onUploadStream:t,retry:n,customTaskUUID:s,taskUUID:r,...a}=e,i=n||this._globalMaxRetries,o;try{return await x(async()=>{await this.ensureConnection();let d=r||s||_();this.send({...a,taskUUID:d,taskType:"modelUpload"});let m,p;return o=this.listenToUpload({taskUUID:d,onUploadStream:(u,c)=>{t?.(u,c),u?.status==="ready"?m=u:c&&(p=c)}}),await A(({resolve:u,reject:c})=>{if(m)return u(m),!0;if(p)return c(p),!1},{shouldThrowError:!1,timeoutDuration:60*60*1e3})},{maxRetries:i,callback:()=>{o?.destroy()}})}catch(d){throw d}};this.photoMaker=async(e,t)=>{let{onPartialImages:n,retry:s,customTaskUUID:r,taskUUID:a,numberResults:i,includeGenerationTime:o,includePayload:d,...m}=e,p=s||this._globalMaxRetries,g,u=[],c=0,y=Date.now();try{return await x(async()=>{await this.ensureConnection(),c++;let h=this._globalImages.filter(U=>u.includes(U.taskUUID)),I=a||r||_();u.push(I);let f=i-h.length,k={...m,...m.seed?{seed:m.seed}:{seed:Ce()},...t??{},taskUUID:I,taskType:"photoMaker",numberResults:i};this.send({...k,numberResults:f}),g=this.listenToResponse({onPartialImages:n,taskUUID:I,groupKey:"REQUEST_IMAGES",requestPayload:d?k:void 0,startTime:o?y:void 0});let R=await this.getSimilarImages({taskUUID:u,numberResults:i,lis:g});return g.destroy(),R},{maxRetries:p,callback:()=>{g?.destroy()}})}catch(h){if(h.taskUUID)throw h;if(c>=p)return this.handleIncompleteImages({taskUUIDs:u,error:h})}};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:s,customTaskUUID:r,taskUUID:a,includePayload:i,includeGenerationTime:o,...d}=e,m=s||this._globalMaxRetries,p,g=Date.now();try{return await x(async()=>{await this.ensureConnection();let u=a||r||_(),c={...d,taskUUID:u};this.send(c),p=this.globalListener({taskUUID:u});let y=await A(({resolve:h,reject:I})=>{let f=n?this.getMultipleMessages({taskUUID:u}):this.getSingleMessage({taskUUID:u});if(f){if(f?.error)return I(f),!0;if(f)return delete this._globalMessages[u],h(f),!0}},{debugKey:t,timeoutDuration:this._timeoutDuration});return this.insertAdditionalResponse({response:y,payload:i?c:void 0,startTime:o?g:void 0}),p.destroy(),y},{maxRetries:m,callback:()=>{p?.destroy()}})}catch(u){throw u}};this.baseSyncRequest=async({payload:e,debugKey:t})=>{let{retry:n,customTaskUUID:s,includePayload:r,numberResults:a=1,onPartialResponse:i,includeGenerationTime:o,...d}=e,m=n||this._globalMaxRetries,p,g=[],u=0,c=Date.now();try{return await x(async()=>{await this.ensureConnection(),u++;let y=this._globalImages.filter(R=>g.includes(R.taskUUID)),h=s||_();g.push(h);let I=a-y.length,f={...d,taskUUID:h,numberResults:I};this.send(f),p=this.listenToResponse({onPartialImages:i,taskUUID:h,groupKey:"REQUEST_AUDIO",requestPayload:r?f:void 0,startTime:o?c:void 0});let k=await this.getSimilarImages({taskUUID:g,numberResults:a,lis:p});return p.destroy(),k},{maxRetries:m,callback:()=>{p?.destroy()}})}catch(y){throw y}};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 s=e;s.additionalResponse={},t&&(e.additionalResponse.payload=t),n&&(e.additionalResponse.generationTime=Date.now()-n)};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=n,this._globalMaxRetries=s,this._timeoutDuration=r}getUniqueUUID(e){return e.mediaUUID||e.audioUUID||e.imageUUID||e.videoUUID}async pollForAsyncResults({taskUUID:e,numberResults:t=1}){let n=new Map;return await Oe(async({resolve:s,reject:r})=>{try{let a=await this.getResponse({taskUUID:e});for(let o of a||[])if(o.status==="success"){let d=this.getUniqueUUID(o);d&&n.set(d,o)}return n.size===t?(s(Array.from(n.values())),!0):!1}catch(a){return r(a),!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}}addListener({lis:e,groupKey:t,taskUUID:n}){let s=i=>{let o=Array.isArray(i?.data)?i.data:[i.data],d=i?.[0]?.errors?i?.[0]?.errors:Array.isArray(i?.errors)?i.errors:[i.errors],m=o.filter(g=>(g?.taskUUID||g?.taskType)===n);if(d.filter(g=>(g?.taskUUID||g?.taskType)===n).length){e({error:{...d[0]??{}}});return}if(m.length){e({[n]:o});return}},r={key:n||_(),listener:s,groupKey:t};return this._listeners.push(r),{destroy:()=>{this._listeners=Ee(this._listeners,r)}}}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 n of this._listeners)if(n?.listener?.(t))return},this._ws.onclose=e=>{this.isInvalidAPIKey()}}destroy(e){xe(this._listeners,e)}listenToResponse({onPartialImages:e,taskUUID:t,groupKey:n,requestPayload:s,startTime:r}){return this.addListener({taskUUID:t,lis:a=>{let i=a?.[t]?.filter(o=>o.taskUUID===t);a.error?(e?.(i,a?.error&&a),this._globalError=a):(i=i.map(o=>(this.insertAdditionalResponse({response:o,payload:s||void 0,startTime:r||void 0}),{...o})),e?.(i,a?.error&&a),this._sdkType==="CLIENT"?this._globalImages=[...this._globalImages,...(a?.[t]??[]).map(o=>(this.insertAdditionalResponse({response:o,payload:s||void 0,startTime:r||void 0}),{...o}))]:this._globalImages=[...this._globalImages,...i])},groupKey:n})}listenToUpload({onUploadStream:e,taskUUID:t}){return this.addListener({taskUUID:t,lis:n=>{let s=n?.error,r=n?.[t]?.[0],a=r?.taskUUID===t?r:null;(a||s)&&e?.(a||void 0,s)}})}globalListener({taskUUID:e}){return this.addListener({taskUUID:e,lis:t=>{if(t.error){this._globalMessages[e]=t;return}let n=Ae({key:e,data:t,useZero:!1});Array.isArray(n)?n.forEach(s=>{this._globalMessages[s.taskUUID]=[...this._globalMessages[s.taskUUID]??[],s]}):this._globalMessages[n.taskUUID]=n}})}async requestImages({outputType:e,outputFormat:t,uploadEndpoint:n,checkNSFW:s,positivePrompt:r,negativePrompt:a,seedImage:i,maskImage:o,strength:d,height:m,width:p,model:g,steps:u,scheduler:c,seed:y,CFGScale:h,clipSkip:I,usePromptWeighting:f,promptWeighting:k,numberResults:R=1,onPartialImages:U,includeCost:N,customTaskUUID:P,taskUUID:z,retry:Q,refiner:v,maskMargin:b,outputQuality:ae,controlNet:j,lora:oe,embeddings:ie,ipAdapters:le,providerSettings:ue,outpaint:ce,acceleratorOptions:de,advancedFeatures:pe,referenceImages:ge,includeGenerationTime:qe,includePayload:Ve,...Be},Ge){let E,me,L=[],Ie=0,ye=Q||this._globalMaxRetries;try{await this.ensureConnection();let S=null,J=null,Z=[];if(i){let D=await this.uploadImage(i);if(!D)return[];S=D.imageUUID}if(o){let D=await this.uploadImage(o);if(!D)return[];J=D.imageUUID}if(j?.length)for(let D=0;D<j.length;D++){let C=j[D],{endStep:$,startStep:K,weight:Y,guideImage:F,controlMode:ze,startStepPercentage:Qe,endStepPercentage:je,model:Je}=C,Ze=F?await this.uploadImage(F):null;Z.push({guideImage:Ze?.imageUUID,model:Je,endStep:$,startStep:K,weight:Y,...T({key:"startStepPercentage",value:Qe}),...T({key:"endStepPercentage",value:je}),controlMode:ze||"controlnet"})}me={taskType:"imageInference",model:g,positivePrompt:r,...a?{negativePrompt:a}:{},...m?{height:m}:{},...p?{width:p}:{},numberResults:R,...e?{outputType:e}:{},...t?{outputFormat:t}:{},...n?{uploadEndpoint:n}:{},...T({key:"checkNSFW",value:s}),...T({key:"strength",value:d}),...T({key:"CFGScale",value:h}),...T({key:"clipSkip",value:I}),...T({key:"maskMargin",value:b}),...T({key:"usePromptWeighting",value:f}),...T({key:"steps",value:u}),...k?{promptWeighting:k}:{},...y?{seed:y}:{},...c?{scheduler:c}:{},...v?{refiner:v}:{},...ce?{outpaint:ce}:{},...T({key:"includeCost",value:N}),...S?{seedImage:S}:{},...J?{maskImage:J}:{},...ae?{outputQuality:ae}:{},...Z.length?{controlNet:Z}:{},...oe?.length?{lora:oe}:{},...ie?.length?{embeddings:ie}:{},...le?.length?{ipAdapters:le}:{},...ue?{providerSettings:ue}:{},...de?{acceleratorOptions:de}:{},...pe?{advancedFeatures:pe}:{},...ge?.length?{referenceImages:ge}:{},...Be,...Ge??{}};let He=Date.now();return await x(async()=>{Ie++,E?.destroy();let D=this._globalImages.filter(F=>L.includes(F.taskUUID)),C=z||P||_();L.push(C);let $=R-D.length,K={...me,taskUUID:C,numberResults:$};this.send(K),E=this.listenToResponse({onPartialImages:U,taskUUID:C,groupKey:"REQUEST_IMAGES",requestPayload:Ve?K:void 0,startTime:qe?He:void 0});let Y=await this.getSimilarImages({taskUUID:L,numberResults:R,lis:E});return E.destroy(),Y},{maxRetries:ye,callback:()=>{E?.destroy()}})}catch(S){if(Ie>=ye)return this.handleIncompleteImages({taskUUIDs:L,error:S});throw S}}async imageInference(e,t){return this.requestImages(e,t)}async ensureConnection(){if(this.connected()||this._url===se.TEST)return;let t=2e3,n=200;try{if(this.isInvalidAPIKey())throw this._connectionError;return new Promise((s,r)=>{let a=0,i=30,o=_(),d,m,p=()=>{this.ensureConnectionUUID=null,clearInterval(d),clearInterval(m)};this._sdkType==="SERVER"&&(d=setInterval(async()=>{try{let g=this.connected(),u=!1;(!this.ensureConnectionUUID||o===this.ensureConnectionUUID)&&(this.ensureConnectionUUID||(this.ensureConnectionUUID=o),u=!0);let c=a%10===0&&u;g?(p(),s(!0)):a>=i?(p(),r(new Error("Retry timed out"))):(c&&this.connect(),a++)}catch(g){p(),r(g)}},t)),m=setInterval(async()=>{if(this.connected()){p(),s(!0);return}if(this.isInvalidAPIKey()){p(),r(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 getSimilarImages({taskUUID:e,numberResults:t,shouldThrowError:n,lis:s}){return await A(({resolve:r,reject:a,intervalId:i})=>{let o=Array.isArray(e)?e:[e],d=this._globalImages.filter(m=>o.includes(m.taskUUID));if(this._globalError){let m=this._globalError;return this._globalError=void 0,clearInterval(i),a?.(m),!0}else if(d.length>=t)return clearInterval(i),this._globalImages=this._globalImages.filter(m=>!o.includes(m.taskUUID)),r([...d].slice(0,t)),!0},{debugKey:"getting images",shouldThrowError:n,timeoutDuration:this._timeoutDuration})}handleIncompleteImages({taskUUIDs:e,error:t}){let n=this._globalImages.filter(s=>e.includes(s.taskUUID));if(n.length>1)return this._globalImages=this._globalImages.filter(s=>!e.includes(s.taskUUID)),n;throw t}};var Fe=Ue(Ke(),1),O=class extends w{constructor(e){let{shouldReconnect:t,...n}=e;super(n),this._ws=new Fe.default(this._url),this.connect()}};var We=Ue(require("ws"),1);var M=class extends w{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(){this._url&&(this.resetConnection(),this._ws=new We.default(this._url,{perMessageDeflate:!1}),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:t=>{if(t?.error){this._connectionError=t;return}this._connectionSessionUUID=t?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0}})}),this._ws.on("message",(t,n)=>{let s=n?t:t?.toString();if(!s)return;let r=JSON.parse(s);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 re;typeof window>"u"?re=M:re=O;0&&(module.exports={EControlMode,EModelArchitecture,EModelConditioning,EModelFormat,EModelType,EOpenPosePreProcessor,EPhotoMakerEnum,EPreProcessor,EPreProcessorGroup,ETaskType,Environment,Runware,RunwareClient,RunwareServer,SdkType});
2
2
  //# sourceMappingURL=index.cjs.map