@runware/sdk-js 1.1.28 → 1.1.30
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 +2 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/readme.md +13 -0
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var Ne=Object.create;var E=Object.defineProperty;var Le=Object.getOwnPropertyDescriptor;var Ee=Object.getOwnPropertyNames;var Ke=Object.getPrototypeOf,Pe=Object.prototype.hasOwnProperty;var We=(l,t)=>()=>(t||l((t={exports:{}}).exports,t),t.exports),Fe=(l,t)=>{for(var e in t)E(l,e,{get:t[e],enumerable:!0})},ne=(l,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Ee(t))!Pe.call(l,a)&&a!==e&&E(l,a,{get:()=>t[a],enumerable:!(n=Le(t,a))||n.enumerable});return l};var se=(l,t,e)=>(e=l!=null?Ne(Ke(l)):{},ne(t||!l||!l.__esModule?E(e,"default",{value:l,enumerable:!0}):e,l)),Ge=l=>ne(E({},"__esModule",{value:!0}),l);var Ue=We((Pt,Te)=>{"use strict";var fe=l=>l&&l.CLOSING===2,qe=()=>typeof WebSocket<"u"&&fe(WebSocket),He=()=>({constructor:qe()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),Ve=(l,t,e)=>{Object.defineProperty(t,e,{get:()=>l[e],set:n=>{l[e]=n},enumerable:!0,configurable:!0})},he=l=>l.minReconnectionDelay+Math.random()*l.minReconnectionDelay,je=(l,t)=>{let e=t*l.reconnectionDelayGrowFactor;return e>l.maxReconnectionDelay?l.maxReconnectionDelay:e},ze=["onopen","onclose","onmessage","onerror"],Je=(l,t,e)=>{Object.keys(e).forEach(n=>{e[n].forEach(([a,o])=>{l.addEventListener(n,a,o)})}),t&&ze.forEach(n=>{l[n]=t[n]})},be=function(l,t,e={}){let n,a,o=0,c=0,i=!0,r={};if(!(this instanceof be))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let u=He();if(Object.keys(u).filter(p=>e.hasOwnProperty(p)).forEach(p=>u[p]=e[p]),!fe(u.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");let g=u.debug?(...p)=>console.log("RWS:",...p):()=>{},d=(p,y)=>setTimeout(()=>{let b=new Error(y);b.code=p,Array.isArray(r.error)&&r.error.forEach(([T])=>T(b)),n.onerror&&n.onerror(b)},0),s=()=>{if(g("close"),c++,g("retries count:",c),c>u.maxRetries){d("EHOSTDOWN","Too many failed connection attempts");return}o?o=je(u,o):o=he(u),g("reconnectDelay:",o),i&&setTimeout(m,o)},m=()=>{g("connect");let p=n;n=new u.constructor(l,t),a=setTimeout(()=>{g("timeout"),n.close(),d("ETIMEDOUT","Connection timeout")},u.connectionTimeout),g("bypass properties");for(let y in n)["addEventListener","removeEventListener","close","send"].indexOf(y)<0&&Ve(n,this,y);n.addEventListener("open",()=>{clearTimeout(a),g("open"),o=he(u),g("reconnectDelay:",o),c=0}),n.addEventListener("close",s),Je(n,p,r)};g("init"),m(),this.close=(p=1e3,y="",{keepClosed:b=!1,fastClose:T=!0,delay:v=0}={})=>{if(v&&(o=v),i=!b,n.close(p,y),T){let x={code:p,reason:y,wasClean:!0};s(),Array.isArray(r.close)&&r.close.forEach(([U,I])=>{U(x),n.removeEventListener("close",U,I)}),n.onclose&&(n.onclose(x),n.onclose=null)}},this.send=p=>{n.send(p)},this.addEventListener=(p,y,b)=>{Array.isArray(r[p])?r[p].some(([T])=>T===y)||r[p].push([y,b]):r[p]=[[y,b]],n.addEventListener(p,y,b)},this.removeEventListener=(p,y,b)=>{Array.isArray(r[p])&&(r[p]=r[p].filter(([T])=>T!==y)),n.removeEventListener(p,y,b)}};Te.exports=be});var Qe={};Fe(Qe,{EControlMode:()=>j,EModelArchitecture:()=>oe,EModelConditioning:()=>le,EModelFormat:()=>ae,EModelType:()=>ie,EOpenPosePreProcessor:()=>re,EPhotoMakerEnum:()=>ce,EPreProcessor:()=>J,EPreProcessorGroup:()=>z,ETaskType:()=>P,Environment:()=>V,Runware:()=>Z,RunwareClient:()=>M,RunwareServer:()=>O,SdkType:()=>K});module.exports=Ge(Qe);var V=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))(V||{}),K=(e=>(e.CLIENT="CLIENT",e.SERVER="SERVER",e))(K||{}),P=(s=>(s.IMAGE_INFERENCE="imageInference",s.IMAGE_UPLOAD="imageUpload",s.IMAGE_UPSCALE="imageUpscale",s.IMAGE_BACKGROUND_REMOVAL="imageBackgroundRemoval",s.IMAGE_CAPTION="imageCaption",s.IMAGE_CONTROL_NET_PRE_PROCESS="imageControlNetPreProcess",s.PROMPT_ENHANCE="promptEnhance",s.AUTHENTICATION="authentication",s.MODEL_UPLOAD="modelUpload",s.PHOTO_MAKER="photoMaker",s.MODEL_SEARCH="modelSearch",s.IMAGE_MASKING="imageMasking",s))(P||{}),j=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(j||{}),z=(s=>(s.canny="canny",s.depth="depth",s.mlsd="mlsd",s.normalbae="normalbae",s.openpose="openpose",s.tile="tile",s.seg="seg",s.lineart="lineart",s.lineart_anime="lineart_anime",s.shuffle="shuffle",s.scribble="scribble",s.softedge="softedge",s))(z||{}),J=(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))(J||{}),re=(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))(re||{}),ae=(e=>(e.safetensors="safetensors",e.pickletensor="pickletensor",e))(ae||{}),oe=(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))(oe||{}),ie=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))(ie||{}),le=(I=>(I.canny="canny",I.depth="depth",I.qrcode="qrcode",I.hed="hed",I.scrible="scrible",I.openpose="openpose",I.seg="segmentation",I.openmlsd="openmlsd",I.softedge="softedge",I.normal="normal bae",I.shuffle="shuffle",I.pix2pix="pix2pix",I.inpaint="inpaint",I.lineart="line art",I.sketch="sketch",I.inpaintdepth="inpaint depth",I.tile="tile",I.outfit="outfit",I.blur="blur",I.gray="gray",I.lowquality="low quality",I))(le||{}),ce=(d=>(d.NoStyle="No style",d.Cinematic="Cinematic",d.DisneyCharacter="Disney Character",d.DigitalArt="Digital Art",d.Photographic="Photographic",d.FantasyArt="Fantasy art",d.Neonpunk="Neonpunk",d.Enhance="Enhance",d.ComicBook="Comic book",d.Lowpoly="Lowpoly",d.LineArt="Line art",d))(ce||{});var W=require("uuid"),Q=6e4,ue=1e3,Be=100,Y={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},ge=(l,t)=>{if(l==null)return;let e=l.indexOf(t);e!==-1&&l.splice(e,1)},D=(l,{debugKey:t="debugKey",timeoutDuration:e=Q,shouldThrowError:n=!0})=>(e=e<ue?ue:e,new Promise((a,o)=>{let c=setTimeout(()=>{i&&(clearInterval(i),n&&o(`Response could not be received from server for ${t}`)),clearTimeout(c)},e),i=setInterval(async()=>{l({resolve:a,reject:o,intervalId:i})&&(clearInterval(i),clearTimeout(c))},Be)})),de=l=>new Promise(t=>{let e=new FileReader;e.readAsDataURL(l),e.onload=function(){t(e.result)}}),_=()=>(0,W.v4)(),pe=l=>(0,W.validate)(l);var me=({key:l,data:t,useZero:e=!0,shouldReturnString:n=!1})=>l.split(/\.|\[/).map(c=>c.replace(/\]$/,"")).reduce((c,i)=>{let r=e?0:void 0,u=c?.[i];if(!u)return r;if(Array.isArray(u)&&/^\d+$/.test(i)){let g=parseInt(i,10);return g>=0&&g<u.length?c[i]=u[g]:c[i]??r}else return c[i]??r},t||{})??{},ye=(l,t=1e3)=>new Promise(e=>setTimeout(e,l*t));var Ie=(l,t)=>l.filter(e=>e.key!==t.key);var h=({key:l,value:t})=>t||t===0||t===!1?{[l]:t}:{};var k=async(l,t={})=>{let{delayInSeconds:e=1,callback:n}=t,a=t.maxRetries??1;for(;a;)try{return await l()}catch(o){if(n?.(),a--,a>0)await ye(e),await k(l,{...t,maxRetries:a});else throw o}};var S=class{constructor({apiKey:t,url:e=Y.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:a=2,timeoutDuration:o=Q}){this._listeners=[];this._globalMessages={};this._globalImages=[];this.isWebsocketReadyState=()=>this._ws?.readyState===1;this.send=t=>{this._ws.send(JSON.stringify([t]))};this.uploadImage=async t=>{try{return await k(async()=>{let e=_();if(typeof t=="string"&&pe(t))return{imageURL:t,imageUUID:t,taskUUID:e,taskType:"imageUpload"};let n=typeof t=="string"?t:await de(t);return{imageURL:n,imageUUID:n,taskUUID:e,taskType:"imageUpload"}})}catch(e){throw e}};this.controlNetPreProcess=async({inputImage:t,preProcessorType:e,height:n,width:a,outputType:o,outputFormat:c,highThresholdCanny:i,lowThresholdCanny:r,includeHandsAndFaceOpenPose:u,includeCost:g,customTaskUUID:d,retry:s})=>{let m=s||this._globalMaxRetries,p;try{return await k(async()=>{await this.ensureConnection();let y=await this.uploadImage(t);if(!y?.imageUUID)return null;let b=d||_();this.send({inputImage:y.imageUUID,taskType:"imageControlNetPreProcess",taskUUID:b,preProcessorType:e,...h({key:"height",value:n}),...h({key:"width",value:a}),...h({key:"outputType",value:o}),...h({key:"outputFormat",value:c}),...h({key:"includeCost",value:g}),...h({key:"highThresholdCanny",value:i}),...h({key:"lowThresholdCanny",value:r}),...h({key:"includeHandsAndFaceOpenPose",value:u})}),p=this.globalListener({taskUUID:b});let T=await D(({resolve:v,reject:x})=>{let U=this.getSingleMessage({taskUUID:b});if(U){if(U?.error)return x(U),!0;if(U)return v(U),!0}},{debugKey:"unprocessed-image",timeoutDuration:this._timeoutDuration});return p.destroy(),T},{maxRetries:m,callback:()=>{p?.destroy()}})}catch(y){throw y}};this.requestImageToText=async({inputImage:t,includeCost:e,customTaskUUID:n,retry:a})=>{let o=a||this._globalMaxRetries,c;try{return await k(async()=>{await this.ensureConnection();let i=t?await this.uploadImage(t):null,r=n||_();this.send({taskUUID:r,taskType:"imageCaption",inputImage:i?.imageUUID,...h({key:"includeCost",value:e})}),c=this.globalListener({taskUUID:r});let u=await D(({resolve:g,reject:d})=>{let s=this.getSingleMessage({taskUUID:r});if(s){if(s?.error)return d(s),!0;if(s)return delete this._globalMessages[r],g(s),!0}},{debugKey:"remove-image-background",timeoutDuration:this._timeoutDuration});return c.destroy(),u},{maxRetries:o,callback:()=>{c?.destroy()}})}catch(i){throw i}};this.removeImageBackground=async({inputImage:t,outputType:e,outputFormat:n,rgba:a,postProcessMask:o,returnOnlyMask:c,alphaMatting:i,alphaMattingForegroundThreshold:r,alphaMattingBackgroundThreshold:u,alphaMattingErodeSize:g,includeCost:d,customTaskUUID:s,retry:m})=>{let p=m||this._globalMaxRetries,y;try{return await k(async()=>{await this.ensureConnection();let b=t?await this.uploadImage(t):null,T=s||_();this.send({taskType:"imageBackgroundRemoval",taskUUID:T,inputImage:b?.imageUUID,...h({key:"rgba",value:a}),...h({key:"postProcessMask",value:o}),...h({key:"returnOnlyMask",value:c}),...h({key:"alphaMatting",value:i}),...h({key:"includeCost",value:d}),...h({key:"alphaMattingForegroundThreshold",value:r}),...h({key:"alphaMattingBackgroundThreshold",value:u}),...h({key:"alphaMattingErodeSize",value:g}),...h({key:"outputType",value:e}),...h({key:"outputFormat",value:n})}),y=this.globalListener({taskUUID:T});let v=await D(({resolve:x,reject:U})=>{let I=this.getSingleMessage({taskUUID:T});if(I){if(I?.error)return U(I),!0;if(I)return delete this._globalMessages[T],x(I),!0}},{debugKey:"remove-image-background",timeoutDuration:this._timeoutDuration});return y.destroy(),v},{maxRetries:p,callback:()=>{y?.destroy()}})}catch(b){throw b}};this.upscaleGan=async({inputImage:t,upscaleFactor:e,outputType:n,outputFormat:a,includeCost:o,customTaskUUID:c,retry:i})=>{let r=i||this._globalMaxRetries,u;try{return await k(async()=>{await this.ensureConnection();let g;g=await this.uploadImage(t);let d=c||_();this.send({taskUUID:d,inputImage:g?.imageUUID,taskType:"imageUpscale",upscaleFactor:e,...h({key:"includeCost",value:o}),...n?{outputType:n}:{},...a?{outputFormat:a}:{}}),u=this.globalListener({taskUUID:d});let s=await D(({resolve:m,reject:p})=>{let y=this.getSingleMessage({taskUUID:d});if(y){if(y?.error)return p(y),!0;if(y)return delete this._globalMessages[d],m(y),!0}},{debugKey:"upscale-gan",timeoutDuration:this._timeoutDuration});return u.destroy(),s},{maxRetries:r,callback:()=>{u?.destroy()}})}catch(g){throw g}};this.enhancePrompt=async({prompt:t,promptMaxLength:e=380,promptVersions:n=1,includeCost:a,customTaskUUID:o,retry:c})=>{let i=c||this._globalMaxRetries,r;try{return await k(async()=>{await this.ensureConnection();let u=o||_();this.send({prompt:t,taskUUID:u,promptMaxLength:e,promptVersions:n,...h({key:"includeCost",value:a}),taskType:"promptEnhance"}),r=this.globalListener({taskUUID:u});let g=await D(({resolve:d,reject:s})=>{let m=this._globalMessages[u];if(m?.error)return s(m),!0;if(m?.length>=n)return delete this._globalMessages[u],d(m),!0},{debugKey:"enhance-prompt",timeoutDuration:this._timeoutDuration});return r.destroy(),g},{maxRetries:i,callback:()=>{r?.destroy()}})}catch(u){throw u}};this.modelUpload=async t=>{let{onUploadStream:e,retry:n,customTaskUUID:a,...o}=t,c=n||this._globalMaxRetries,i;try{return await k(async()=>{await this.ensureConnection();let r=a||_();this.send({...o,taskUUID:r,taskType:"modelUpload"});let u,g;return i=this.listenToUpload({taskUUID:r,onUploadStream:(s,m)=>{e?.(s,m),s?.status==="ready"?u=s:m&&(g=m)}}),await D(({resolve:s,reject:m})=>{if(u)return s(u),!0;if(g)return m(g),!1},{shouldThrowError:!1,timeoutDuration:60*60*1e3})},{maxRetries:c,callback:()=>{i?.destroy()}})}catch(r){throw r}};this.photoMaker=async t=>{let{onPartialImages:e,retry:n,customTaskUUID:a,numberResults:o,...c}=t,i=n||this._globalMaxRetries,r,u=[],g=0;try{return await k(async()=>{await this.ensureConnection(),g++;let d=this._globalImages.filter(y=>u.includes(y.taskUUID)),s=a||_();u.push(s);let m=o-d.length;this.send({...c,numberResults:m,taskUUID:s,taskType:"photoMaker"}),r=this.listenToImages({onPartialImages:e,taskUUID:s,groupKey:"REQUEST_IMAGES",positivePrompt:c.positivePrompt});let p=await this.getSimilarImages({taskUUID:u,numberResults:o,lis:r});return r.destroy(),p},{maxRetries:i,callback:()=>{r?.destroy()}})}catch(d){if(d.taskUUID)throw d;if(g>=i)return this.handleIncompleteImages({taskUUIDs:u,error:d})}};this.modelSearch=async t=>this.baseSingleRequest({payload:{...t,extra:!0,taskType:"modelSearch"},debugKey:"model-search"});this.imageMasking=async t=>this.baseSingleRequest({payload:{...t,taskType:"imageMasking"},debugKey:"image-masking"});this.baseSingleRequest=async({payload:t,debugKey:e})=>{let{retry:n,customTaskUUID:a,...o}=t,c=n||this._globalMaxRetries,i;try{return await k(async()=>{await this.ensureConnection();let r=a||_();this.send({...o,taskUUID:r}),i=this.globalListener({taskUUID:r});let u=await D(({resolve:g,reject:d})=>{let s=this.getSingleMessage({taskUUID:r});if(s){if(s?.error)return d(s),!0;if(s)return delete this._globalMessages[r],g(s),!0}},{debugKey:e,timeoutDuration:this._timeoutDuration});return i.destroy(),u},{maxRetries:c,callback:()=>{i?.destroy()}})}catch(r){throw r}};this.getSingleMessage=({taskUUID:t})=>{let e=this._globalMessages[t]?.[0],n=this._globalMessages[t];return!e&&!n?null:n?.error?n:e};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=a,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 a=i=>{let r=Array.isArray(i?.data)?i.data:[i.data],u=i?.[0]?.errors?i?.[0]?.errors:Array.isArray(i?.errors)?i.errors:[i.errors],g=r.filter(s=>(s?.taskUUID||s?.taskType)===n);if(u.filter(s=>(s?.taskUUID||s?.taskType)===n).length){t({error:{...u[0]??{}}});return}if(g.length){t({[n]:r});return}},o={key:n||_(),listener:a,groupKey:e};return this._listeners.push(o),{destroy:()=>{this._listeners=Ie(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._invalidAPIkey=e;return}this._connectionSessionUUID=e?.authentication?.[0]?.connectionSessionUUID,this._invalidAPIkey=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._invalidAPIkey}}destroy(t){ge(this._listeners,t)}listenToImages({onPartialImages:t,taskUUID:e,groupKey:n,positivePrompt:a,negativePrompt:o}){return this.addListener({taskUUID:e,lis:c=>{let i=c?.[e]?.filter(r=>r.taskUUID===e);c.error?(t?.(i,c?.error&&c),this._globalError=c):(i=i.map(r=>({...r,positivePrompt:a,negativePrompt:o})),t?.(i,c?.error&&c),this._sdkType==="CLIENT"?this._globalImages=[...this._globalImages,...(c?.[e]??[]).map(r=>({...r,positivePrompt:a,negativePrompt:o}))]:this._globalImages=[...this._globalImages,...i])},groupKey:n})}listenToUpload({onUploadStream:t,taskUUID:e}){return this.addListener({taskUUID:e,lis:n=>{let a=n?.error,o=n?.[e]?.[0],c=o?.taskUUID===e?o:null;(c||a)&&t?.(c||void 0,a)}})}globalListener({taskUUID:t}){return this.addListener({taskUUID:t,lis:e=>{if(e.error){this._globalMessages[t]=e;return}let n=me({key:t,data:e,useZero:!1});Array.isArray(n)?n.forEach(a=>{this._globalMessages[a.taskUUID]=[...this._globalMessages[a.taskUUID]??[],a]}):this._globalMessages[n.taskUUID]=n}})}async requestImages({outputType:t,outputFormat:e,uploadEndpoint:n,checkNSFW:a,positivePrompt:o,negativePrompt:c,seedImage:i,maskImage:r,strength:u,height:g,width:d,model:s,steps:m,scheduler:p,seed:y,CFGScale:b,clipSkip:T,usePromptWeighting:v,promptWeighting:x,numberResults:U=1,controlNet:I,lora:$,onPartialImages:Re,includeCost:xe,customTaskUUID:De,retry:ve,refiner:f,maskMargin:we}){let A,X,N=[],ee=0,te=ve||this._globalMaxRetries;try{await this.ensureConnection();let w=null,F=null,G=[];if(i){let R=await this.uploadImage(i);if(!R)return[];w=R.imageUUID}if(r){let R=await this.uploadImage(r);if(!R)return[];F=R.imageUUID}if(I?.length)for(let R=0;R<I.length;R++){let C=I[R],{endStep:B,startStep:q,weight:H,guideImage:L,controlMode:Se,startStepPercentage:Ae,endStepPercentage:Ce,model:Me}=C,Oe=L?await this.uploadImage(L):null;G.push({guideImage:Oe?.imageUUID,model:Me,endStep:B,startStep:q,weight:H,...h({key:"startStepPercentage",value:Ae}),...h({key:"endStepPercentage",value:Ce}),controlMode:Se||"controlnet"})}return X={taskType:"imageInference",model:s,positivePrompt:o,...c?{negativePrompt:c}:{},...g?{height:g}:{},...d?{width:d}:{},numberResults:U,...$?.length?{lora:$}:{},...t?{outputType:t}:{},...e?{outputFormat:e}:{},...n?{uploadEndpoint:n}:{},...h({key:"checkNSFW",value:a}),...h({key:"strength",value:u}),...h({key:"CFGScale",value:b}),...h({key:"clipSkip",value:T}),...h({key:"maskMargin",value:we}),...h({key:"usePromptWeighting",value:v}),...h({key:"steps",value:m}),...x?{promptWeighting:x}:{},...G.length?{controlNet:G}:{},...y?{seed:y}:{},...p?{scheduler:p}:{},...f?{refiner:f}:{},...h({key:"includeCost",value:xe}),...w?{seedImage:w}:{},...F?{maskImage:F}:{}},await k(async()=>{ee++,A?.destroy();let R=this._globalImages.filter(L=>N.includes(L.taskUUID)),C=De||_();N.push(C);let B=U-R.length,q={...X,taskUUID:C,numberResults:B};this.send(q),A=this.listenToImages({onPartialImages:Re,taskUUID:C,groupKey:"REQUEST_IMAGES",positivePrompt:o,negativePrompt:c});let H=await this.getSimilarImages({taskUUID:N,numberResults:U,lis:A});return A.destroy(),H},{maxRetries:te,callback:()=>{A?.destroy()}})}catch(w){if(w.taskUUID)throw w;if(ee>=te)return this.handleIncompleteImages({taskUUIDs:N,error:w})}}async ensureConnection(){if(this.connected()||this._url===Y.TEST)return;let e=2e3,n=200;try{if(this._invalidAPIkey)throw this._invalidAPIkey;return new Promise((a,o)=>{let c=0,i=30,r=c%10===0,u,g,d=()=>{clearInterval(u),clearInterval(g)};this._sdkType==="SERVER"&&(u=setInterval(async()=>{try{this.connected()?(d(),a(!0)):c>=i?(d(),o(new Error("Retry timed out"))):(r&&this.connect(),c++)}catch(s){d(),o(s)}},e)),g=setInterval(async()=>{if(this.connected()){d(),a(!0);return}if(this._invalidAPIkey){d(),o(this._invalidAPIkey);return}},n)})}catch{throw this._invalidAPIkey??"Could not connect to server. Ensure your API key is correct"}}async getSimilarImages({taskUUID:t,numberResults:e,shouldThrowError:n,lis:a}){return await D(({resolve:o,reject:c,intervalId:i})=>{let r=Array.isArray(t)?t:[t],u=this._globalImages.filter(g=>r.includes(g.taskUUID));if(this._globalError){let g=this._globalError;return this._globalError=void 0,clearInterval(i),c?.(g),!0}else if(u.length>=e)return clearInterval(i),this._globalImages=this._globalImages.filter(g=>!r.includes(g.taskUUID)),o([...u].slice(0,e)),!0},{debugKey:"getting images",shouldThrowError:n,timeoutDuration:this._timeoutDuration})}handleIncompleteImages({taskUUIDs:t,error:e}){let n=this._globalImages.filter(a=>t.includes(a.taskUUID));if(n.length>1)return this._globalImages=this._globalImages.filter(a=>!t.includes(a.taskUUID)),n;throw e}};var _e=se(Ue(),1),M=class extends S{constructor(t){let{shouldReconnect:e,...n}=t;super(n),this._ws=new _e.default(this._url),this.connect()}};var ke=se(require("ws"),1);var O=class extends S{constructor(e){super(e);this._instantiated=!1;this._listeners=[];this._reconnectingIntervalId=null;this.send=e=>{this._ws.send(JSON.stringify([e]))};this.resetConnection=()=>{this._ws&&(this._listeners.forEach(e=>{e?.destroy?.()}),this._ws.removeAllListeners(),this._ws.readyState===1&&(this._ws.terminate(),this._ws.close()),this._ws=null,this._listeners=[])};this._sdkType="SERVER",this.connect()}async connect(){this._url&&(this.resetConnection(),this._ws=new ke.default(this._url,{perMessageDeflate:!1}),this._ws.on("error",()=>{}),this._ws.on("close",()=>{this.handleClose()}),this._ws.on("open",()=>{this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._connectionSessionUUID&&this.isWebsocketReadyState()?this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.isWebsocketReadyState()&&this.send({apiKey:this._apiKey,taskType:"authentication"}),this.addListener({taskUUID:"authentication",lis:e=>{if(e?.error){this._invalidAPIkey=e;return}this._connectionSessionUUID=e?.authentication?.[0]?.connectionSessionUUID,this._invalidAPIkey=void 0}})}),this._ws.on("message",(e,n)=>{let a=n?e:e?.toString();if(!a)return;let o=JSON.parse(a);this._listeners.forEach(c=>{c.listener(o)})}))}handleClose(){this._invalidAPIkey||(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 Z;typeof window>"u"?Z=O:Z=M;0&&(module.exports={EControlMode,EModelArchitecture,EModelConditioning,EModelFormat,EModelType,EOpenPosePreProcessor,EPhotoMakerEnum,EPreProcessor,EPreProcessorGroup,ETaskType,Environment,Runware,RunwareClient,RunwareServer,SdkType});
|
|
1
|
+
"use strict";var Le=Object.create;var E=Object.defineProperty;var Ee=Object.getOwnPropertyDescriptor;var Ke=Object.getOwnPropertyNames;var Pe=Object.getPrototypeOf,We=Object.prototype.hasOwnProperty;var Fe=(l,t)=>()=>(t||l((t={exports:{}}).exports,t),t.exports),Ge=(l,t)=>{for(var e in t)E(l,e,{get:t[e],enumerable:!0})},ne=(l,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Ke(t))!We.call(l,a)&&a!==e&&E(l,a,{get:()=>t[a],enumerable:!(n=Ee(t,a))||n.enumerable});return l};var se=(l,t,e)=>(e=l!=null?Le(Pe(l)):{},ne(t||!l||!l.__esModule?E(e,"default",{value:l,enumerable:!0}):e,l)),Be=l=>ne(E({},"__esModule",{value:!0}),l);var Te=Fe((Wt,Ue)=>{"use strict";var fe=l=>l&&l.CLOSING===2,He=()=>typeof WebSocket<"u"&&fe(WebSocket),Ve=()=>({constructor:He()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),je=(l,t,e)=>{Object.defineProperty(t,e,{get:()=>l[e],set:n=>{l[e]=n},enumerable:!0,configurable:!0})},he=l=>l.minReconnectionDelay+Math.random()*l.minReconnectionDelay,ze=(l,t)=>{let e=t*l.reconnectionDelayGrowFactor;return e>l.maxReconnectionDelay?l.maxReconnectionDelay:e},Je=["onopen","onclose","onmessage","onerror"],Qe=(l,t,e)=>{Object.keys(e).forEach(n=>{e[n].forEach(([a,o])=>{l.addEventListener(n,a,o)})}),t&&Je.forEach(n=>{l[n]=t[n]})},be=function(l,t,e={}){let n,a,o=0,u=0,i=!0,r={};if(!(this instanceof be))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let c=Ve();if(Object.keys(c).filter(p=>e.hasOwnProperty(p)).forEach(p=>c[p]=e[p]),!fe(c.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");let g=c.debug?(...p)=>console.log("RWS:",...p):()=>{},d=(p,y)=>setTimeout(()=>{let b=new Error(y);b.code=p,Array.isArray(r.error)&&r.error.forEach(([U])=>U(b)),n.onerror&&n.onerror(b)},0),s=()=>{if(g("close"),u++,g("retries count:",u),u>c.maxRetries){d("EHOSTDOWN","Too many failed connection attempts");return}o?o=ze(c,o):o=he(c),g("reconnectDelay:",o),i&&setTimeout(m,o)},m=()=>{g("connect");let p=n;n=new c.constructor(l,t),a=setTimeout(()=>{g("timeout"),n.close(),d("ETIMEDOUT","Connection timeout")},c.connectionTimeout),g("bypass properties");for(let y in n)["addEventListener","removeEventListener","close","send"].indexOf(y)<0&&je(n,this,y);n.addEventListener("open",()=>{clearTimeout(a),g("open"),o=he(c),g("reconnectDelay:",o),u=0}),n.addEventListener("close",s),Qe(n,p,r)};g("init"),m(),this.close=(p=1e3,y="",{keepClosed:b=!1,fastClose:U=!0,delay:v=0}={})=>{if(v&&(o=v),i=!b,n.close(p,y),U){let D={code:p,reason:y,wasClean:!0};s(),Array.isArray(r.close)&&r.close.forEach(([T,I])=>{T(D),n.removeEventListener("close",T,I)}),n.onclose&&(n.onclose(D),n.onclose=null)}},this.send=p=>{n.send(p)},this.addEventListener=(p,y,b)=>{Array.isArray(r[p])?r[p].some(([U])=>U===y)||r[p].push([y,b]):r[p]=[[y,b]],n.addEventListener(p,y,b)},this.removeEventListener=(p,y,b)=>{Array.isArray(r[p])&&(r[p]=r[p].filter(([U])=>U!==y)),n.removeEventListener(p,y,b)}};Ue.exports=be});var Ye={};Ge(Ye,{EControlMode:()=>j,EModelArchitecture:()=>oe,EModelConditioning:()=>le,EModelFormat:()=>ae,EModelType:()=>ie,EOpenPosePreProcessor:()=>re,EPhotoMakerEnum:()=>ue,EPreProcessor:()=>J,EPreProcessorGroup:()=>z,ETaskType:()=>P,Environment:()=>V,Runware:()=>Z,RunwareClient:()=>M,RunwareServer:()=>O,SdkType:()=>K});module.exports=Be(Ye);var V=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))(V||{}),K=(e=>(e.CLIENT="CLIENT",e.SERVER="SERVER",e))(K||{}),P=(s=>(s.IMAGE_INFERENCE="imageInference",s.IMAGE_UPLOAD="imageUpload",s.IMAGE_UPSCALE="imageUpscale",s.IMAGE_BACKGROUND_REMOVAL="imageBackgroundRemoval",s.IMAGE_CAPTION="imageCaption",s.IMAGE_CONTROL_NET_PRE_PROCESS="imageControlNetPreProcess",s.PROMPT_ENHANCE="promptEnhance",s.AUTHENTICATION="authentication",s.MODEL_UPLOAD="modelUpload",s.PHOTO_MAKER="photoMaker",s.MODEL_SEARCH="modelSearch",s.IMAGE_MASKING="imageMasking",s))(P||{}),j=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(j||{}),z=(s=>(s.canny="canny",s.depth="depth",s.mlsd="mlsd",s.normalbae="normalbae",s.openpose="openpose",s.tile="tile",s.seg="seg",s.lineart="lineart",s.lineart_anime="lineart_anime",s.shuffle="shuffle",s.scribble="scribble",s.softedge="softedge",s))(z||{}),J=(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))(J||{}),re=(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))(re||{}),ae=(e=>(e.safetensors="safetensors",e.pickletensor="pickletensor",e))(ae||{}),oe=(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))(oe||{}),ie=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))(ie||{}),le=(I=>(I.canny="canny",I.depth="depth",I.qrcode="qrcode",I.hed="hed",I.scrible="scrible",I.openpose="openpose",I.seg="segmentation",I.openmlsd="openmlsd",I.softedge="softedge",I.normal="normal bae",I.shuffle="shuffle",I.pix2pix="pix2pix",I.inpaint="inpaint",I.lineart="line art",I.sketch="sketch",I.inpaintdepth="inpaint depth",I.tile="tile",I.outfit="outfit",I.blur="blur",I.gray="gray",I.lowquality="low quality",I))(le||{}),ue=(d=>(d.NoStyle="No style",d.Cinematic="Cinematic",d.DisneyCharacter="Disney Character",d.DigitalArt="Digital Art",d.Photographic="Photographic",d.FantasyArt="Fantasy art",d.Neonpunk="Neonpunk",d.Enhance="Enhance",d.ComicBook="Comic book",d.Lowpoly="Lowpoly",d.LineArt="Line art",d))(ue||{});var W=require("uuid"),Q=6e4,ce=1e3,qe=100,Y={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},ge=(l,t)=>{if(l==null)return;let e=l.indexOf(t);e!==-1&&l.splice(e,1)},x=(l,{debugKey:t="debugKey",timeoutDuration:e=Q,shouldThrowError:n=!0})=>(e=e<ce?ce:e,new Promise((a,o)=>{let u=setTimeout(()=>{i&&(clearInterval(i),n&&o(`Response could not be received from server for ${t}`)),clearTimeout(u)},e),i=setInterval(async()=>{l({resolve:a,reject:o,intervalId:i})&&(clearInterval(i),clearTimeout(u))},qe)})),de=l=>new Promise(t=>{let e=new FileReader;e.readAsDataURL(l),e.onload=function(){t(e.result)}}),_=()=>(0,W.v4)(),pe=l=>(0,W.validate)(l);var me=({key:l,data:t,useZero:e=!0,shouldReturnString:n=!1})=>l.split(/\.|\[/).map(u=>u.replace(/\]$/,"")).reduce((u,i)=>{let r=e?0:void 0,c=u?.[i];if(!c)return r;if(Array.isArray(c)&&/^\d+$/.test(i)){let g=parseInt(i,10);return g>=0&&g<c.length?u[i]=c[g]:u[i]??r}else return u[i]??r},t||{})??{},ye=(l,t=1e3)=>new Promise(e=>setTimeout(e,l*t));var Ie=(l,t)=>l.filter(e=>e.key!==t.key);var h=({key:l,value:t})=>t||t===0||t===!1?{[l]:t}:{};var k=async(l,t={})=>{let{delayInSeconds:e=1,callback:n}=t,a=t.maxRetries??1;for(;a;)try{return await l()}catch(o){if(n?.(),a--,a>0)await ye(e),await k(l,{...t,maxRetries:a});else throw o}};var S=class{constructor({apiKey:t,url:e=Y.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:a=2,timeoutDuration:o=Q}){this._listeners=[];this._globalMessages={};this._globalImages=[];this.ensureConnectionUUID=null;this.isWebsocketReadyState=()=>this._ws?.readyState===1;this.send=t=>{this._ws.send(JSON.stringify([t]))};this.uploadImage=async t=>{try{return await k(async()=>{let e=_();if(typeof t=="string"&&pe(t))return{imageURL:t,imageUUID:t,taskUUID:e,taskType:"imageUpload"};let n=typeof t=="string"?t:await de(t);return{imageURL:n,imageUUID:n,taskUUID:e,taskType:"imageUpload"}})}catch(e){throw e}};this.controlNetPreProcess=async({inputImage:t,preProcessorType:e,height:n,width:a,outputType:o,outputFormat:u,highThresholdCanny:i,lowThresholdCanny:r,includeHandsAndFaceOpenPose:c,includeCost:g,customTaskUUID:d,retry:s})=>{let m=s||this._globalMaxRetries,p;try{return await k(async()=>{await this.ensureConnection();let y=await this.uploadImage(t);if(!y?.imageUUID)return null;let b=d||_();this.send({inputImage:y.imageUUID,taskType:"imageControlNetPreProcess",taskUUID:b,preProcessorType:e,...h({key:"height",value:n}),...h({key:"width",value:a}),...h({key:"outputType",value:o}),...h({key:"outputFormat",value:u}),...h({key:"includeCost",value:g}),...h({key:"highThresholdCanny",value:i}),...h({key:"lowThresholdCanny",value:r}),...h({key:"includeHandsAndFaceOpenPose",value:c})}),p=this.globalListener({taskUUID:b});let U=await x(({resolve:v,reject:D})=>{let T=this.getSingleMessage({taskUUID:b});if(T){if(T?.error)return D(T),!0;if(T)return v(T),!0}},{debugKey:"unprocessed-image",timeoutDuration:this._timeoutDuration});return p.destroy(),U},{maxRetries:m,callback:()=>{p?.destroy()}})}catch(y){throw y}};this.requestImageToText=async({inputImage:t,includeCost:e,customTaskUUID:n,retry:a})=>{let o=a||this._globalMaxRetries,u;try{return await k(async()=>{await this.ensureConnection();let i=t?await this.uploadImage(t):null,r=n||_();this.send({taskUUID:r,taskType:"imageCaption",inputImage:i?.imageUUID,...h({key:"includeCost",value:e})}),u=this.globalListener({taskUUID:r});let c=await x(({resolve:g,reject:d})=>{let s=this.getSingleMessage({taskUUID:r});if(s){if(s?.error)return d(s),!0;if(s)return delete this._globalMessages[r],g(s),!0}},{debugKey:"remove-image-background",timeoutDuration:this._timeoutDuration});return u.destroy(),c},{maxRetries:o,callback:()=>{u?.destroy()}})}catch(i){throw i}};this.removeImageBackground=async({inputImage:t,outputType:e,outputFormat:n,rgba:a,postProcessMask:o,returnOnlyMask:u,alphaMatting:i,alphaMattingForegroundThreshold:r,alphaMattingBackgroundThreshold:c,alphaMattingErodeSize:g,includeCost:d,customTaskUUID:s,retry:m})=>{let p=m||this._globalMaxRetries,y;try{return await k(async()=>{await this.ensureConnection();let b=t?await this.uploadImage(t):null,U=s||_();this.send({taskType:"imageBackgroundRemoval",taskUUID:U,inputImage:b?.imageUUID,...h({key:"rgba",value:a}),...h({key:"postProcessMask",value:o}),...h({key:"returnOnlyMask",value:u}),...h({key:"alphaMatting",value:i}),...h({key:"includeCost",value:d}),...h({key:"alphaMattingForegroundThreshold",value:r}),...h({key:"alphaMattingBackgroundThreshold",value:c}),...h({key:"alphaMattingErodeSize",value:g}),...h({key:"outputType",value:e}),...h({key:"outputFormat",value:n})}),y=this.globalListener({taskUUID:U});let v=await x(({resolve:D,reject:T})=>{let I=this.getSingleMessage({taskUUID:U});if(I){if(I?.error)return T(I),!0;if(I)return delete this._globalMessages[U],D(I),!0}},{debugKey:"remove-image-background",timeoutDuration:this._timeoutDuration});return y.destroy(),v},{maxRetries:p,callback:()=>{y?.destroy()}})}catch(b){throw b}};this.upscaleGan=async({inputImage:t,upscaleFactor:e,outputType:n,outputFormat:a,includeCost:o,customTaskUUID:u,retry:i})=>{let r=i||this._globalMaxRetries,c;try{return await k(async()=>{await this.ensureConnection();let g;g=await this.uploadImage(t);let d=u||_();this.send({taskUUID:d,inputImage:g?.imageUUID,taskType:"imageUpscale",upscaleFactor:e,...h({key:"includeCost",value:o}),...n?{outputType:n}:{},...a?{outputFormat:a}:{}}),c=this.globalListener({taskUUID:d});let s=await x(({resolve:m,reject:p})=>{let y=this.getSingleMessage({taskUUID:d});if(y){if(y?.error)return p(y),!0;if(y)return delete this._globalMessages[d],m(y),!0}},{debugKey:"upscale-gan",timeoutDuration:this._timeoutDuration});return c.destroy(),s},{maxRetries:r,callback:()=>{c?.destroy()}})}catch(g){throw g}};this.enhancePrompt=async({prompt:t,promptMaxLength:e=380,promptVersions:n=1,includeCost:a,customTaskUUID:o,retry:u})=>{let i=u||this._globalMaxRetries,r;try{return await k(async()=>{await this.ensureConnection();let c=o||_();this.send({prompt:t,taskUUID:c,promptMaxLength:e,promptVersions:n,...h({key:"includeCost",value:a}),taskType:"promptEnhance"}),r=this.globalListener({taskUUID:c});let g=await x(({resolve:d,reject:s})=>{let m=this._globalMessages[c];if(m?.error)return s(m),!0;if(m?.length>=n)return delete this._globalMessages[c],d(m),!0},{debugKey:"enhance-prompt",timeoutDuration:this._timeoutDuration});return r.destroy(),g},{maxRetries:i,callback:()=>{r?.destroy()}})}catch(c){throw c}};this.modelUpload=async t=>{let{onUploadStream:e,retry:n,customTaskUUID:a,...o}=t,u=n||this._globalMaxRetries,i;try{return await k(async()=>{await this.ensureConnection();let r=a||_();this.send({...o,taskUUID:r,taskType:"modelUpload"});let c,g;return i=this.listenToUpload({taskUUID:r,onUploadStream:(s,m)=>{e?.(s,m),s?.status==="ready"?c=s:m&&(g=m)}}),await x(({resolve:s,reject:m})=>{if(c)return s(c),!0;if(g)return m(g),!1},{shouldThrowError:!1,timeoutDuration:60*60*1e3})},{maxRetries:u,callback:()=>{i?.destroy()}})}catch(r){throw r}};this.photoMaker=async t=>{let{onPartialImages:e,retry:n,customTaskUUID:a,numberResults:o,...u}=t,i=n||this._globalMaxRetries,r,c=[],g=0;try{return await k(async()=>{await this.ensureConnection(),g++;let d=this._globalImages.filter(y=>c.includes(y.taskUUID)),s=a||_();c.push(s);let m=o-d.length;this.send({...u,numberResults:m,taskUUID:s,taskType:"photoMaker"}),r=this.listenToImages({onPartialImages:e,taskUUID:s,groupKey:"REQUEST_IMAGES",positivePrompt:u.positivePrompt});let p=await this.getSimilarImages({taskUUID:c,numberResults:o,lis:r});return r.destroy(),p},{maxRetries:i,callback:()=>{r?.destroy()}})}catch(d){if(d.taskUUID)throw d;if(g>=i)return this.handleIncompleteImages({taskUUIDs:c,error:d})}};this.modelSearch=async t=>this.baseSingleRequest({payload:{...t,extra:!0,taskType:"modelSearch"},debugKey:"model-search"});this.imageMasking=async t=>this.baseSingleRequest({payload:{...t,taskType:"imageMasking"},debugKey:"image-masking"});this.baseSingleRequest=async({payload:t,debugKey:e})=>{let{retry:n,customTaskUUID:a,...o}=t,u=n||this._globalMaxRetries,i;try{return await k(async()=>{await this.ensureConnection();let r=a||_();this.send({...o,taskUUID:r}),i=this.globalListener({taskUUID:r});let c=await x(({resolve:g,reject:d})=>{let s=this.getSingleMessage({taskUUID:r});if(s){if(s?.error)return d(s),!0;if(s)return delete this._globalMessages[r],g(s),!0}},{debugKey:e,timeoutDuration:this._timeoutDuration});return i.destroy(),c},{maxRetries:u,callback:()=>{i?.destroy()}})}catch(r){throw r}};this.getSingleMessage=({taskUUID:t})=>{let e=this._globalMessages[t]?.[0],n=this._globalMessages[t];return!e&&!n?null:n?.error?n:e};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=a,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 a=i=>{let r=Array.isArray(i?.data)?i.data:[i.data],c=i?.[0]?.errors?i?.[0]?.errors:Array.isArray(i?.errors)?i.errors:[i.errors],g=r.filter(s=>(s?.taskUUID||s?.taskType)===n);if(c.filter(s=>(s?.taskUUID||s?.taskType)===n).length){t({error:{...c[0]??{}}});return}if(g.length){t({[n]:r});return}},o={key:n||_(),listener:a,groupKey:e};return this._listeners.push(o),{destroy:()=>{this._listeners=Ie(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._invalidAPIkey=e;return}this._connectionSessionUUID=e?.authentication?.[0]?.connectionSessionUUID,this._invalidAPIkey=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._invalidAPIkey}}destroy(t){ge(this._listeners,t)}listenToImages({onPartialImages:t,taskUUID:e,groupKey:n,positivePrompt:a,negativePrompt:o}){return this.addListener({taskUUID:e,lis:u=>{let i=u?.[e]?.filter(r=>r.taskUUID===e);u.error?(t?.(i,u?.error&&u),this._globalError=u):(i=i.map(r=>({...r,positivePrompt:a,negativePrompt:o})),t?.(i,u?.error&&u),this._sdkType==="CLIENT"?this._globalImages=[...this._globalImages,...(u?.[e]??[]).map(r=>({...r,positivePrompt:a,negativePrompt:o}))]:this._globalImages=[...this._globalImages,...i])},groupKey:n})}listenToUpload({onUploadStream:t,taskUUID:e}){return this.addListener({taskUUID:e,lis:n=>{let a=n?.error,o=n?.[e]?.[0],u=o?.taskUUID===e?o:null;(u||a)&&t?.(u||void 0,a)}})}globalListener({taskUUID:t}){return this.addListener({taskUUID:t,lis:e=>{if(e.error){this._globalMessages[t]=e;return}let n=me({key:t,data:e,useZero:!1});Array.isArray(n)?n.forEach(a=>{this._globalMessages[a.taskUUID]=[...this._globalMessages[a.taskUUID]??[],a]}):this._globalMessages[n.taskUUID]=n}})}async requestImages({outputType:t,outputFormat:e,uploadEndpoint:n,checkNSFW:a,positivePrompt:o,negativePrompt:u,seedImage:i,maskImage:r,strength:c,height:g,width:d,model:s,steps:m,scheduler:p,seed:y,CFGScale:b,clipSkip:U,usePromptWeighting:v,promptWeighting:D,numberResults:T=1,controlNet:I,lora:$,onPartialImages:Re,includeCost:De,customTaskUUID:xe,retry:ve,refiner:f,maskMargin:we},Se){let A,X,N=[],ee=0,te=ve||this._globalMaxRetries;try{await this.ensureConnection();let w=null,F=null,G=[];if(i){let R=await this.uploadImage(i);if(!R)return[];w=R.imageUUID}if(r){let R=await this.uploadImage(r);if(!R)return[];F=R.imageUUID}if(I?.length)for(let R=0;R<I.length;R++){let C=I[R],{endStep:B,startStep:q,weight:H,guideImage:L,controlMode:Ae,startStepPercentage:Ce,endStepPercentage:Me,model:Oe}=C,Ne=L?await this.uploadImage(L):null;G.push({guideImage:Ne?.imageUUID,model:Oe,endStep:B,startStep:q,weight:H,...h({key:"startStepPercentage",value:Ce}),...h({key:"endStepPercentage",value:Me}),controlMode:Ae||"controlnet"})}return X={taskType:"imageInference",model:s,positivePrompt:o,...u?{negativePrompt:u}:{},...g?{height:g}:{},...d?{width:d}:{},numberResults:T,...$?.length?{lora:$}:{},...t?{outputType:t}:{},...e?{outputFormat:e}:{},...n?{uploadEndpoint:n}:{},...h({key:"checkNSFW",value:a}),...h({key:"strength",value:c}),...h({key:"CFGScale",value:b}),...h({key:"clipSkip",value:U}),...h({key:"maskMargin",value:we}),...h({key:"usePromptWeighting",value:v}),...h({key:"steps",value:m}),...D?{promptWeighting:D}:{},...G.length?{controlNet:G}:{},...y?{seed:y}:{},...p?{scheduler:p}:{},...f?{refiner:f}:{},...h({key:"includeCost",value:De}),...w?{seedImage:w}:{},...F?{maskImage:F}:{},...Se??{}},await k(async()=>{ee++,A?.destroy();let R=this._globalImages.filter(L=>N.includes(L.taskUUID)),C=xe||_();N.push(C);let B=T-R.length,q={...X,taskUUID:C,numberResults:B};this.send(q),A=this.listenToImages({onPartialImages:Re,taskUUID:C,groupKey:"REQUEST_IMAGES",positivePrompt:o,negativePrompt:u});let H=await this.getSimilarImages({taskUUID:N,numberResults:T,lis:A});return A.destroy(),H},{maxRetries:te,callback:()=>{A?.destroy()}})}catch(w){if(ee>=te)return this.handleIncompleteImages({taskUUIDs:N,error:w});throw w}}async ensureConnection(){if(this.connected()||this._url===Y.TEST)return;let e=2e3,n=200;try{if(this._invalidAPIkey)throw this._invalidAPIkey;return new Promise((a,o)=>{let u=0,i=30,r=_(),c,g,d=()=>{this.ensureConnectionUUID=null,clearInterval(c),clearInterval(g)};this._sdkType==="SERVER"&&(c=setInterval(async()=>{try{let s=this.connected(),m=!1;(!this.ensureConnectionUUID||r===this.ensureConnectionUUID)&&(this.ensureConnectionUUID||(this.ensureConnectionUUID=r),m=!0);let p=u%10===0&&m;s?(d(),a(!0)):u>=i?(d(),o(new Error("Retry timed out"))):(p&&this.connect(),u++)}catch(s){d(),o(s)}},e)),g=setInterval(async()=>{if(this.connected()){d(),a(!0);return}if(this._invalidAPIkey){d(),o(this._invalidAPIkey);return}},n)})}catch{throw this.ensureConnectionUUID=null,this._invalidAPIkey??"Could not connect to server. Ensure your API key is correct"}}async getSimilarImages({taskUUID:t,numberResults:e,shouldThrowError:n,lis:a}){return await x(({resolve:o,reject:u,intervalId:i})=>{let r=Array.isArray(t)?t:[t],c=this._globalImages.filter(g=>r.includes(g.taskUUID));if(this._globalError){let g=this._globalError;return this._globalError=void 0,clearInterval(i),u?.(g),!0}else if(c.length>=e)return clearInterval(i),this._globalImages=this._globalImages.filter(g=>!r.includes(g.taskUUID)),o([...c].slice(0,e)),!0},{debugKey:"getting images",shouldThrowError:n,timeoutDuration:this._timeoutDuration})}handleIncompleteImages({taskUUIDs:t,error:e}){let n=this._globalImages.filter(a=>t.includes(a.taskUUID));if(n.length>1)return this._globalImages=this._globalImages.filter(a=>!t.includes(a.taskUUID)),n;throw e}};var _e=se(Te(),1),M=class extends S{constructor(t){let{shouldReconnect:e,...n}=t;super(n),this._ws=new _e.default(this._url),this.connect()}};var ke=se(require("ws"),1);var O=class extends S{constructor(e){super(e);this._instantiated=!1;this._listeners=[];this._reconnectingIntervalId=null;this.send=e=>{this._ws.send(JSON.stringify([e]))};this.resetConnection=()=>{this._ws&&(this._listeners.forEach(e=>{e?.destroy?.()}),this._ws.removeAllListeners(),this._ws.readyState===1&&(this._ws.terminate(),this._ws.close()),this._ws=null,this._listeners=[])};this._sdkType="SERVER",this.connect()}async connect(){this._url&&(this.resetConnection(),this._ws=new ke.default(this._url,{perMessageDeflate:!1}),this._ws.on("error",()=>{}),this._ws.on("close",()=>{this.handleClose()}),this._ws.on("open",()=>{this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._connectionSessionUUID&&this.isWebsocketReadyState()?this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.isWebsocketReadyState()&&this.send({apiKey:this._apiKey,taskType:"authentication"}),this.addListener({taskUUID:"authentication",lis:e=>{if(e?.error){this._invalidAPIkey=e;return}this._connectionSessionUUID=e?.authentication?.[0]?.connectionSessionUUID,this._invalidAPIkey=void 0}})}),this._ws.on("message",(e,n)=>{let a=n?e:e?.toString();if(!a)return;let o=JSON.parse(a);this._listeners.forEach(u=>{u.listener(o)})}))}handleClose(){this._invalidAPIkey||(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 Z;typeof window>"u"?Z=O:Z=M;0&&(module.exports={EControlMode,EModelArchitecture,EModelConditioning,EModelFormat,EModelType,EOpenPosePreProcessor,EPhotoMakerEnum,EPreProcessor,EPreProcessorGroup,ETaskType,Environment,Runware,RunwareClient,RunwareServer,SdkType});
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|