@runware/sdk-js 1.1.41-beta.2 → 1.1.41-beta.3

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 Je=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var Ze=Object.getPrototypeOf,$e=Object.prototype.hasOwnProperty;var Xe=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),et=(r,t)=>{for(var e in t)F(r,e,{get:t[e],enumerable:!0})},me=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ze(t))!$e.call(r,s)&&s!==e&&F(r,s,{get:()=>t[s],enumerable:!(n=Je(t,s))||n.enumerable});return r};var ye=(r,t,e)=>(e=r!=null?Ye(Ze(r)):{},me(t||!r||!r.__esModule?F(e,"default",{value:r,enumerable:!0}):e,r)),tt=r=>me(F({},"__esModule",{value:!0}),r);var Me=Xe((on,Oe)=>{"use strict";var Ee=r=>r&&r.CLOSING===2,at=()=>typeof WebSocket<"u"&&Ee(WebSocket),ot=()=>({constructor:at()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),it=(r,t,e)=>{Object.defineProperty(t,e,{get:()=>r[e],set:n=>{r[e]=n},enumerable:!0,configurable:!0})},Ce=r=>r.minReconnectionDelay+Math.random()*r.minReconnectionDelay,lt=(r,t)=>{let e=t*r.reconnectionDelayGrowFactor;return e>r.maxReconnectionDelay?r.maxReconnectionDelay:e},ct=["onopen","onclose","onmessage","onerror"],ut=(r,t,e)=>{Object.keys(e).forEach(n=>{e[n].forEach(([s,a])=>{r.addEventListener(n,s,a)})}),t&&ct.forEach(n=>{r[n]=t[n]})},Ne=function(r,t,e={}){let n,s,a=0,c=0,u=!0,l={};if(!(this instanceof Ne))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let p=ot();if(Object.keys(p).filter(i=>e.hasOwnProperty(i)).forEach(i=>p[i]=e[i]),!Ee(p.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");let d=p.debug?(...i)=>console.log("RWS:",...i):()=>{},g=(i,y)=>setTimeout(()=>{let I=new Error(y);I.code=i,Array.isArray(l.error)&&l.error.forEach(([f])=>f(I)),n.onerror&&n.onerror(I)},0),o=()=>{if(d("close"),c++,d("retries count:",c),c>p.maxRetries){g("EHOSTDOWN","Too many failed connection attempts");return}a?a=lt(p,a):a=Ce(p),d("reconnectDelay:",a),u&&setTimeout(m,a)},m=()=>{d("connect");let i=n;n=new p.constructor(r,t),s=setTimeout(()=>{d("timeout"),n.close(),g("ETIMEDOUT","Connection timeout")},p.connectionTimeout),d("bypass properties");for(let y in n)["addEventListener","removeEventListener","close","send"].indexOf(y)<0&&it(n,this,y);n.addEventListener("open",()=>{clearTimeout(s),d("open"),a=Ce(p),d("reconnectDelay:",a),c=0}),n.addEventListener("close",o),ut(n,i,l)};d("init"),m(),this.close=(i=1e3,y="",{keepClosed:I=!1,fastClose:f=!0,delay:k=0}={})=>{if(k&&(a=k),u=!I,n.close(i,y),f){let _={code:i,reason:y,wasClean:!0};o(),Array.isArray(l.close)&&l.close.forEach(([U,b])=>{U(_),n.removeEventListener("close",U,b)}),n.onclose&&(n.onclose(_),n.onclose=null)}},this.send=i=>{n.send(i)},this.addEventListener=(i,y,I)=>{Array.isArray(l[i])?l[i].some(([f])=>f===y)||l[i].push([y,I]):l[i]=[[y,I]],n.addEventListener(i,y,I)},this.removeEventListener=(i,y,I)=>{Array.isArray(l[i])&&(l[i]=l[i].filter(([f])=>f!==y)),n.removeEventListener(i,y,I)}};Oe.exports=Ne});var dt={};et(dt,{EControlMode:()=>Z,EModelArchitecture:()=>fe,EModelConditioning:()=>Te,EModelFormat:()=>he,EModelType:()=>be,EOpenPosePreProcessor:()=>Ie,EPhotoMakerEnum:()=>Ue,EPreProcessor:()=>X,EPreProcessorGroup:()=>$,ETaskType:()=>G,Environment:()=>z,Runware:()=>se,RunwareClient:()=>N,RunwareServer:()=>O,SdkType:()=>W});module.exports=tt(dt);var z=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))(z||{}),W=(e=>(e.CLIENT="CLIENT",e.SERVER="SERVER",e))(W||{}),G=(i=>(i.IMAGE_INFERENCE="imageInference",i.IMAGE_UPLOAD="imageUpload",i.IMAGE_UPSCALE="imageUpscale",i.IMAGE_BACKGROUND_REMOVAL="imageBackgroundRemoval",i.VIDEO_INFERENCE="videoInference",i.ASYNC_RESULTS="asyncResults",i.PHOTO_MAKER="photoMaker",i.IMAGE_CAPTION="imageCaption",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))(G||{}),Z=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(Z||{}),$=(o=>(o.canny="canny",o.depth="depth",o.mlsd="mlsd",o.normalbae="normalbae",o.openpose="openpose",o.tile="tile",o.seg="seg",o.lineart="lineart",o.lineart_anime="lineart_anime",o.shuffle="shuffle",o.scribble="scribble",o.softedge="softedge",o))($||{}),X=(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))(X||{}),Ie=(a=>(a.openpose="openpose",a.openpose_face="openpose_face",a.openpose_faceonly="openpose_faceonly",a.openpose_full="openpose_full",a.openpose_hand="openpose_hand",a))(Ie||{}),he=(e=>(e.safetensors="safetensors",e.pickletensor="pickletensor",e))(he||{}),fe=(m=>(m.flux1d="flux1d",m.flux1s="flux1s",m.pony="pony",m.sdhyper="sdhyper",m.sd1x="sd1x",m.sd1xlcm="sd1xlcm",m.sd3="sd3",m.sdxl="sdxl",m.sdxllcm="sdxllcm",m.sdxldistilled="sdxldistilled",m.sdxlhyper="sdxlhyper",m.sdxllightning="sdxllightning",m.sdxlturbo="sdxlturbo",m))(fe||{}),be=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))(be||{}),Te=(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))(Te||{}),Ue=(g=>(g.NoStyle="No style",g.Cinematic="Cinematic",g.DisneyCharacter="Disney Character",g.DigitalArt="Digital Art",g.Photographic="Photographic",g.FantasyArt="Fantasy art",g.Neonpunk="Neonpunk",g.Enhance="Enhance",g.ComicBook="Comic book",g.Lowpoly="Lowpoly",g.LineArt="Line art",g))(Ue||{});var B=require("uuid"),ee=6e4,_e=1e3,nt=100,te={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},ke=(r,t)=>{if(r==null)return;let e=r.indexOf(t);e!==-1&&r.splice(e,1)},S=(r,{debugKey:t="debugKey",timeoutDuration:e=ee,shouldThrowError:n=!0})=>(e=e<_e?_e:e,new Promise((s,a)=>{let c=setTimeout(()=>{u&&(clearInterval(u),n&&a(`Response could not be received from server for ${t}`)),clearTimeout(c)},e),u=setInterval(async()=>{r({resolve:s,reject:a,intervalId:u})&&(clearInterval(u),clearTimeout(c))},nt)})),De=r=>new Promise(t=>{let e=new FileReader;e.readAsDataURL(r),e.onload=function(){t(e.result)}}),R=()=>(0,B.v4)(),xe=r=>(0,B.validate)(r);var ve=({key:r,data:t,useZero:e=!0,shouldReturnString:n=!1})=>r.split(/\.|\[/).map(c=>c.replace(/\]$/,"")).reduce((c,u)=>{let l=e?0:void 0,p=c?.[u];if(!p)return l;if(Array.isArray(p)&&/^\d+$/.test(u)){let d=parseInt(u,10);return d>=0&&d<p.length?c[u]=p[d]:c[u]??l}else return c[u]??l},t||{})??{},Se=(r,t=1e3)=>new Promise(e=>setTimeout(e,r*t));var we=(r,t)=>r.filter(e=>e.key!==t.key);var T=({key:r,value:t})=>t||t===0||t===!1?{[r]:t}:{},st=(r,t)=>Math.floor(Math.random()*(t-r+1))+r,ne=()=>st(1,Number.MAX_SAFE_INTEGER),Ae=({count:r,taskUUID:t})=>{let e=[];for(let n=0;n<r;n++){let s=Math.random()<.5,a={taskUUID:t,taskType:"videoInference"};s?e.push({...a,status:"succeeded",videoUUID:crypto.randomUUID(),cost:parseFloat((Math.random()*10).toFixed(2)),seed:Math.floor(Math.random()*100),videoURL:rt()}):e.push({...a,status:"pending"})}return e},Re=["https://vm.runware.dev/video/ws/2/vi/032dd763-4082-4fa4-aa7c-ca2e0d272c08.mp4","https://vm.runware.dev/video/ws/2/vi/4f809a60-47bb-49e7-9a31-c8834a8bf143.mp4","https://vm.runware.dev/video/ws/2/vi/3a146615-5ba6-4844-9d54-6455617554f8.mp4","https://www.w3schools.com/html/mov_bbb.mp4","https://filesamples.com/samples/video/mp4/sample_640x360.mp4","https://media.w3.org/2010/05/sintel/trailer.mp4","https://samplelib.com/lib/preview/mp4/sample-5s.mp4","https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/720/Big_Buck_Bunny_720_10s_1MB.mp4"];function rt(){let r=Math.floor(Math.random()*Re.length);return Re[r]}var x=async(r,t={})=>{let{delayInSeconds:e=1,callback:n}=t,s=t.maxRetries??1;for(;s;)try{return await r()}catch(a){if(n?.(),s--,s>0)await Se(e),await x(r,{...t,maxRetries:s});else throw a}};var A=class{constructor({apiKey:t,url:e=te.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:s=2,timeoutDuration:a=ee}){this._listeners=[];this._globalMessages={};this._globalImages=[];this.ensureConnectionUUID=null;this.isWebsocketReadyState=()=>this._ws?.readyState===1;this.isInvalidAPIKey=()=>this._connectionError?.error?.code==="invalidApiKey";this.send=t=>{this._ws.send(JSON.stringify([t]))};this.uploadImage=async t=>{try{return await x(async()=>{let e=R();if(typeof t=="string"&&xe(t))return{imageURL:t,imageUUID:t,taskUUID:e,taskType:"imageUpload"};let n=typeof t=="string"?t:await De(t);return{imageURL:n,imageUUID:n,taskUUID:e,taskType:"imageUpload"}})}catch(e){throw e}};this.controlNetPreProcess=async({inputImage:t,preProcessorType:e,height:n,width:s,outputType:a,outputFormat:c,highThresholdCanny:u,lowThresholdCanny:l,includeHandsAndFaceOpenPose:p,includeCost:d,outputQuality:g,customTaskUUID:o,retry:m,includeGenerationTime:i,includePayload:y})=>{let I=m||this._globalMaxRetries,f,k=Date.now();try{return await x(async()=>{await this.ensureConnection();let _=await this.uploadImage(t);if(!_?.imageUUID)return null;let U=o||R(),b={inputImage:_.imageUUID,taskType:"imageControlNetPreProcess",taskUUID:U,preProcessorType:e,...T({key:"height",value:n}),...T({key:"width",value:s}),...T({key:"outputType",value:a}),...T({key:"outputFormat",value:c}),...T({key:"includeCost",value:d}),...T({key:"highThresholdCanny",value:u}),...T({key:"lowThresholdCanny",value:l}),...T({key:"includeHandsAndFaceOpenPose",value:p}),...g?{outputQuality:g}:{}};this.send({...b}),f=this.globalListener({taskUUID:U});let M=await S(({resolve:q,reject:V})=>{let v=this.getSingleMessage({taskUUID:U});if(v){if(v?.error)return V(v),!0;if(v)return q(v),!0}},{debugKey:"unprocessed-image",timeoutDuration:this._timeoutDuration});return f.destroy(),this.insertAdditionalResponse({response:M,payload:y?b:void 0,startTime:i?k:void 0}),M},{maxRetries:I,callback:()=>{f?.destroy()}})}catch(_){throw _}};this.requestImageToText=async({inputImage:t,includeCost:e,customTaskUUID:n,retry:s,includePayload:a,includeGenerationTime:c})=>{let u=s||this._globalMaxRetries,l,p=Date.now();try{return await x(async()=>{await this.ensureConnection();let d=t?await this.uploadImage(t):null,g=n||R(),o={taskUUID:g,taskType:"imageCaption",inputImage:d?.imageUUID,...T({key:"includeCost",value:e})};this.send(o),l=this.globalListener({taskUUID:g});let m=await S(({resolve:i,reject:y})=>{let I=this.getSingleMessage({taskUUID:g});if(I){if(I?.error)return y(I),!0;if(I)return delete this._globalMessages[g],i(I),!0}},{debugKey:"remove-image-background",timeoutDuration:this._timeoutDuration});return l.destroy(),this.insertAdditionalResponse({response:m,payload:a?o:void 0,startTime:c?p:void 0}),m},{maxRetries:u,callback:()=>{l?.destroy()}})}catch(d){throw d}};this.removeImageBackground=async t=>this.baseSingleRequest({payload:{...t,taskType:"imageBackgroundRemoval"},debugKey:"remove-image-background"});this.videoInference=async t=>this.baseSingleRequest({payload:{...t,deliveryMethod:"async",taskType:"videoInference"},mockResponse:[{taskType:"videoInference",taskUUID:R(),status:"pending"}],debugKey:"video-inference"});this.getAsyncResults=async t=>{let e=t.taskUUID,n=Ae({count:2,taskUUID:e});return this.baseSingleRequest({payload:{...t,customTaskUUID:e,taskType:"asyncResults"},mockResponse:n,debugKey:"async-results"})};this.upscaleGan=async({inputImage:t,upscaleFactor:e,outputType:n,outputFormat:s,includeCost:a,outputQuality:c,customTaskUUID:u,retry:l,includeGenerationTime:p,includePayload:d})=>{let g=l||this._globalMaxRetries,o,m=Date.now();try{return await x(async()=>{await this.ensureConnection();let i;i=await this.uploadImage(t);let y=u||R(),I={taskUUID:y,inputImage:i?.imageUUID,taskType:"imageUpscale",upscaleFactor:e,...T({key:"includeCost",value:a}),...n?{outputType:n}:{},...c?{outputQuality:c}:{},...s?{outputFormat:s}:{}};this.send(I),o=this.globalListener({taskUUID:y});let f=await S(({resolve:k,reject:_})=>{let U=this.getSingleMessage({taskUUID:y});if(U){if(U?.error)return _(U),!0;if(U)return delete this._globalMessages[y],k(U),!0}},{debugKey:"upscale-gan",timeoutDuration:this._timeoutDuration});return o.destroy(),this.insertAdditionalResponse({response:f,payload:d?I:void 0,startTime:p?m:void 0}),f},{maxRetries:g,callback:()=>{o?.destroy()}})}catch(i){throw i}};this.enhancePrompt=async({prompt:t,promptMaxLength:e=380,promptVersions:n=1,includeCost:s,customTaskUUID:a,retry:c,includeGenerationTime:u,includePayload:l})=>{let p=c||this._globalMaxRetries,d,g=Date.now();try{return await x(async()=>{await this.ensureConnection();let o=a||R(),m={prompt:t,taskUUID:o,promptMaxLength:e,promptVersions:n,...T({key:"includeCost",value:s}),taskType:"promptEnhance"};this.send(m),d=this.globalListener({taskUUID:o});let i=await S(({resolve:y,reject:I})=>{let f=this._globalMessages[o];if(f?.error)return I(f),!0;if(f?.length>=n)return delete this._globalMessages[o],y(f),!0},{debugKey:"enhance-prompt",timeoutDuration:this._timeoutDuration});return d.destroy(),this.insertAdditionalResponse({response:i,payload:l?m:void 0,startTime:u?g:void 0}),i},{maxRetries:p,callback:()=>{d?.destroy()}})}catch(o){throw o}};this.modelUpload=async t=>{let{onUploadStream:e,retry:n,customTaskUUID:s,...a}=t,c=n||this._globalMaxRetries,u;try{return await x(async()=>{await this.ensureConnection();let l=s||R();this.send({...a,taskUUID:l,taskType:"modelUpload"});let p,d;return u=this.listenToUpload({taskUUID:l,onUploadStream:(o,m)=>{e?.(o,m),o?.status==="ready"?p=o:m&&(d=m)}}),await S(({resolve:o,reject:m})=>{if(p)return o(p),!0;if(d)return m(d),!1},{shouldThrowError:!1,timeoutDuration:60*60*1e3})},{maxRetries:c,callback:()=>{u?.destroy()}})}catch(l){throw l}};this.photoMaker=async(t,e)=>{let{onPartialImages:n,retry:s,customTaskUUID:a,numberResults:c,includeGenerationTime:u,includePayload:l,...p}=t,d=s||this._globalMaxRetries,g,o=[],m=0,i=Date.now();try{return await x(async()=>{await this.ensureConnection(),m++;let y=this._globalImages.filter(U=>o.includes(U.taskUUID)),I=a||R();o.push(I);let f=c-y.length,k={...p,...p.seed?{seed:p.seed}:{seed:ne()},...e??{},taskUUID:I,taskType:"photoMaker",numberResults:c};this.send({...k,numberResults:f}),g=this.listenToImages({onPartialImages:n,taskUUID:I,groupKey:"REQUEST_IMAGES",requestPayload:l?k:void 0,startTime:u?i:void 0});let _=await this.getSimilarImages({taskUUID:o,numberResults:c,lis:g});return g.destroy(),_},{maxRetries:d,callback:()=>{g?.destroy()}})}catch(y){if(y.taskUUID)throw y;if(m>=d)return this.handleIncompleteImages({taskUUIDs:o,error:y})}};this.modelSearch=async t=>this.baseSingleRequest({payload:{...t,taskType:"modelSearch"},debugKey:"model-search"});this.imageMasking=async t=>this.baseSingleRequest({payload:{...t,taskType:"imageMasking"},debugKey:"image-masking"});this.imageUpload=async t=>this.baseSingleRequest({payload:{...t,taskType:"imageUpload"},debugKey:"image-upload"});this.baseSingleRequest=async({payload:t,debugKey:e,mockResponse:n})=>{let{retry:s,customTaskUUID:a,includePayload:c,includeGenerationTime:u,...l}=t,p=s||this._globalMaxRetries,d,g=Date.now();try{return await x(async()=>{await this.ensureConnection();let o=a||R(),m={...l,taskUUID:o};n?setTimeout(()=>{this._globalMessages[o]=n},1e3):this.send(m),d=this.globalListener({taskUUID:o});let i=await S(({resolve:y,reject:I})=>{let f=this.getSingleMessage({taskUUID:o});if(f){if(f?.error)return I(f),!0;if(f)return delete this._globalMessages[o],y(f),!0}},{debugKey:e,timeoutDuration:this._timeoutDuration});return this.insertAdditionalResponse({response:i,payload:c?m:void 0,startTime:u?g:void 0}),d.destroy(),i},{maxRetries:p,callback:()=>{d?.destroy()}})}catch(o){throw o}};this.getSingleMessage=({taskUUID:t})=>{let e=this._globalMessages[t]?.[0],n=this._globalMessages[t];return!e&&!n?null:n?.error?n:e};this.insertAdditionalResponse=({response:t,payload:e,startTime:n})=>{if(!e&&!n)return;let s=t;s.additionalResponse={},e&&(t.additionalResponse.payload=e),n&&(t.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=t,this._url=e,this._sdkType="CLIENT",this._shouldReconnect=n,this._globalMaxRetries=s,this._timeoutDuration=a}static async initialize(t){try{let e=new this(t);return await e.ensureConnection(),e}catch(e){throw e}}addListener({lis:t,groupKey:e,taskUUID:n}){let s=u=>{let l=Array.isArray(u?.data)?u.data:[u.data],p=u?.[0]?.errors?u?.[0]?.errors:Array.isArray(u?.errors)?u.errors:[u.errors],d=l.filter(o=>(o?.taskUUID||o?.taskType)===n);if(p.filter(o=>(o?.taskUUID||o?.taskType)===n).length){t({error:{...p[0]??{}}});return}if(d.length){t({[n]:l});return}},a={key:n||R(),listener:s,groupKey:e};return this._listeners.push(a),{destroy:()=>{this._listeners=we(this._listeners,a)}}}connect(){this._ws.onopen=t=>{this._connectionSessionUUID?this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.send({apiKey:this._apiKey,taskType:"authentication"}),this.addListener({taskUUID:"authentication",lis:e=>{if(e?.error){this._connectionError=e;return}this._connectionSessionUUID=e?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0}})},this._ws.onmessage=t=>{let e=JSON.parse(t.data);for(let n of this._listeners)if(n?.listener?.(e))return},this._ws.onclose=t=>{this.isInvalidAPIKey()}}destroy(t){ke(this._listeners,t)}listenToImages({onPartialImages:t,taskUUID:e,groupKey:n,requestPayload:s,startTime:a}){return this.addListener({taskUUID:e,lis:c=>{let u=c?.[e]?.filter(l=>l.taskUUID===e);c.error?(t?.(u,c?.error&&c),this._globalError=c):(u=u.map(l=>(this.insertAdditionalResponse({response:l,payload:s||void 0,startTime:a||void 0}),{...l})),t?.(u,c?.error&&c),this._sdkType==="CLIENT"?this._globalImages=[...this._globalImages,...(c?.[e]??[]).map(l=>(this.insertAdditionalResponse({response:l,payload:s||void 0,startTime:a||void 0}),{...l}))]:this._globalImages=[...this._globalImages,...u])},groupKey:n})}listenToUpload({onUploadStream:t,taskUUID:e}){return this.addListener({taskUUID:e,lis:n=>{let s=n?.error,a=n?.[e]?.[0],c=a?.taskUUID===e?a:null;(c||s)&&t?.(c||void 0,s)}})}globalListener({taskUUID:t}){return this.addListener({taskUUID:t,lis:e=>{if(e.error){this._globalMessages[t]=e;return}let n=ve({key:t,data:e,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:t,outputFormat:e,uploadEndpoint:n,checkNSFW:s,positivePrompt:a,negativePrompt:c,seedImage:u,maskImage:l,strength:p,height:d,width:g,model:o,steps:m,scheduler:i,seed:y,CFGScale:I,clipSkip:f,usePromptWeighting:k,promptWeighting:_,numberResults:U=1,onPartialImages:b,includeCost:M,customTaskUUID:q,retry:V,refiner:v,maskMargin:Pe,outputQuality:h,controlNet:H,lora:re,embeddings:ae,ipAdapters:oe,outpaint:ie,acceleratorOptions:le,advancedFeatures:ce,referenceImages:ue,includeGenerationTime:Fe,includePayload:We},Ge){let C,de,L=[],pe=0,ge=V||this._globalMaxRetries;try{await this.ensureConnection();let w=null,j=null,Q=[];if(u){let D=await this.uploadImage(u);if(!D)return[];w=D.imageUUID}if(l){let D=await this.uploadImage(l);if(!D)return[];j=D.imageUUID}if(H?.length)for(let D=0;D<H.length;D++){let E=H[D],{endStep:Y,startStep:K,weight:J,guideImage:P,controlMode:qe,startStepPercentage:Ve,endStepPercentage:He,model:je}=E,Qe=P?await this.uploadImage(P):null;Q.push({guideImage:Qe?.imageUUID,model:je,endStep:Y,startStep:K,weight:J,...T({key:"startStepPercentage",value:Ve}),...T({key:"endStepPercentage",value:He}),controlMode:qe||"controlnet"})}de={taskType:"imageInference",model:o,positivePrompt:a,...c?{negativePrompt:c}:{},...d?{height:d}:{},...g?{width:g}:{},numberResults:U,...t?{outputType:t}:{},...e?{outputFormat:e}:{},...n?{uploadEndpoint:n}:{},...T({key:"checkNSFW",value:s}),...T({key:"strength",value:p}),...T({key:"CFGScale",value:I}),...T({key:"clipSkip",value:f}),...T({key:"maskMargin",value:Pe}),...T({key:"usePromptWeighting",value:k}),...T({key:"steps",value:m}),..._?{promptWeighting:_}:{},...y?{seed:y}:{seed:ne()},...i?{scheduler:i}:{},...v?{refiner:v}:{},...ie?{outpaint:ie}:{},...T({key:"includeCost",value:M}),...w?{seedImage:w}:{},...j?{maskImage:j}:{},...h?{outputQuality:h}:{},...Q.length?{controlNet:Q}:{},...re?.length?{lora:re}:{},...ae?.length?{embeddings:ae}:{},...oe?.length?{ipAdapters:oe}:{},...le?{acceleratorOptions:le}:{},...ce?{advancedFeatures:ce}:{},...ue?.length?{referenceImages:ue}:{},...Ge??{}};let Be=Date.now();return await x(async()=>{pe++,C?.destroy();let D=this._globalImages.filter(P=>L.includes(P.taskUUID)),E=q||R();L.push(E);let Y=U-D.length,K={...de,taskUUID:E,numberResults:Y};this.send(K),C=this.listenToImages({onPartialImages:b,taskUUID:E,groupKey:"REQUEST_IMAGES",requestPayload:We?K:void 0,startTime:Fe?Be:void 0});let J=await this.getSimilarImages({taskUUID:L,numberResults:U,lis:C});return C.destroy(),J},{maxRetries:ge,callback:()=>{C?.destroy()}})}catch(w){if(pe>=ge)return this.handleIncompleteImages({taskUUIDs:L,error:w});throw w}}async ensureConnection(){if(this.connected()||this._url===te.TEST)return;let e=2e3,n=200;try{if(this.isInvalidAPIKey())throw this._connectionError;return new Promise((s,a)=>{let c=0,u=30,l=R(),p,d,g=()=>{this.ensureConnectionUUID=null,clearInterval(p),clearInterval(d)};this._sdkType==="SERVER"&&(p=setInterval(async()=>{try{let o=this.connected(),m=!1;(!this.ensureConnectionUUID||l===this.ensureConnectionUUID)&&(this.ensureConnectionUUID||(this.ensureConnectionUUID=l),m=!0);let i=c%10===0&&m;o?(g(),s(!0)):c>=u?(g(),a(new Error("Retry timed out"))):(i&&this.connect(),c++)}catch(o){g(),a(o)}},e)),d=setInterval(async()=>{if(this.connected()){g(),s(!0);return}if(this.isInvalidAPIKey()){g(),a(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:t,numberResults:e,shouldThrowError:n,lis:s}){return await S(({resolve:a,reject:c,intervalId:u})=>{let l=Array.isArray(t)?t:[t],p=this._globalImages.filter(d=>l.includes(d.taskUUID));if(this._globalError){let d=this._globalError;return this._globalError=void 0,clearInterval(u),c?.(d),!0}else if(p.length>=e)return clearInterval(u),this._globalImages=this._globalImages.filter(d=>!l.includes(d.taskUUID)),a([...p].slice(0,e)),!0},{debugKey:"getting images",shouldThrowError:n,timeoutDuration:this._timeoutDuration})}handleIncompleteImages({taskUUIDs:t,error:e}){let n=this._globalImages.filter(s=>t.includes(s.taskUUID));if(n.length>1)return this._globalImages=this._globalImages.filter(s=>!t.includes(s.taskUUID)),n;throw e}};var Le=ye(Me(),1),N=class extends A{constructor(t){let{shouldReconnect:e,...n}=t;super(n),this._ws=new Le.default(this._url),this.connect()}};var Ke=ye(require("ws"),1);var O=class extends A{constructor(e){super(e);this._instantiated=!1;this._listeners=[];this._reconnectingIntervalId=null;this.send=e=>{this._ws.send(JSON.stringify([e]))};this.resetConnection=()=>{this._ws&&(this._listeners.forEach(e=>{e?.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:e=>{if(e?.error){this._connectionError=e;return}this._connectionSessionUUID=e?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0}})}),this._ws.on("message",(e,n)=>{let s=n?e:e?.toString();if(!s)return;let a=JSON.parse(s);this._listeners.forEach(c=>{c.listener(a)})}))}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=O:se=N;0&&(module.exports={EControlMode,EModelArchitecture,EModelConditioning,EModelFormat,EModelType,EOpenPosePreProcessor,EPhotoMakerEnum,EPreProcessor,EPreProcessorGroup,ETaskType,Environment,Runware,RunwareClient,RunwareServer,SdkType});
1
+ "use strict";var je=Object.create;var F=Object.defineProperty;var Qe=Object.getOwnPropertyDescriptor;var Je=Object.getOwnPropertyNames;var Ye=Object.getPrototypeOf,ze=Object.prototype.hasOwnProperty;var Ze=(o,e)=>()=>(e||o((e={exports:{}}).exports,e),e.exports),$e=(o,e)=>{for(var t in e)F(o,t,{get:e[t],enumerable:!0})},me=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Je(e))!ze.call(o,s)&&s!==t&&F(o,s,{get:()=>e[s],enumerable:!(n=Qe(e,s))||n.enumerable});return o};var ye=(o,e,t)=>(t=o!=null?je(Ye(o)):{},me(e||!o||!o.__esModule?F(t,"default",{value:o,enumerable:!0}):t,o)),Xe=o=>me(F({},"__esModule",{value:!0}),o);var Oe=Ze((rn,Ee)=>{"use strict";var Ae=o=>o&&o.CLOSING===2,nt=()=>typeof WebSocket<"u"&&Ae(WebSocket),st=()=>({constructor:nt()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),rt=(o,e,t)=>{Object.defineProperty(e,t,{get:()=>o[t],set:n=>{o[t]=n},enumerable:!0,configurable:!0})},we=o=>o.minReconnectionDelay+Math.random()*o.minReconnectionDelay,at=(o,e)=>{let t=e*o.reconnectionDelayGrowFactor;return t>o.maxReconnectionDelay?o.maxReconnectionDelay:t},ot=["onopen","onclose","onmessage","onerror"],it=(o,e,t)=>{Object.keys(t).forEach(n=>{t[n].forEach(([s,i])=>{o.addEventListener(n,s,i)})}),e&&ot.forEach(n=>{o[n]=e[n]})},Ce=function(o,e,t={}){let n,s,i=0,c=0,u=!0,l={};if(!(this instanceof Ce))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let p=st();if(Object.keys(p).filter(a=>t.hasOwnProperty(a)).forEach(a=>p[a]=t[a]),!Ae(p.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");let d=p.debug?(...a)=>console.log("RWS:",...a):()=>{},g=(a,y)=>setTimeout(()=>{let I=new Error(y);I.code=a,Array.isArray(l.error)&&l.error.forEach(([f])=>f(I)),n.onerror&&n.onerror(I)},0),r=()=>{if(d("close"),c++,d("retries count:",c),c>p.maxRetries){g("EHOSTDOWN","Too many failed connection attempts");return}i?i=at(p,i):i=we(p),d("reconnectDelay:",i),u&&setTimeout(m,i)},m=()=>{d("connect");let a=n;n=new p.constructor(o,e),s=setTimeout(()=>{d("timeout"),n.close(),g("ETIMEDOUT","Connection timeout")},p.connectionTimeout),d("bypass properties");for(let y in n)["addEventListener","removeEventListener","close","send"].indexOf(y)<0&&rt(n,this,y);n.addEventListener("open",()=>{clearTimeout(s),d("open"),i=we(p),d("reconnectDelay:",i),c=0}),n.addEventListener("close",r),it(n,a,l)};d("init"),m(),this.close=(a=1e3,y="",{keepClosed:I=!1,fastClose:f=!0,delay:k=0}={})=>{if(k&&(i=k),u=!I,n.close(a,y),f){let _={code:a,reason:y,wasClean:!0};r(),Array.isArray(l.close)&&l.close.forEach(([U,b])=>{U(_),n.removeEventListener("close",U,b)}),n.onclose&&(n.onclose(_),n.onclose=null)}},this.send=a=>{n.send(a)},this.addEventListener=(a,y,I)=>{Array.isArray(l[a])?l[a].some(([f])=>f===y)||l[a].push([y,I]):l[a]=[[y,I]],n.addEventListener(a,y,I)},this.removeEventListener=(a,y,I)=>{Array.isArray(l[a])&&(l[a]=l[a].filter(([f])=>f!==y)),n.removeEventListener(a,y,I)}};Ee.exports=Ce});var lt={};$e(lt,{EControlMode:()=>Z,EModelArchitecture:()=>fe,EModelConditioning:()=>Te,EModelFormat:()=>he,EModelType:()=>be,EOpenPosePreProcessor:()=>Ie,EPhotoMakerEnum:()=>Ue,EPreProcessor:()=>X,EPreProcessorGroup:()=>$,ETaskType:()=>G,Environment:()=>z,Runware:()=>se,RunwareClient:()=>O,RunwareServer:()=>N,SdkType:()=>W});module.exports=Xe(lt);var z=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))(z||{}),W=(t=>(t.CLIENT="CLIENT",t.SERVER="SERVER",t))(W||{}),G=(a=>(a.IMAGE_INFERENCE="imageInference",a.IMAGE_UPLOAD="imageUpload",a.IMAGE_UPSCALE="imageUpscale",a.IMAGE_BACKGROUND_REMOVAL="imageBackgroundRemoval",a.VIDEO_INFERENCE="videoInference",a.GET_RESPONSE="getResponse",a.PHOTO_MAKER="photoMaker",a.IMAGE_CAPTION="imageCaption",a.IMAGE_CONTROL_NET_PRE_PROCESS="imageControlNetPreProcess",a.IMAGE_MASKING="imageMasking",a.PROMPT_ENHANCE="promptEnhance",a.AUTHENTICATION="authentication",a.MODEL_UPLOAD="modelUpload",a.MODEL_SEARCH="modelSearch",a))(G||{}),Z=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(Z||{}),$=(r=>(r.canny="canny",r.depth="depth",r.mlsd="mlsd",r.normalbae="normalbae",r.openpose="openpose",r.tile="tile",r.seg="seg",r.lineart="lineart",r.lineart_anime="lineart_anime",r.shuffle="shuffle",r.scribble="scribble",r.softedge="softedge",r))($||{}),X=(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))(X||{}),Ie=(i=>(i.openpose="openpose",i.openpose_face="openpose_face",i.openpose_faceonly="openpose_faceonly",i.openpose_full="openpose_full",i.openpose_hand="openpose_hand",i))(Ie||{}),he=(t=>(t.safetensors="safetensors",t.pickletensor="pickletensor",t))(he||{}),fe=(m=>(m.flux1d="flux1d",m.flux1s="flux1s",m.pony="pony",m.sdhyper="sdhyper",m.sd1x="sd1x",m.sd1xlcm="sd1xlcm",m.sd3="sd3",m.sdxl="sdxl",m.sdxllcm="sdxllcm",m.sdxldistilled="sdxldistilled",m.sdxlhyper="sdxlhyper",m.sdxllightning="sdxllightning",m.sdxlturbo="sdxlturbo",m))(fe||{}),be=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))(be||{}),Te=(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))(Te||{}),Ue=(g=>(g.NoStyle="No style",g.Cinematic="Cinematic",g.DisneyCharacter="Disney Character",g.DigitalArt="Digital Art",g.Photographic="Photographic",g.FantasyArt="Fantasy art",g.Neonpunk="Neonpunk",g.Enhance="Enhance",g.ComicBook="Comic book",g.Lowpoly="Lowpoly",g.LineArt="Line art",g))(Ue||{});var B=require("uuid"),ee=6e4,_e=1e3,et=100,te={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},Re=(o,e)=>{if(o==null)return;let t=o.indexOf(e);t!==-1&&o.splice(t,1)},S=(o,{debugKey:e="debugKey",timeoutDuration:t=ee,shouldThrowError:n=!0})=>(t=t<_e?_e:t,new Promise((s,i)=>{let c=setTimeout(()=>{u&&(clearInterval(u),n&&i(`Response could not be received from server for ${e}`)),clearTimeout(c)},t),u=setInterval(async()=>{o({resolve:s,reject:i,intervalId:u})&&(clearInterval(u),clearTimeout(c))},et)})),ke=o=>new Promise(e=>{let t=new FileReader;t.readAsDataURL(o),t.onload=function(){e(t.result)}}),R=()=>(0,B.v4)(),De=o=>(0,B.validate)(o);var xe=({key:o,data:e,useZero:t=!0,shouldReturnString:n=!1})=>o.split(/\.|\[/).map(c=>c.replace(/\]$/,"")).reduce((c,u)=>{let l=t?0:void 0,p=c?.[u];if(!p)return l;if(Array.isArray(p)&&/^\d+$/.test(u)){let d=parseInt(u,10);return d>=0&&d<p.length?c[u]=p[d]:c[u]??l}else return c[u]??l},e||{})??{},ve=(o,e=1e3)=>new Promise(t=>setTimeout(t,o*e));var Se=(o,e)=>o.filter(t=>t.key!==e.key);var T=({key:o,value:e})=>e||e===0||e===!1?{[o]:e}:{},tt=(o,e)=>Math.floor(Math.random()*(e-o+1))+o,ne=()=>tt(1,Number.MAX_SAFE_INTEGER);var x=async(o,e={})=>{let{delayInSeconds:t=1,callback:n}=e,s=e.maxRetries??1;for(;s;)try{return await o()}catch(i){if(n?.(),s--,s>0)await ve(t),await x(o,{...e,maxRetries:s});else throw i}};var A=class{constructor({apiKey:e,url:t=te.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:s=2,timeoutDuration:i=ee}){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=R();if(typeof e=="string"&&De(e))return{imageURL:e,imageUUID:e,taskUUID:t,taskType:"imageUpload"};let n=typeof e=="string"?e:await ke(e);return{imageURL:n,imageUUID:n,taskUUID:t,taskType:"imageUpload"}})}catch(t){throw t}};this.controlNetPreProcess=async({inputImage:e,preProcessorType:t,height:n,width:s,outputType:i,outputFormat:c,highThresholdCanny:u,lowThresholdCanny:l,includeHandsAndFaceOpenPose:p,includeCost:d,outputQuality:g,customTaskUUID:r,retry:m,includeGenerationTime:a,includePayload:y})=>{let I=m||this._globalMaxRetries,f,k=Date.now();try{return await x(async()=>{await this.ensureConnection();let _=await this.uploadImage(e);if(!_?.imageUUID)return null;let U=r||R(),b={inputImage:_.imageUUID,taskType:"imageControlNetPreProcess",taskUUID:U,preProcessorType:t,...T({key:"height",value:n}),...T({key:"width",value:s}),...T({key:"outputType",value:i}),...T({key:"outputFormat",value:c}),...T({key:"includeCost",value:d}),...T({key:"highThresholdCanny",value:u}),...T({key:"lowThresholdCanny",value:l}),...T({key:"includeHandsAndFaceOpenPose",value:p}),...g?{outputQuality:g}:{}};this.send({...b}),f=this.globalListener({taskUUID:U});let M=await S(({resolve:q,reject:V})=>{let v=this.getSingleMessage({taskUUID:U});if(v){if(v?.error)return V(v),!0;if(v)return q(v),!0}},{debugKey:"unprocessed-image",timeoutDuration:this._timeoutDuration});return f.destroy(),this.insertAdditionalResponse({response:M,payload:y?b:void 0,startTime:a?k:void 0}),M},{maxRetries:I,callback:()=>{f?.destroy()}})}catch(_){throw _}};this.requestImageToText=async({inputImage:e,includeCost:t,customTaskUUID:n,retry:s,includePayload:i,includeGenerationTime:c})=>{let u=s||this._globalMaxRetries,l,p=Date.now();try{return await x(async()=>{await this.ensureConnection();let d=e?await this.uploadImage(e):null,g=n||R(),r={taskUUID:g,taskType:"imageCaption",inputImage:d?.imageUUID,...T({key:"includeCost",value:t})};this.send(r),l=this.globalListener({taskUUID:g});let m=await S(({resolve:a,reject:y})=>{let I=this.getSingleMessage({taskUUID:g});if(I){if(I?.error)return y(I),!0;if(I)return delete this._globalMessages[g],a(I),!0}},{debugKey:"remove-image-background",timeoutDuration:this._timeoutDuration});return l.destroy(),this.insertAdditionalResponse({response:m,payload:i?r:void 0,startTime:c?p:void 0}),m},{maxRetries:u,callback:()=>{l?.destroy()}})}catch(d){throw d}};this.removeImageBackground=async e=>this.baseSingleRequest({payload:{...e,taskType:"imageBackgroundRemoval"},debugKey:"remove-image-background"});this.videoInference=async e=>this.baseSingleRequest({payload:{...e,deliveryMethod:"async",taskType:"videoInference"},debugKey:"video-inference"});this.getResponse=async e=>{let t=e.taskUUID;return this.baseSingleRequest({payload:{...e,customTaskUUID:t,taskType:"getResponse"},debugKey:"async-results"})};this.upscaleGan=async({inputImage:e,upscaleFactor:t,outputType:n,outputFormat:s,includeCost:i,outputQuality:c,customTaskUUID:u,retry:l,includeGenerationTime:p,includePayload:d})=>{let g=l||this._globalMaxRetries,r,m=Date.now();try{return await x(async()=>{await this.ensureConnection();let a;a=await this.uploadImage(e);let y=u||R(),I={taskUUID:y,inputImage:a?.imageUUID,taskType:"imageUpscale",upscaleFactor:t,...T({key:"includeCost",value:i}),...n?{outputType:n}:{},...c?{outputQuality:c}:{},...s?{outputFormat:s}:{}};this.send(I),r=this.globalListener({taskUUID:y});let f=await S(({resolve:k,reject:_})=>{let U=this.getSingleMessage({taskUUID:y});if(U){if(U?.error)return _(U),!0;if(U)return delete this._globalMessages[y],k(U),!0}},{debugKey:"upscale-gan",timeoutDuration:this._timeoutDuration});return r.destroy(),this.insertAdditionalResponse({response:f,payload:d?I:void 0,startTime:p?m:void 0}),f},{maxRetries:g,callback:()=>{r?.destroy()}})}catch(a){throw a}};this.enhancePrompt=async({prompt:e,promptMaxLength:t=380,promptVersions:n=1,includeCost:s,customTaskUUID:i,retry:c,includeGenerationTime:u,includePayload:l})=>{let p=c||this._globalMaxRetries,d,g=Date.now();try{return await x(async()=>{await this.ensureConnection();let r=i||R(),m={prompt:e,taskUUID:r,promptMaxLength:t,promptVersions:n,...T({key:"includeCost",value:s}),taskType:"promptEnhance"};this.send(m),d=this.globalListener({taskUUID:r});let a=await S(({resolve:y,reject:I})=>{let f=this._globalMessages[r];if(f?.error)return I(f),!0;if(f?.length>=n)return delete this._globalMessages[r],y(f),!0},{debugKey:"enhance-prompt",timeoutDuration:this._timeoutDuration});return d.destroy(),this.insertAdditionalResponse({response:a,payload:l?m:void 0,startTime:u?g:void 0}),a},{maxRetries:p,callback:()=>{d?.destroy()}})}catch(r){throw r}};this.modelUpload=async e=>{let{onUploadStream:t,retry:n,customTaskUUID:s,...i}=e,c=n||this._globalMaxRetries,u;try{return await x(async()=>{await this.ensureConnection();let l=s||R();this.send({...i,taskUUID:l,taskType:"modelUpload"});let p,d;return u=this.listenToUpload({taskUUID:l,onUploadStream:(r,m)=>{t?.(r,m),r?.status==="ready"?p=r:m&&(d=m)}}),await S(({resolve:r,reject:m})=>{if(p)return r(p),!0;if(d)return m(d),!1},{shouldThrowError:!1,timeoutDuration:60*60*1e3})},{maxRetries:c,callback:()=>{u?.destroy()}})}catch(l){throw l}};this.photoMaker=async(e,t)=>{let{onPartialImages:n,retry:s,customTaskUUID:i,numberResults:c,includeGenerationTime:u,includePayload:l,...p}=e,d=s||this._globalMaxRetries,g,r=[],m=0,a=Date.now();try{return await x(async()=>{await this.ensureConnection(),m++;let y=this._globalImages.filter(U=>r.includes(U.taskUUID)),I=i||R();r.push(I);let f=c-y.length,k={...p,...p.seed?{seed:p.seed}:{seed:ne()},...t??{},taskUUID:I,taskType:"photoMaker",numberResults:c};this.send({...k,numberResults:f}),g=this.listenToImages({onPartialImages:n,taskUUID:I,groupKey:"REQUEST_IMAGES",requestPayload:l?k:void 0,startTime:u?a:void 0});let _=await this.getSimilarImages({taskUUID:r,numberResults:c,lis:g});return g.destroy(),_},{maxRetries:d,callback:()=>{g?.destroy()}})}catch(y){if(y.taskUUID)throw y;if(m>=d)return this.handleIncompleteImages({taskUUIDs:r,error:y})}};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,mockResponse:n})=>{let{retry:s,customTaskUUID:i,includePayload:c,includeGenerationTime:u,...l}=e,p=s||this._globalMaxRetries,d,g=Date.now();try{return await x(async()=>{await this.ensureConnection();let r=i||R(),m={...l,taskUUID:r};n?setTimeout(()=>{this._globalMessages[r]=n},1e3):this.send(m),d=this.globalListener({taskUUID:r});let a=await S(({resolve:y,reject:I})=>{let f=this.getSingleMessage({taskUUID:r});if(f){if(f?.error)return I(f),!0;if(f)return delete this._globalMessages[r],y(f),!0}},{debugKey:t,timeoutDuration:this._timeoutDuration});return this.insertAdditionalResponse({response:a,payload:c?m:void 0,startTime:u?g:void 0}),d.destroy(),a},{maxRetries:p,callback:()=>{d?.destroy()}})}catch(r){throw r}};this.getSingleMessage=({taskUUID:e})=>{let t=this._globalMessages[e]?.[0],n=this._globalMessages[e];return!t&&!n?null:n?.error?n:t};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=i}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 l=Array.isArray(u?.data)?u.data:[u.data],p=u?.[0]?.errors?u?.[0]?.errors:Array.isArray(u?.errors)?u.errors:[u.errors],d=l.filter(r=>(r?.taskUUID||r?.taskType)===n);if(p.filter(r=>(r?.taskUUID||r?.taskType)===n).length){e({error:{...p[0]??{}}});return}if(d.length){e({[n]:l});return}},i={key:n||R(),listener:s,groupKey:t};return this._listeners.push(i),{destroy:()=>{this._listeners=Se(this._listeners,i)}}}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){Re(this._listeners,e)}listenToImages({onPartialImages:e,taskUUID:t,groupKey:n,requestPayload:s,startTime:i}){return this.addListener({taskUUID:t,lis:c=>{let u=c?.[t]?.filter(l=>l.taskUUID===t);c.error?(e?.(u,c?.error&&c),this._globalError=c):(u=u.map(l=>(this.insertAdditionalResponse({response:l,payload:s||void 0,startTime:i||void 0}),{...l})),e?.(u,c?.error&&c),this._sdkType==="CLIENT"?this._globalImages=[...this._globalImages,...(c?.[t]??[]).map(l=>(this.insertAdditionalResponse({response:l,payload:s||void 0,startTime:i||void 0}),{...l}))]:this._globalImages=[...this._globalImages,...u])},groupKey:n})}listenToUpload({onUploadStream:e,taskUUID:t}){return this.addListener({taskUUID:t,lis:n=>{let s=n?.error,i=n?.[t]?.[0],c=i?.taskUUID===t?i:null;(c||s)&&e?.(c||void 0,s)}})}globalListener({taskUUID:e}){return this.addListener({taskUUID:e,lis:t=>{if(t.error){this._globalMessages[e]=t;return}let n=xe({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:i,negativePrompt:c,seedImage:u,maskImage:l,strength:p,height:d,width:g,model:r,steps:m,scheduler:a,seed:y,CFGScale:I,clipSkip:f,usePromptWeighting:k,promptWeighting:_,numberResults:U=1,onPartialImages:b,includeCost:M,customTaskUUID:q,retry:V,refiner:v,maskMargin:Le,outputQuality:h,controlNet:H,lora:re,embeddings:ae,ipAdapters:oe,outpaint:ie,acceleratorOptions:le,advancedFeatures:ce,referenceImages:ue,includeGenerationTime:Ke,includePayload:Pe},Fe){let C,de,L=[],pe=0,ge=V||this._globalMaxRetries;try{await this.ensureConnection();let w=null,j=null,Q=[];if(u){let D=await this.uploadImage(u);if(!D)return[];w=D.imageUUID}if(l){let D=await this.uploadImage(l);if(!D)return[];j=D.imageUUID}if(H?.length)for(let D=0;D<H.length;D++){let E=H[D],{endStep:J,startStep:K,weight:Y,guideImage:P,controlMode:Ge,startStepPercentage:Be,endStepPercentage:qe,model:Ve}=E,He=P?await this.uploadImage(P):null;Q.push({guideImage:He?.imageUUID,model:Ve,endStep:J,startStep:K,weight:Y,...T({key:"startStepPercentage",value:Be}),...T({key:"endStepPercentage",value:qe}),controlMode:Ge||"controlnet"})}de={taskType:"imageInference",model:r,positivePrompt:i,...c?{negativePrompt:c}:{},...d?{height:d}:{},...g?{width:g}:{},numberResults:U,...e?{outputType:e}:{},...t?{outputFormat:t}:{},...n?{uploadEndpoint:n}:{},...T({key:"checkNSFW",value:s}),...T({key:"strength",value:p}),...T({key:"CFGScale",value:I}),...T({key:"clipSkip",value:f}),...T({key:"maskMargin",value:Le}),...T({key:"usePromptWeighting",value:k}),...T({key:"steps",value:m}),..._?{promptWeighting:_}:{},...y?{seed:y}:{seed:ne()},...a?{scheduler:a}:{},...v?{refiner:v}:{},...ie?{outpaint:ie}:{},...T({key:"includeCost",value:M}),...w?{seedImage:w}:{},...j?{maskImage:j}:{},...h?{outputQuality:h}:{},...Q.length?{controlNet:Q}:{},...re?.length?{lora:re}:{},...ae?.length?{embeddings:ae}:{},...oe?.length?{ipAdapters:oe}:{},...le?{acceleratorOptions:le}:{},...ce?{advancedFeatures:ce}:{},...ue?.length?{referenceImages:ue}:{},...Fe??{}};let We=Date.now();return await x(async()=>{pe++,C?.destroy();let D=this._globalImages.filter(P=>L.includes(P.taskUUID)),E=q||R();L.push(E);let J=U-D.length,K={...de,taskUUID:E,numberResults:J};this.send(K),C=this.listenToImages({onPartialImages:b,taskUUID:E,groupKey:"REQUEST_IMAGES",requestPayload:Pe?K:void 0,startTime:Ke?We:void 0});let Y=await this.getSimilarImages({taskUUID:L,numberResults:U,lis:C});return C.destroy(),Y},{maxRetries:ge,callback:()=>{C?.destroy()}})}catch(w){if(pe>=ge)return this.handleIncompleteImages({taskUUIDs:L,error:w});throw w}}async ensureConnection(){if(this.connected()||this._url===te.TEST)return;let t=2e3,n=200;try{if(this.isInvalidAPIKey())throw this._connectionError;return new Promise((s,i)=>{let c=0,u=30,l=R(),p,d,g=()=>{this.ensureConnectionUUID=null,clearInterval(p),clearInterval(d)};this._sdkType==="SERVER"&&(p=setInterval(async()=>{try{let r=this.connected(),m=!1;(!this.ensureConnectionUUID||l===this.ensureConnectionUUID)&&(this.ensureConnectionUUID||(this.ensureConnectionUUID=l),m=!0);let a=c%10===0&&m;r?(g(),s(!0)):c>=u?(g(),i(new Error("Retry timed out"))):(a&&this.connect(),c++)}catch(r){g(),i(r)}},t)),d=setInterval(async()=>{if(this.connected()){g(),s(!0);return}if(this.isInvalidAPIKey()){g(),i(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:i,reject:c,intervalId:u})=>{let l=Array.isArray(e)?e:[e],p=this._globalImages.filter(d=>l.includes(d.taskUUID));if(this._globalError){let d=this._globalError;return this._globalError=void 0,clearInterval(u),c?.(d),!0}else if(p.length>=t)return clearInterval(u),this._globalImages=this._globalImages.filter(d=>!l.includes(d.taskUUID)),i([...p].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 Ne=ye(Oe(),1),O=class extends A{constructor(e){let{shouldReconnect:t,...n}=e;super(n),this._ws=new Ne.default(this._url),this.connect()}};var Me=ye(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 Me.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 i=JSON.parse(s);this._listeners.forEach(c=>{c.listener(i)})}))}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});
2
2
  //# sourceMappingURL=index.cjs.map