@runware/sdk-js 1.1.45-beta.4 → 1.1.45-beta.6
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 +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +5 -4
- package/dist/index.d.ts +5 -4
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var Ye=Object.create;var W=Object.defineProperty;var Ze=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var et=Object.getPrototypeOf,tt=Object.prototype.hasOwnProperty;var nt=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),st=(i,e)=>{for(var t in e)W(i,t,{get:e[t],enumerable:!0})},Ie=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Xe(e))!tt.call(i,s)&&s!==t&&W(i,s,{get:()=>e[s],enumerable:!(n=Ze(e,s))||n.enumerable});return i};var he=(i,e,t)=>(t=i!=null?Ye(et(i)):{},Ie(e||!i||!i.__esModule?W(t,"default",{value:i,enumerable:!0}):t,i)),rt=i=>Ie(W({},"__esModule",{value:!0}),i);var Pe=nt((dn,Le)=>{"use strict";var Me=i=>i&&i.CLOSING===2,ot=()=>typeof WebSocket<"u"&&Me(WebSocket),it=()=>({constructor:ot()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),lt=(i,e,t)=>{Object.defineProperty(e,t,{get:()=>i[t],set:n=>{i[t]=n},enumerable:!0,configurable:!0})},Oe=i=>i.minReconnectionDelay+Math.random()*i.minReconnectionDelay,ut=(i,e)=>{let t=e*i.reconnectionDelayGrowFactor;return t>i.maxReconnectionDelay?i.maxReconnectionDelay:t},ct=["onopen","onclose","onmessage","onerror"],dt=(i,e,t)=>{Object.keys(t).forEach(n=>{t[n].forEach(([s,r])=>{i.addEventListener(n,s,r)})}),e&&ct.forEach(n=>{i[n]=e[n]})},Ne=function(i,e,t={}){let n,s,r=0,l=0,u=!0,a={};if(!(this instanceof Ne))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let d=it();if(Object.keys(d).filter(y=>t.hasOwnProperty(y)).forEach(y=>d[y]=t[y]),!Me(d.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");let g=d.debug?(...y)=>console.log("RWS:",...y):()=>{},p=(y,c)=>setTimeout(()=>{let h=new Error(c);h.code=y,Array.isArray(a.error)&&a.error.forEach(([I])=>I(h)),n.onerror&&n.onerror(h)},0),o=()=>{if(g("close"),l++,g("retries count:",l),l>d.maxRetries){p("EHOSTDOWN","Too many failed connection attempts");return}r?r=ut(d,r):r=Oe(d),g("reconnectDelay:",r),u&&setTimeout(m,r)},m=()=>{g("connect");let y=n;n=new d.constructor(i,e),s=setTimeout(()=>{g("timeout"),n.close(),p("ETIMEDOUT","Connection timeout")},d.connectionTimeout),g("bypass properties");for(let c in n)["addEventListener","removeEventListener","close","send"].indexOf(c)<0&<(n,this,c);n.addEventListener("open",()=>{clearTimeout(s),g("open"),r=Oe(d),g("reconnectDelay:",r),l=0}),n.addEventListener("close",o),dt(n,y,a)};g("init"),m(),this.close=(y=1e3,c="",{keepClosed:h=!1,fastClose:I=!0,delay:R=0}={})=>{if(R&&(r=R),u=!h,n.close(y,c),I){let T={code:y,reason:c,wasClean:!0};o(),Array.isArray(a.close)&&a.close.forEach(([_,b])=>{_(T),n.removeEventListener("close",_,b)}),n.onclose&&(n.onclose(T),n.onclose=null)}},this.send=y=>{n.send(y)},this.addEventListener=(y,c,h)=>{Array.isArray(a[y])?a[y].some(([I])=>I===c)||a[y].push([c,h]):a[y]=[[c,h]],n.addEventListener(y,c,h)},this.removeEventListener=(y,c,h)=>{Array.isArray(a[y])&&(a[y]=a[y].filter(([I])=>I!==c)),n.removeEventListener(y,c,h)}};Le.exports=Ne});var pt={};st(pt,{EControlMode:()=>X,EModelArchitecture:()=>Te,EModelConditioning:()=>Re,EModelFormat:()=>fe,EModelType:()=>Ue,EOpenPosePreProcessor:()=>be,EPhotoMakerEnum:()=>_e,EPreProcessor:()=>te,EPreProcessorGroup:()=>ee,ETaskType:()=>G,Environment:()=>Z,Runware:()=>re,RunwareClient:()=>O,RunwareServer:()=>M,SdkType:()=>F});module.exports=rt(pt);var Z=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))(Z||{}),F=(t=>(t.CLIENT="CLIENT",t.SERVER="SERVER",t))(F||{}),G=(c=>(c.IMAGE_INFERENCE="imageInference",c.IMAGE_UPLOAD="imageUpload",c.IMAGE_UPSCALE="imageUpscale",c.IMAGE_BACKGROUND_REMOVAL="imageBackgroundRemoval",c.VIDEO_INFERENCE="videoInference",c.GET_RESPONSE="getResponse",c.PHOTO_MAKER="photoMaker",c.IMAGE_CAPTION="imageCaption",c.IMAGE_CONTROL_NET_PRE_PROCESS="imageControlNetPreProcess",c.IMAGE_MASKING="imageMasking",c.PROMPT_ENHANCE="promptEnhance",c.AUTHENTICATION="authentication",c.MODEL_UPLOAD="modelUpload",c.MODEL_SEARCH="modelSearch",c.AUDIO_INFERENCE="audioInference",c))(G||{}),X=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(X||{}),ee=(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))(ee||{}),te=(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))(te||{}),be=(r=>(r.openpose="openpose",r.openpose_face="openpose_face",r.openpose_faceonly="openpose_faceonly",r.openpose_full="openpose_full",r.openpose_hand="openpose_hand",r))(be||{}),fe=(t=>(t.safetensors="safetensors",t.pickletensor="pickletensor",t))(fe||{}),Te=(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))(Te||{}),Ue=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))(Ue||{}),Re=(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))(Re||{}),_e=(p=>(p.NoStyle="No style",p.Cinematic="Cinematic",p.DisneyCharacter="Disney Character",p.DigitalArt="Digital Art",p.Photographic="Photographic",p.FantasyArt="Fantasy art",p.Neonpunk="Neonpunk",p.Enhance="Enhance",p.ComicBook="Comic book",p.Lowpoly="Lowpoly",p.LineArt="Line art",p))(_e||{});var q=require("uuid"),V=6e4,B=1e3,ke=100,ne={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},De=(i,e)=>{if(i==null)return;let t=i.indexOf(e);t!==-1&&i.splice(t,1)},S=(i,{debugKey:e="debugKey",timeoutDuration:t=V,shouldThrowError:n=!0,pollingInterval:s=ke})=>(t=t<B?B:t,new Promise((r,l)=>{let u=setTimeout(()=>{a&&(clearInterval(a),n&&l(`Response could not be received from server for ${e}`)),clearTimeout(u)},t),a=setInterval(async()=>{i({resolve:r,reject:l,intervalId:a})&&(clearInterval(a),clearTimeout(u))},s)})),xe=i=>new Promise(e=>{let t=new FileReader;t.readAsDataURL(i),t.onload=function(){e(t.result)}}),k=()=>(0,q.v4)(),se=i=>(0,q.validate)(i);var ve=({key:i,data:e,useZero:t=!0,shouldReturnString:n=!1})=>i.split(/\.|\[/).map(l=>l.replace(/\]$/,"")).reduce((l,u)=>{let a=t?0:void 0,d=l?.[u];if(!d)return a;if(Array.isArray(d)&&/^\d+$/.test(u)){let g=parseInt(u,10);return g>=0&&g<d.length?l[u]=d[g]:l[u]??a}else return l[u]??a},e||{})??{},Se=(i,e=1e3)=>new Promise(t=>setTimeout(t,i*e));var Ae=(i,e)=>i.filter(t=>t.key!==e.key);var U=({key:i,value:e})=>e||e===0||e===!1?{[i]:e}:{},at=(i,e)=>Math.floor(Math.random()*(e-i+1))+i,we=()=>at(1,Number.MAX_SAFE_INTEGER),Ce=(i,{debugKey:e="debugKey",timeoutDuration:t=V,shouldThrowError:n=!0,pollingInterval:s=ke})=>(t=t<B?B:t,new Promise((r,l)=>{let u=setTimeout(()=>{a&&(clearInterval(a),n&&l(`Response could not be received from server for ${e}`)),clearTimeout(u)},t),a=setInterval(async()=>{try{await i({resolve:r,reject:l,intervalId:a})&&(clearInterval(a),clearTimeout(u))}catch(d){clearInterval(a),clearTimeout(u),l(d)}},s)})),Ee=i=>typeof i=="string"&&(i.startsWith("http:")||i.startsWith("https:"));var D=async(i,e={})=>{let{delayInSeconds:t=1,callback:n}=e,s=e.maxRetries??1;for(;s;)try{return await i()}catch(r){if(n?.(),r?.error)throw r;if(s--,s>0)await Se(t),await D(i,{...e,maxRetries:s});else throw r}};var w=class{constructor({apiKey:e,url:t=ne.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:s=2,timeoutDuration:r=V}){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=k();if(typeof e=="string"&&se(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:r,outputFormat:l,highThresholdCanny:u,lowThresholdCanny:a,includeHandsAndFaceOpenPose:d,includeCost:g,outputQuality:p,customTaskUUID:o,retry:m,includeGenerationTime:y,includePayload:c})=>{let h=m||this._globalMaxRetries,I,R=Date.now();try{return await D(async()=>{await this.ensureConnection();let T=await this.uploadImage(e);if(!T?.imageUUID)return null;let _=o||k(),b={inputImage:T.imageUUID,taskType:"imageControlNetPreProcess",taskUUID:_,preProcessorType:t,...U({key:"height",value:n}),...U({key:"width",value:s}),...U({key:"outputType",value:r}),...U({key:"outputFormat",value:l}),...U({key:"includeCost",value:g}),...U({key:"highThresholdCanny",value:u}),...U({key:"lowThresholdCanny",value:a}),...U({key:"includeHandsAndFaceOpenPose",value:d}),...p?{outputQuality:p}:{}};this.send({...b}),I=this.globalListener({taskUUID:_});let N=await S(({resolve:H,reject:Q})=>{let v=this.getSingleMessage({taskUUID:_});if(v){if(v?.error)return Q(v),!0;if(v)return H(v),!0}},{debugKey:"unprocessed-image",timeoutDuration:this._timeoutDuration});return I.destroy(),this.insertAdditionalResponse({response:N,payload:c?b:void 0,startTime:y?R:void 0}),N},{maxRetries:h,callback:()=>{I?.destroy()}})}catch(T){throw T}};this.requestImageToText=async({inputImage:e,includeCost:t,customTaskUUID:n,retry:s,includePayload:r,includeGenerationTime:l,inputImages:u,...a})=>{let d=s||this._globalMaxRetries,g,p=Date.now();try{return await D(async()=>{await this.ensureConnection();let o=e?await this.uploadImage(e):null,m=u?.length?await Promise.all(u.map(I=>this.uploadImage(I))):null,y=n||k(),c={taskUUID:y,taskType:"imageCaption",...o?.imageUUID?{inputImage:o.imageUUID}:{},...m?.length?{inputImages:m.map(I=>I?.imageUUID).filter(Boolean)}:{},...U({key:"includeCost",value:t}),...a};this.send(c),g=this.globalListener({taskUUID:y});let h=await S(({resolve:I,reject:R})=>{let T=this.getSingleMessage({taskUUID:y});if(T){if(T?.error)return R(T),!0;if(T)return delete this._globalMessages[y],I(T),!0}},{debugKey:"remove-image-background",timeoutDuration:this._timeoutDuration});return g.destroy(),this.insertAdditionalResponse({response:h,payload:r?c:void 0,startTime:l?p:void 0}),h},{maxRetries:d,callback:()=>{g?.destroy()}})}catch(o){throw o}};this.removeImageBackground=async e=>this.baseSingleRequest({payload:{...e,taskType:"imageBackgroundRemoval"},debugKey:"remove-image-background"});this.videoInference=async e=>{let{skipResponse:t,inputAudios:n,...s}=e;try{if(n?.length){for(let d of n)if(!Ee(d)&&!se(d))throw new Error(`Invalid audio source: "${d}". Only public URLs or media UUIDs are supported for audio.`)}let r=await this.baseSingleRequest({payload:{...s,...n?.length?{inputAudios:n}:{},deliveryMethod:"async",taskType:"videoInference"},debugKey:"video-inference"});if(t)return r;let l=r?.taskUUID,u=e?.numberResults??1,a=new Map;return await Ce(async({resolve:d,reject:g})=>{try{let p=await this.getResponse({taskUUID:l});for(let m of p||[])m.videoUUID&&a.set(m.videoUUID,m);return a.size===u?(d(Array.from(a.values())),!0):!1}catch(p){return g(p),!0}},{debugKey:"async-response",pollingInterval:2*1e3,timeoutDuration:10*60*1e3}),Array.from(a.values())}catch(r){throw r}};this.getResponse=async e=>{let t=e.taskUUID;return this.baseSingleRequest({payload:{...e,customTaskUUID:t,taskType:"getResponse"},isMultiple:!0,debugKey:"async-results"})};this.upscaleGan=async({inputImage:e,upscaleFactor:t,outputType:n,outputFormat:s,includeCost:r,outputQuality:l,customTaskUUID:u,retry:a,includeGenerationTime:d,includePayload:g,...p})=>{let o=a||this._globalMaxRetries,m,y=Date.now();try{return await D(async()=>{await this.ensureConnection();let c;c=await this.uploadImage(e);let h=u||k(),I={taskUUID:h,inputImage:c?.imageUUID,taskType:"imageUpscale",upscaleFactor:t,...U({key:"includeCost",value:r}),...n?{outputType:n}:{},...l?{outputQuality:l}:{},...s?{outputFormat:s}:{},...p};this.send(I),m=this.globalListener({taskUUID:h});let R=await S(({resolve:T,reject:_})=>{let b=this.getSingleMessage({taskUUID:h});if(b){if(b?.error)return _(b),!0;if(b)return delete this._globalMessages[h],T(b),!0}},{debugKey:"upscale-gan",timeoutDuration:this._timeoutDuration});return m.destroy(),this.insertAdditionalResponse({response:R,payload:g?I:void 0,startTime:d?y:void 0}),R},{maxRetries:o,callback:()=>{m?.destroy()}})}catch(c){throw c}};this.enhancePrompt=async({prompt:e,promptMaxLength:t=380,promptVersions:n=1,includeCost:s,customTaskUUID:r,retry:l,includeGenerationTime:u,includePayload:a})=>{let d=l||this._globalMaxRetries,g,p=Date.now();try{return await D(async()=>{await this.ensureConnection();let o=r||k(),m={prompt:e,taskUUID:o,promptMaxLength:t,promptVersions:n,...U({key:"includeCost",value:s}),taskType:"promptEnhance"};this.send(m),g=this.globalListener({taskUUID:o});let y=await S(({resolve:c,reject:h})=>{let I=this._globalMessages[o];if(I?.error)return h(I),!0;if(I?.length>=n)return delete this._globalMessages[o],c(I),!0},{debugKey:"enhance-prompt",timeoutDuration:this._timeoutDuration});return g.destroy(),this.insertAdditionalResponse({response:y,payload:a?m:void 0,startTime:u?p:void 0}),y},{maxRetries:d,callback:()=>{g?.destroy()}})}catch(o){throw o}};this.modelUpload=async e=>{let{onUploadStream:t,retry:n,customTaskUUID:s,...r}=e,l=n||this._globalMaxRetries,u;try{return await D(async()=>{await this.ensureConnection();let a=s||k();this.send({...r,taskUUID:a,taskType:"modelUpload"});let d,g;return u=this.listenToUpload({taskUUID:a,onUploadStream:(o,m)=>{t?.(o,m),o?.status==="ready"?d=o:m&&(g=m)}}),await S(({resolve:o,reject:m})=>{if(d)return o(d),!0;if(g)return m(g),!1},{shouldThrowError:!1,timeoutDuration:60*60*1e3})},{maxRetries:l,callback:()=>{u?.destroy()}})}catch(a){throw a}};this.photoMaker=async(e,t)=>{let{onPartialImages:n,retry:s,customTaskUUID:r,numberResults:l,includeGenerationTime:u,includePayload:a,...d}=e,g=s||this._globalMaxRetries,p,o=[],m=0,y=Date.now();try{return await D(async()=>{await this.ensureConnection(),m++;let c=this._globalImages.filter(_=>o.includes(_.taskUUID)),h=r||k();o.push(h);let I=l-c.length,R={...d,...d.seed?{seed:d.seed}:{seed:we()},...t??{},taskUUID:h,taskType:"photoMaker",numberResults:l};this.send({...R,numberResults:I}),p=this.listenToImages({onPartialImages:n,taskUUID:h,groupKey:"REQUEST_IMAGES",requestPayload:a?R:void 0,startTime:u?y:void 0});let T=await this.getSimilarImages({taskUUID:o,numberResults:l,lis:p});return p.destroy(),T},{maxRetries:g,callback:()=>{p?.destroy()}})}catch(c){if(c.taskUUID)throw c;if(m>=g)return this.handleIncompleteImages({taskUUIDs:o,error:c})}};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.audioInference=async e=>{let{skipResponse:t,deliveryMethod:n="sync",...s}=e;try{return await(n==="sync"?this.baseSyncRequest:this.baseSingleRequest)({payload:{...s,numberResults:s.numberResults||1,taskType:"audioInference",deliveryMethod:n},debugKey:"audio-inference"})}catch(r){throw r}};this.baseSingleRequest=async({payload:e,debugKey:t,isMultiple:n})=>{let{retry:s,customTaskUUID:r,includePayload:l,includeGenerationTime:u,...a}=e,d=s||this._globalMaxRetries,g,p=Date.now();try{return await D(async()=>{await this.ensureConnection();let o=r||k(),m={...a,taskUUID:o};this.send(m),g=this.globalListener({taskUUID:o});let y=await S(({resolve:c,reject:h})=>{let I=n?this.getMultipleMessages({taskUUID:o}):this.getSingleMessage({taskUUID:o});if(I){if(I?.error)return h(I),!0;if(I)return delete this._globalMessages[o],c(I),!0}},{debugKey:t,timeoutDuration:this._timeoutDuration});return this.insertAdditionalResponse({response:y,payload:l?m:void 0,startTime:u?p:void 0}),g.destroy(),y},{maxRetries:d,callback:()=>{g?.destroy()}})}catch(o){throw o}};this.baseSyncRequest=async({payload:e,debugKey:t})=>{let{retry:n,customTaskUUID:s,includePayload:r,numberResults:l=1,onPartialRequest:u,includeGenerationTime:a,...d}=e,g=n||this._globalMaxRetries,p,o=[],m=0,y=Date.now();try{return await D(async()=>{await this.ensureConnection(),m++;let c=this._globalImages.filter(_=>o.includes(_.taskUUID)),h=s||k();o.push(h);let I=l-c.length,R={...d,taskUUID:h,numberResults:I};this.send(R),p=this.listenToImages({onPartialImages:u,taskUUID:h,groupKey:"REQUEST_AUDIO",requestPayload:r?R:void 0,startTime:a?y:void 0});let T=await this.getSimilarImages({taskUUID:o,numberResults:l,lis:p,debugKey:t});return p.destroy(),T},{maxRetries:g,callback:()=>{p?.destroy()}})}catch(c){throw c}};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=u=>{let a=Array.isArray(u?.data)?u.data:[u.data],d=u?.[0]?.errors?u?.[0]?.errors:Array.isArray(u?.errors)?u.errors:[u.errors],g=a.filter(o=>(o?.taskUUID||o?.taskType)===n);if(d.filter(o=>(o?.taskUUID||o?.taskType)===n).length){e({error:{...d[0]??{}}});return}if(g.length){e({[n]:a});return}},r={key:n||k(),listener:s,groupKey:t};return this._listeners.push(r),{destroy:()=>{this._listeners=Ae(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){De(this._listeners,e)}listenToImages({onPartialImages:e,taskUUID:t,groupKey:n,requestPayload:s,startTime:r}){return this.addListener({taskUUID:t,lis:l=>{let u=l?.[t]?.filter(a=>a.taskUUID===t);l.error?(e?.(u,l?.error&&l),this._globalError=l):(u=u.map(a=>(this.insertAdditionalResponse({response:a,payload:s||void 0,startTime:r||void 0}),{...a})),e?.(u,l?.error&&l),this._sdkType==="CLIENT"?this._globalImages=[...this._globalImages,...(l?.[t]??[]).map(a=>(this.insertAdditionalResponse({response:a,payload:s||void 0,startTime:r||void 0}),{...a}))]:this._globalImages=[...this._globalImages,...u])},groupKey:n})}listenToUpload({onUploadStream:e,taskUUID:t}){return this.addListener({taskUUID:t,lis:n=>{let s=n?.error,r=n?.[t]?.[0],l=r?.taskUUID===t?r:null;(l||s)&&e?.(l||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:r,negativePrompt:l,seedImage:u,maskImage:a,strength:d,height:g,width:p,model:o,steps:m,scheduler:y,seed:c,CFGScale:h,clipSkip:I,usePromptWeighting:R,promptWeighting:T,numberResults:_=1,onPartialImages:b,includeCost:N,customTaskUUID:H,retry:Q,refiner:v,maskMargin:Fe,outputQuality:f,controlNet:j,lora:ae,embeddings:oe,ipAdapters:ie,providerSettings:le,outpaint:ue,acceleratorOptions:ce,advancedFeatures:de,referenceImages:pe,includeGenerationTime:Ge,includePayload:Be,...qe},Ve){let C,ge,L=[],me=0,ye=Q||this._globalMaxRetries;try{await this.ensureConnection();let A=null,J=null,$=[];if(u){let x=await this.uploadImage(u);if(!x)return[];A=x.imageUUID}if(a){let x=await this.uploadImage(a);if(!x)return[];J=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:Qe,startStepPercentage:je,endStepPercentage:Je,model:$e}=E,ze=K?await this.uploadImage(K):null;$.push({guideImage:ze?.imageUUID,model:$e,endStep:z,startStep:P,weight:Y,...U({key:"startStepPercentage",value:je}),...U({key:"endStepPercentage",value:Je}),controlMode:Qe||"controlnet"})}ge={taskType:"imageInference",model:o,positivePrompt:r,...l?{negativePrompt:l}:{},...g?{height:g}:{},...p?{width:p}:{},numberResults:_,...e?{outputType:e}:{},...t?{outputFormat:t}:{},...n?{uploadEndpoint:n}:{},...U({key:"checkNSFW",value:s}),...U({key:"strength",value:d}),...U({key:"CFGScale",value:h}),...U({key:"clipSkip",value:I}),...U({key:"maskMargin",value:Fe}),...U({key:"usePromptWeighting",value:R}),...U({key:"steps",value:m}),...T?{promptWeighting:T}:{},...c?{seed:c}:{},...y?{scheduler:y}:{},...v?{refiner:v}:{},...ue?{outpaint:ue}:{},...U({key:"includeCost",value:N}),...A?{seedImage:A}:{},...J?{maskImage:J}:{},...f?{outputQuality:f}:{},...$.length?{controlNet:$}:{},...ae?.length?{lora:ae}:{},...oe?.length?{embeddings:oe}:{},...ie?.length?{ipAdapters:ie}:{},...le?{providerSettings:le}:{},...ce?{acceleratorOptions:ce}:{},...de?{advancedFeatures:de}:{},...pe?.length?{referenceImages:pe}:{},...qe,...Ve??{}};let He=Date.now();return await D(async()=>{me++,C?.destroy();let x=this._globalImages.filter(K=>L.includes(K.taskUUID)),E=H||k();L.push(E);let z=_-x.length,P={...ge,taskUUID:E,numberResults:z};this.send(P),C=this.listenToImages({onPartialImages:b,taskUUID:E,groupKey:"REQUEST_IMAGES",requestPayload:Be?P:void 0,startTime:Ge?He:void 0});let Y=await this.getSimilarImages({taskUUID:L,numberResults:_,lis:C});return C.destroy(),Y},{maxRetries:ye,callback:()=>{C?.destroy()}})}catch(A){if(me>=ye)return this.handleIncompleteImages({taskUUIDs:L,error:A});throw A}}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,r)=>{let l=0,u=30,a=k(),d,g,p=()=>{this.ensureConnectionUUID=null,clearInterval(d),clearInterval(g)};this._sdkType==="SERVER"&&(d=setInterval(async()=>{try{let o=this.connected(),m=!1;(!this.ensureConnectionUUID||a===this.ensureConnectionUUID)&&(this.ensureConnectionUUID||(this.ensureConnectionUUID=a),m=!0);let y=l%10===0&&m;o?(p(),s(!0)):l>=u?(p(),r(new Error("Retry timed out"))):(y&&this.connect(),l++)}catch(o){p(),r(o)}},t)),g=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,debugKey:r="getting-images"}){return await S(({resolve:l,reject:u,intervalId:a})=>{let d=Array.isArray(e)?e:[e],g=this._globalImages.filter(p=>d.includes(p.taskUUID));if(this._globalError){let p=this._globalError;return this._globalError=void 0,clearInterval(a),u?.(p),!0}else if(g.length>=t)return clearInterval(a),this._globalImages=this._globalImages.filter(p=>!d.includes(p.taskUUID)),l([...g].slice(0,t)),!0},{debugKey:r,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 Ke=he(Pe(),1),O=class extends w{constructor(e){let{shouldReconnect:t,...n}=e;super(n),this._ws=new Ke.default(this._url),this.connect()}};var We=he(require("ws"),1);var M=class extends w{constructor(t){super(t);this._instantiated=!1;this._listeners=[];this._reconnectingIntervalId=null;this.send=t=>{this._ws.send(JSON.stringify([t]))};this.resetConnection=()=>{this._ws&&(this._listeners.forEach(t=>{t?.destroy?.()}),this._ws.removeAllListeners(),this._ws.readyState===1&&(this._ws.terminate(),this._ws.close()),this._ws=null,this._listeners=[])};this._sdkType="SERVER",this.connect()}async connect(){this._url&&(this.resetConnection(),this._ws=new We.default(this._url,{perMessageDeflate:!1}),this._ws.on("error",()=>{}),this._ws.on("close",()=>{this.handleClose()}),this._ws.on("open",()=>{this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._connectionSessionUUID&&this.isWebsocketReadyState()?this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.isWebsocketReadyState()&&this.send({apiKey:this._apiKey,taskType:"authentication"}),this.addListener({taskUUID:"authentication",lis:t=>{if(t?.error){this._connectionError=t;return}this._connectionSessionUUID=t?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0}})}),this._ws.on("message",(t,n)=>{let s=n?t:t?.toString();if(!s)return;let r=JSON.parse(s);this._listeners.forEach(l=>{l.listener(r)})}))}handleClose(){this.isInvalidAPIKey()||(this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._shouldReconnect&&setTimeout(()=>this.connect(),1e3))}heartBeat(){clearTimeout(this._pingTimeout),this._pingTimeout=setTimeout(()=>{this.isWebsocketReadyState()&&this.send({ping:!0})},5e3)}};var re;typeof window>"u"?re=M:re=O;0&&(module.exports={EControlMode,EModelArchitecture,EModelConditioning,EModelFormat,EModelType,EOpenPosePreProcessor,EPhotoMakerEnum,EPreProcessor,EPreProcessorGroup,ETaskType,Environment,Runware,RunwareClient,RunwareServer,SdkType});
|
|
1
|
+
"use strict";var Ye=Object.create;var W=Object.defineProperty;var Ze=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var et=Object.getPrototypeOf,tt=Object.prototype.hasOwnProperty;var nt=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),st=(i,e)=>{for(var t in e)W(i,t,{get:e[t],enumerable:!0})},Ie=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Xe(e))!tt.call(i,s)&&s!==t&&W(i,s,{get:()=>e[s],enumerable:!(n=Ze(e,s))||n.enumerable});return i};var he=(i,e,t)=>(t=i!=null?Ye(et(i)):{},Ie(e||!i||!i.__esModule?W(t,"default",{value:i,enumerable:!0}):t,i)),rt=i=>Ie(W({},"__esModule",{value:!0}),i);var Pe=nt((dn,Le)=>{"use strict";var Me=i=>i&&i.CLOSING===2,ot=()=>typeof WebSocket<"u"&&Me(WebSocket),it=()=>({constructor:ot()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),lt=(i,e,t)=>{Object.defineProperty(e,t,{get:()=>i[t],set:n=>{i[t]=n},enumerable:!0,configurable:!0})},Oe=i=>i.minReconnectionDelay+Math.random()*i.minReconnectionDelay,ut=(i,e)=>{let t=e*i.reconnectionDelayGrowFactor;return t>i.maxReconnectionDelay?i.maxReconnectionDelay:t},ct=["onopen","onclose","onmessage","onerror"],dt=(i,e,t)=>{Object.keys(t).forEach(n=>{t[n].forEach(([s,r])=>{i.addEventListener(n,s,r)})}),e&&ct.forEach(n=>{i[n]=e[n]})},Ne=function(i,e,t={}){let n,s,r=0,l=0,u=!0,a={};if(!(this instanceof Ne))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let d=it();if(Object.keys(d).filter(y=>t.hasOwnProperty(y)).forEach(y=>d[y]=t[y]),!Me(d.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");let g=d.debug?(...y)=>console.log("RWS:",...y):()=>{},p=(y,c)=>setTimeout(()=>{let h=new Error(c);h.code=y,Array.isArray(a.error)&&a.error.forEach(([I])=>I(h)),n.onerror&&n.onerror(h)},0),o=()=>{if(g("close"),l++,g("retries count:",l),l>d.maxRetries){p("EHOSTDOWN","Too many failed connection attempts");return}r?r=ut(d,r):r=Oe(d),g("reconnectDelay:",r),u&&setTimeout(m,r)},m=()=>{g("connect");let y=n;n=new d.constructor(i,e),s=setTimeout(()=>{g("timeout"),n.close(),p("ETIMEDOUT","Connection timeout")},d.connectionTimeout),g("bypass properties");for(let c in n)["addEventListener","removeEventListener","close","send"].indexOf(c)<0&<(n,this,c);n.addEventListener("open",()=>{clearTimeout(s),g("open"),r=Oe(d),g("reconnectDelay:",r),l=0}),n.addEventListener("close",o),dt(n,y,a)};g("init"),m(),this.close=(y=1e3,c="",{keepClosed:h=!1,fastClose:I=!0,delay:R=0}={})=>{if(R&&(r=R),u=!h,n.close(y,c),I){let U={code:y,reason:c,wasClean:!0};o(),Array.isArray(a.close)&&a.close.forEach(([_,b])=>{_(U),n.removeEventListener("close",_,b)}),n.onclose&&(n.onclose(U),n.onclose=null)}},this.send=y=>{n.send(y)},this.addEventListener=(y,c,h)=>{Array.isArray(a[y])?a[y].some(([I])=>I===c)||a[y].push([c,h]):a[y]=[[c,h]],n.addEventListener(y,c,h)},this.removeEventListener=(y,c,h)=>{Array.isArray(a[y])&&(a[y]=a[y].filter(([I])=>I!==c)),n.removeEventListener(y,c,h)}};Le.exports=Ne});var pt={};st(pt,{EControlMode:()=>X,EModelArchitecture:()=>Ue,EModelConditioning:()=>Re,EModelFormat:()=>fe,EModelType:()=>Te,EOpenPosePreProcessor:()=>be,EPhotoMakerEnum:()=>_e,EPreProcessor:()=>te,EPreProcessorGroup:()=>ee,ETaskType:()=>G,Environment:()=>Z,Runware:()=>re,RunwareClient:()=>O,RunwareServer:()=>M,SdkType:()=>F});module.exports=rt(pt);var Z=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))(Z||{}),F=(t=>(t.CLIENT="CLIENT",t.SERVER="SERVER",t))(F||{}),G=(c=>(c.IMAGE_INFERENCE="imageInference",c.IMAGE_UPLOAD="imageUpload",c.IMAGE_UPSCALE="imageUpscale",c.IMAGE_BACKGROUND_REMOVAL="imageBackgroundRemoval",c.VIDEO_INFERENCE="videoInference",c.GET_RESPONSE="getResponse",c.PHOTO_MAKER="photoMaker",c.IMAGE_CAPTION="imageCaption",c.IMAGE_CONTROL_NET_PRE_PROCESS="imageControlNetPreProcess",c.IMAGE_MASKING="imageMasking",c.PROMPT_ENHANCE="promptEnhance",c.AUTHENTICATION="authentication",c.MODEL_UPLOAD="modelUpload",c.MODEL_SEARCH="modelSearch",c.AUDIO_INFERENCE="audioInference",c))(G||{}),X=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(X||{}),ee=(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))(ee||{}),te=(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))(te||{}),be=(r=>(r.openpose="openpose",r.openpose_face="openpose_face",r.openpose_faceonly="openpose_faceonly",r.openpose_full="openpose_full",r.openpose_hand="openpose_hand",r))(be||{}),fe=(t=>(t.safetensors="safetensors",t.pickletensor="pickletensor",t))(fe||{}),Ue=(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))(Ue||{}),Te=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))(Te||{}),Re=(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))(Re||{}),_e=(p=>(p.NoStyle="No style",p.Cinematic="Cinematic",p.DisneyCharacter="Disney Character",p.DigitalArt="Digital Art",p.Photographic="Photographic",p.FantasyArt="Fantasy art",p.Neonpunk="Neonpunk",p.Enhance="Enhance",p.ComicBook="Comic book",p.Lowpoly="Lowpoly",p.LineArt="Line art",p))(_e||{});var q=require("uuid"),V=6e4,B=1e3,ke=100,ne={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},De=(i,e)=>{if(i==null)return;let t=i.indexOf(e);t!==-1&&i.splice(t,1)},S=(i,{debugKey:e="debugKey",timeoutDuration:t=V,shouldThrowError:n=!0,pollingInterval:s=ke})=>(t=t<B?B:t,new Promise((r,l)=>{let u=setTimeout(()=>{a&&(clearInterval(a),n&&l(`Response could not be received from server for ${e}`)),clearTimeout(u)},t),a=setInterval(async()=>{i({resolve:r,reject:l,intervalId:a})&&(clearInterval(a),clearTimeout(u))},s)})),xe=i=>new Promise(e=>{let t=new FileReader;t.readAsDataURL(i),t.onload=function(){e(t.result)}}),k=()=>(0,q.v4)(),se=i=>(0,q.validate)(i);var ve=({key:i,data:e,useZero:t=!0,shouldReturnString:n=!1})=>i.split(/\.|\[/).map(l=>l.replace(/\]$/,"")).reduce((l,u)=>{let a=t?0:void 0,d=l?.[u];if(!d)return a;if(Array.isArray(d)&&/^\d+$/.test(u)){let g=parseInt(u,10);return g>=0&&g<d.length?l[u]=d[g]:l[u]??a}else return l[u]??a},e||{})??{},Se=(i,e=1e3)=>new Promise(t=>setTimeout(t,i*e));var Ae=(i,e)=>i.filter(t=>t.key!==e.key);var T=({key:i,value:e})=>e||e===0||e===!1?{[i]:e}:{},at=(i,e)=>Math.floor(Math.random()*(e-i+1))+i,we=()=>at(1,Number.MAX_SAFE_INTEGER),Ce=(i,{debugKey:e="debugKey",timeoutDuration:t=V,shouldThrowError:n=!0,pollingInterval:s=ke})=>(t=t<B?B:t,new Promise((r,l)=>{let u=setTimeout(()=>{a&&(clearInterval(a),n&&l(`Response could not be received from server for ${e}`)),clearTimeout(u)},t),a=setInterval(async()=>{try{await i({resolve:r,reject:l,intervalId:a})&&(clearInterval(a),clearTimeout(u))}catch(d){clearInterval(a),clearTimeout(u),l(d)}},s)})),Ee=i=>typeof i=="string"&&(i.startsWith("http:")||i.startsWith("https:"));var D=async(i,e={})=>{let{delayInSeconds:t=1,callback:n}=e,s=e.maxRetries??1;for(;s;)try{return await i()}catch(r){if(n?.(),r?.error)throw r;if(s--,s>0)await Se(t),await D(i,{...e,maxRetries:s});else throw r}};var w=class{constructor({apiKey:e,url:t=ne.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:s=2,timeoutDuration:r=V}){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=k();if(typeof e=="string"&&se(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:r,outputFormat:l,highThresholdCanny:u,lowThresholdCanny:a,includeHandsAndFaceOpenPose:d,includeCost:g,outputQuality:p,customTaskUUID:o,retry:m,includeGenerationTime:y,includePayload:c})=>{let h=m||this._globalMaxRetries,I,R=Date.now();try{return await D(async()=>{await this.ensureConnection();let U=await this.uploadImage(e);if(!U?.imageUUID)return null;let _=o||k(),b={inputImage:U.imageUUID,taskType:"imageControlNetPreProcess",taskUUID:_,preProcessorType:t,...T({key:"height",value:n}),...T({key:"width",value:s}),...T({key:"outputType",value:r}),...T({key:"outputFormat",value:l}),...T({key:"includeCost",value:g}),...T({key:"highThresholdCanny",value:u}),...T({key:"lowThresholdCanny",value:a}),...T({key:"includeHandsAndFaceOpenPose",value:d}),...p?{outputQuality:p}:{}};this.send({...b}),I=this.globalListener({taskUUID:_});let N=await S(({resolve:H,reject:Q})=>{let v=this.getSingleMessage({taskUUID:_});if(v){if(v?.error)return Q(v),!0;if(v)return H(v),!0}},{debugKey:"unprocessed-image",timeoutDuration:this._timeoutDuration});return I.destroy(),this.insertAdditionalResponse({response:N,payload:c?b:void 0,startTime:y?R:void 0}),N},{maxRetries:h,callback:()=>{I?.destroy()}})}catch(U){throw U}};this.requestImageToText=async({inputImage:e,includeCost:t,customTaskUUID:n,retry:s,includePayload:r,includeGenerationTime:l,inputImages:u,...a})=>{let d=s||this._globalMaxRetries,g,p=Date.now();try{return await D(async()=>{await this.ensureConnection();let o=e?await this.uploadImage(e):null,m=u?.length?await Promise.all(u.map(I=>this.uploadImage(I))):null,y=n||k(),c={taskUUID:y,taskType:"imageCaption",...o?.imageUUID?{inputImage:o.imageUUID}:{},...m?.length?{inputImages:m.map(I=>I?.imageUUID).filter(Boolean)}:{},...T({key:"includeCost",value:t}),...a};this.send(c),g=this.globalListener({taskUUID:y});let h=await S(({resolve:I,reject:R})=>{let U=this.getSingleMessage({taskUUID:y});if(U){if(U?.error)return R(U),!0;if(U)return delete this._globalMessages[y],I(U),!0}},{debugKey:"remove-image-background",timeoutDuration:this._timeoutDuration});return g.destroy(),this.insertAdditionalResponse({response:h,payload:r?c:void 0,startTime:l?p:void 0}),h},{maxRetries:d,callback:()=>{g?.destroy()}})}catch(o){throw o}};this.removeImageBackground=async e=>this.baseSingleRequest({payload:{...e,taskType:"imageBackgroundRemoval"},debugKey:"remove-image-background"});this.videoInference=async e=>{let{skipResponse:t,inputAudios:n,...s}=e;try{if(n?.length){for(let d of n)if(!Ee(d)&&!se(d))throw new Error(`Invalid audio source: "${d}". Only public URLs or media UUIDs are supported for audio.`)}let r=await this.baseSingleRequest({payload:{...s,...n?.length?{inputAudios:n}:{},deliveryMethod:"async",taskType:"videoInference"},debugKey:"video-inference"});if(t)return r;let l=r?.taskUUID,u=e?.numberResults??1,a=new Map;return await Ce(async({resolve:d,reject:g})=>{try{let p=await this.getResponse({taskUUID:l});for(let m of p||[])m.videoUUID&&a.set(m.videoUUID,m);return a.size===u?(d(Array.from(a.values())),!0):!1}catch(p){return g(p),!0}},{debugKey:"async-response",pollingInterval:2*1e3,timeoutDuration:10*60*1e3}),Array.from(a.values())}catch(r){throw r}};this.getResponse=async e=>{let t=e.taskUUID;return this.baseSingleRequest({payload:{...e,customTaskUUID:t,taskType:"getResponse"},isMultiple:!0,debugKey:"async-results"})};this.upscaleGan=async({inputImage:e,upscaleFactor:t,outputType:n,outputFormat:s,includeCost:r,outputQuality:l,customTaskUUID:u,retry:a,includeGenerationTime:d,includePayload:g,...p})=>{let o=a||this._globalMaxRetries,m,y=Date.now();try{return await D(async()=>{await this.ensureConnection();let c;c=await this.uploadImage(e);let h=u||k(),I={taskUUID:h,inputImage:c?.imageUUID,taskType:"imageUpscale",upscaleFactor:t,...T({key:"includeCost",value:r}),...n?{outputType:n}:{},...l?{outputQuality:l}:{},...s?{outputFormat:s}:{},...p};this.send(I),m=this.globalListener({taskUUID:h});let R=await S(({resolve:U,reject:_})=>{let b=this.getSingleMessage({taskUUID:h});if(b){if(b?.error)return _(b),!0;if(b)return delete this._globalMessages[h],U(b),!0}},{debugKey:"upscale-gan",timeoutDuration:this._timeoutDuration});return m.destroy(),this.insertAdditionalResponse({response:R,payload:g?I:void 0,startTime:d?y:void 0}),R},{maxRetries:o,callback:()=>{m?.destroy()}})}catch(c){throw c}};this.enhancePrompt=async({prompt:e,promptMaxLength:t=380,promptVersions:n=1,includeCost:s,customTaskUUID:r,retry:l,includeGenerationTime:u,includePayload:a})=>{let d=l||this._globalMaxRetries,g,p=Date.now();try{return await D(async()=>{await this.ensureConnection();let o=r||k(),m={prompt:e,taskUUID:o,promptMaxLength:t,promptVersions:n,...T({key:"includeCost",value:s}),taskType:"promptEnhance"};this.send(m),g=this.globalListener({taskUUID:o});let y=await S(({resolve:c,reject:h})=>{let I=this._globalMessages[o];if(I?.error)return h(I),!0;if(I?.length>=n)return delete this._globalMessages[o],c(I),!0},{debugKey:"enhance-prompt",timeoutDuration:this._timeoutDuration});return g.destroy(),this.insertAdditionalResponse({response:y,payload:a?m:void 0,startTime:u?p:void 0}),y},{maxRetries:d,callback:()=>{g?.destroy()}})}catch(o){throw o}};this.modelUpload=async e=>{let{onUploadStream:t,retry:n,customTaskUUID:s,...r}=e,l=n||this._globalMaxRetries,u;try{return await D(async()=>{await this.ensureConnection();let a=s||k();this.send({...r,taskUUID:a,taskType:"modelUpload"});let d,g;return u=this.listenToUpload({taskUUID:a,onUploadStream:(o,m)=>{t?.(o,m),o?.status==="ready"?d=o:m&&(g=m)}}),await S(({resolve:o,reject:m})=>{if(d)return o(d),!0;if(g)return m(g),!1},{shouldThrowError:!1,timeoutDuration:60*60*1e3})},{maxRetries:l,callback:()=>{u?.destroy()}})}catch(a){throw a}};this.photoMaker=async(e,t)=>{let{onPartialImages:n,retry:s,customTaskUUID:r,numberResults:l,includeGenerationTime:u,includePayload:a,...d}=e,g=s||this._globalMaxRetries,p,o=[],m=0,y=Date.now();try{return await D(async()=>{await this.ensureConnection(),m++;let c=this._globalImages.filter(_=>o.includes(_.taskUUID)),h=r||k();o.push(h);let I=l-c.length,R={...d,...d.seed?{seed:d.seed}:{seed:we()},...t??{},taskUUID:h,taskType:"photoMaker",numberResults:l};this.send({...R,numberResults:I}),p=this.listenToResponse({onPartialImages:n,taskUUID:h,groupKey:"REQUEST_IMAGES",requestPayload:a?R:void 0,startTime:u?y:void 0});let U=await this.getSimilarImages({taskUUID:o,numberResults:l,lis:p});return p.destroy(),U},{maxRetries:g,callback:()=>{p?.destroy()}})}catch(c){if(c.taskUUID)throw c;if(m>=g)return this.handleIncompleteImages({taskUUIDs:o,error:c})}};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.audioInference=async e=>{let{skipResponse:t,deliveryMethod:n="sync",...s}=e;try{return await(n==="sync"?this.baseSyncRequest:this.baseSingleRequest)({payload:{...s,numberResults:s.numberResults||1,taskType:"audioInference",deliveryMethod:n},debugKey:"audio-inference"})}catch(r){throw r}};this.baseSingleRequest=async({payload:e,debugKey:t,isMultiple:n})=>{let{retry:s,customTaskUUID:r,includePayload:l,includeGenerationTime:u,...a}=e,d=s||this._globalMaxRetries,g,p=Date.now();try{return await D(async()=>{await this.ensureConnection();let o=r||k(),m={...a,taskUUID:o};this.send(m),g=this.globalListener({taskUUID:o});let y=await S(({resolve:c,reject:h})=>{let I=n?this.getMultipleMessages({taskUUID:o}):this.getSingleMessage({taskUUID:o});if(I){if(I?.error)return h(I),!0;if(I)return delete this._globalMessages[o],c(I),!0}},{debugKey:t,timeoutDuration:this._timeoutDuration});return this.insertAdditionalResponse({response:y,payload:l?m:void 0,startTime:u?p:void 0}),g.destroy(),y},{maxRetries:d,callback:()=>{g?.destroy()}})}catch(o){throw o}};this.baseSyncRequest=async({payload:e,debugKey:t})=>{let{retry:n,customTaskUUID:s,includePayload:r,numberResults:l=1,onPartialResponse:u,includeGenerationTime:a,...d}=e,g=n||this._globalMaxRetries,p,o=[],m=0,y=Date.now();try{return await D(async()=>{await this.ensureConnection(),m++;let c=this._globalImages.filter(_=>o.includes(_.taskUUID)),h=s||k();o.push(h);let I=l-c.length,R={...d,taskUUID:h,numberResults:I};this.send(R),p=this.listenToResponse({onPartialImages:u,taskUUID:h,groupKey:"REQUEST_AUDIO",requestPayload:r?R:void 0,startTime:a?y:void 0});let U=await this.getSimilarImages({taskUUID:o,numberResults:l,lis:p,debugKey:t});return p.destroy(),U},{maxRetries:g,callback:()=>{p?.destroy()}})}catch(c){throw c}};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=u=>{let a=Array.isArray(u?.data)?u.data:[u.data],d=u?.[0]?.errors?u?.[0]?.errors:Array.isArray(u?.errors)?u.errors:[u.errors],g=a.filter(o=>(o?.taskUUID||o?.taskType)===n);if(d.filter(o=>(o?.taskUUID||o?.taskType)===n).length){e({error:{...d[0]??{}}});return}if(g.length){e({[n]:a});return}},r={key:n||k(),listener:s,groupKey:t};return this._listeners.push(r),{destroy:()=>{this._listeners=Ae(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){De(this._listeners,e)}listenToResponse({onPartialImages:e,taskUUID:t,groupKey:n,requestPayload:s,startTime:r}){return this.addListener({taskUUID:t,lis:l=>{let u=l?.[t]?.filter(a=>a.taskUUID===t);l.error?(e?.(u,l?.error&&l),this._globalError=l):(u=u.map(a=>(this.insertAdditionalResponse({response:a,payload:s||void 0,startTime:r||void 0}),{...a})),e?.(u,l?.error&&l),this._sdkType==="CLIENT"?this._globalImages=[...this._globalImages,...(l?.[t]??[]).map(a=>(this.insertAdditionalResponse({response:a,payload:s||void 0,startTime:r||void 0}),{...a}))]:this._globalImages=[...this._globalImages,...u])},groupKey:n})}listenToUpload({onUploadStream:e,taskUUID:t}){return this.addListener({taskUUID:t,lis:n=>{let s=n?.error,r=n?.[t]?.[0],l=r?.taskUUID===t?r:null;(l||s)&&e?.(l||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:r,negativePrompt:l,seedImage:u,maskImage:a,strength:d,height:g,width:p,model:o,steps:m,scheduler:y,seed:c,CFGScale:h,clipSkip:I,usePromptWeighting:R,promptWeighting:U,numberResults:_=1,onPartialImages:b,includeCost:N,customTaskUUID:H,retry:Q,refiner:v,maskMargin:Fe,outputQuality:f,controlNet:j,lora:ae,embeddings:oe,ipAdapters:ie,providerSettings:le,outpaint:ue,acceleratorOptions:ce,advancedFeatures:de,referenceImages:pe,includeGenerationTime:Ge,includePayload:Be,...qe},Ve){let C,ge,L=[],me=0,ye=Q||this._globalMaxRetries;try{await this.ensureConnection();let A=null,J=null,$=[];if(u){let x=await this.uploadImage(u);if(!x)return[];A=x.imageUUID}if(a){let x=await this.uploadImage(a);if(!x)return[];J=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:Qe,startStepPercentage:je,endStepPercentage:Je,model:$e}=E,ze=K?await this.uploadImage(K):null;$.push({guideImage:ze?.imageUUID,model:$e,endStep:z,startStep:P,weight:Y,...T({key:"startStepPercentage",value:je}),...T({key:"endStepPercentage",value:Je}),controlMode:Qe||"controlnet"})}ge={taskType:"imageInference",model:o,positivePrompt:r,...l?{negativePrompt:l}:{},...g?{height:g}:{},...p?{width:p}:{},numberResults:_,...e?{outputType:e}:{},...t?{outputFormat:t}:{},...n?{uploadEndpoint:n}:{},...T({key:"checkNSFW",value:s}),...T({key:"strength",value:d}),...T({key:"CFGScale",value:h}),...T({key:"clipSkip",value:I}),...T({key:"maskMargin",value:Fe}),...T({key:"usePromptWeighting",value:R}),...T({key:"steps",value:m}),...U?{promptWeighting:U}:{},...c?{seed:c}:{},...y?{scheduler:y}:{},...v?{refiner:v}:{},...ue?{outpaint:ue}:{},...T({key:"includeCost",value:N}),...A?{seedImage:A}:{},...J?{maskImage:J}:{},...f?{outputQuality:f}:{},...$.length?{controlNet:$}:{},...ae?.length?{lora:ae}:{},...oe?.length?{embeddings:oe}:{},...ie?.length?{ipAdapters:ie}:{},...le?{providerSettings:le}:{},...ce?{acceleratorOptions:ce}:{},...de?{advancedFeatures:de}:{},...pe?.length?{referenceImages:pe}:{},...qe,...Ve??{}};let He=Date.now();return await D(async()=>{me++,C?.destroy();let x=this._globalImages.filter(K=>L.includes(K.taskUUID)),E=H||k();L.push(E);let z=_-x.length,P={...ge,taskUUID:E,numberResults:z};this.send(P),C=this.listenToResponse({onPartialImages:b,taskUUID:E,groupKey:"REQUEST_IMAGES",requestPayload:Be?P:void 0,startTime:Ge?He:void 0});let Y=await this.getSimilarImages({taskUUID:L,numberResults:_,lis:C});return C.destroy(),Y},{maxRetries:ye,callback:()=>{C?.destroy()}})}catch(A){if(me>=ye)return this.handleIncompleteImages({taskUUIDs:L,error:A});throw A}}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,r)=>{let l=0,u=30,a=k(),d,g,p=()=>{this.ensureConnectionUUID=null,clearInterval(d),clearInterval(g)};this._sdkType==="SERVER"&&(d=setInterval(async()=>{try{let o=this.connected(),m=!1;(!this.ensureConnectionUUID||a===this.ensureConnectionUUID)&&(this.ensureConnectionUUID||(this.ensureConnectionUUID=a),m=!0);let y=l%10===0&&m;o?(p(),s(!0)):l>=u?(p(),r(new Error("Retry timed out"))):(y&&this.connect(),l++)}catch(o){p(),r(o)}},t)),g=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,debugKey:r="getting-images"}){return await S(({resolve:l,reject:u,intervalId:a})=>{let d=Array.isArray(e)?e:[e],g=this._globalImages.filter(p=>d.includes(p.taskUUID));if(this._globalError){let p=this._globalError;return this._globalError=void 0,clearInterval(a),u?.(p),!0}else if(g.length>=t)return clearInterval(a),this._globalImages=this._globalImages.filter(p=>!d.includes(p.taskUUID)),l([...g].slice(0,t)),!0},{debugKey:r,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 Ke=he(Pe(),1),O=class extends w{constructor(e){let{shouldReconnect:t,...n}=e;super(n),this._ws=new Ke.default(this._url),this.connect()}};var We=he(require("ws"),1);var M=class extends w{constructor(t){super(t);this._instantiated=!1;this._listeners=[];this._reconnectingIntervalId=null;this.send=t=>{this._ws.send(JSON.stringify([t]))};this.resetConnection=()=>{this._ws&&(this._listeners.forEach(t=>{t?.destroy?.()}),this._ws.removeAllListeners(),this._ws.readyState===1&&(this._ws.terminate(),this._ws.close()),this._ws=null,this._listeners=[])};this._sdkType="SERVER",this.connect()}async connect(){this._url&&(this.resetConnection(),this._ws=new We.default(this._url,{perMessageDeflate:!1}),this._ws.on("error",()=>{}),this._ws.on("close",()=>{this.handleClose()}),this._ws.on("open",()=>{this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._connectionSessionUUID&&this.isWebsocketReadyState()?this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.isWebsocketReadyState()&&this.send({apiKey:this._apiKey,taskType:"authentication"}),this.addListener({taskUUID:"authentication",lis:t=>{if(t?.error){this._connectionError=t;return}this._connectionSessionUUID=t?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0}})}),this._ws.on("message",(t,n)=>{let s=n?t:t?.toString();if(!s)return;let r=JSON.parse(s);this._listeners.forEach(l=>{l.listener(r)})}))}handleClose(){this.isInvalidAPIKey()||(this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._shouldReconnect&&setTimeout(()=>this.connect(),1e3))}heartBeat(){clearTimeout(this._pingTimeout),this._pingTimeout=setTimeout(()=>{this.isWebsocketReadyState()&&this.send({ping:!0})},5e3)}};var re;typeof window>"u"?re=M:re=O;0&&(module.exports={EControlMode,EModelArchitecture,EModelConditioning,EModelFormat,EModelType,EOpenPosePreProcessor,EPhotoMakerEnum,EPreProcessor,EPreProcessorGroup,ETaskType,Environment,Runware,RunwareClient,RunwareServer,SdkType});
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|