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