@runware/sdk-js 1.1.49 → 1.1.50

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