@runware/sdk-js 1.1.21-beta.1 → 1.1.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +5 -1
- package/dist/index.d.ts +5 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/readme.md +126 -0
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var Me=Object.create;var L=Object.defineProperty;var Oe=Object.getOwnPropertyDescriptor;var Ne=Object.getOwnPropertyNames;var Le=Object.getPrototypeOf,Ee=Object.prototype.hasOwnProperty;var Ke=(l,t)=>()=>(t||l((t={exports:{}}).exports,t),t.exports),Pe=(l,t)=>{for(var e in t)L(l,e,{get:t[e],enumerable:!0})},te=(l,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Ne(t))!Ee.call(l,a)&&a!==e&&L(l,a,{get:()=>t[a],enumerable:!(n=Oe(t,a))||n.enumerable});return l};var ne=(l,t,e)=>(e=l!=null?Me(Le(l)):{},te(t||!l||!l.__esModule?L(e,"default",{value:l,enumerable:!0}):e,l)),We=l=>te(L({},"__esModule",{value:!0}),l);var Te=Ke((Et,be)=>{"use strict";var he=l=>l&&l.CLOSING===2,Ge=()=>typeof WebSocket<"u"&&he(WebSocket),Be=()=>({constructor:Ge()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),qe=(l,t,e)=>{Object.defineProperty(t,e,{get:()=>l[e],set:n=>{l[e]=n},enumerable:!0,configurable:!0})},Ie=l=>l.minReconnectionDelay+Math.random()*l.minReconnectionDelay,He=(l,t)=>{let e=t*l.reconnectionDelayGrowFactor;return e>l.maxReconnectionDelay?l.maxReconnectionDelay:e},Ve=["onopen","onclose","onmessage","onerror"],je=(l,t,e)=>{Object.keys(e).forEach(n=>{e[n].forEach(([a,o])=>{l.addEventListener(n,a,o)})}),t&&Ve.forEach(n=>{l[n]=t[n]})},fe=function(l,t,e={}){let n,a,o=0,c=0,i=!0,r={};if(!(this instanceof fe))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let u=Be();if(Object.keys(u).filter(p=>e.hasOwnProperty(p)).forEach(p=>u[p]=e[p]),!he(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=He(u,o):o=Ie(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&&qe(n,this,y);n.addEventListener("open",()=>{clearTimeout(a),g("open"),o=Ie(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(([_,h])=>{_(x),n.removeEventListener("close",_,h)}),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)}};be.exports=fe});var ze={};Pe(ze,{EControlMode:()=>V,EModelArchitecture:()=>ae,EModelConditioning:()=>ie,EModelFormat:()=>re,EModelType:()=>oe,EOpenPosePreProcessor:()=>se,EPhotoMakerEnum:()=>le,EPreProcessor:()=>z,EPreProcessorGroup:()=>j,ETaskType:()=>K,Environment:()=>H,Runware:()=>Y,RunwareClient:()=>C,RunwareServer:()=>M,SdkType:()=>E});module.exports=We(ze);var H=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))(H||{}),E=(e=>(e.CLIENT="CLIENT",e.SERVER="SERVER",e))(E||{}),K=(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))(K||{}),V=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(V||{}),j=(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))(j||{}),z=(I=>(I.canny="canny",I.depth_leres="depth_leres",I.depth_midas="depth_midas",I.depth_zoe="depth_zoe",I.inpaint_global_harmonious="inpaint_global_harmonious",I.lineart_anime="lineart_anime",I.lineart_coarse="lineart_coarse",I.lineart_realistic="lineart_realistic",I.lineart_standard="lineart_standard",I.mlsd="mlsd",I.normal_bae="normal_bae",I.scribble_hed="scribble_hed",I.scribble_pidinet="scribble_pidinet",I.seg_ofade20k="seg_ofade20k",I.seg_ofcoco="seg_ofcoco",I.seg_ufade20k="seg_ufade20k",I.shuffle="shuffle",I.softedge_hed="softedge_hed",I.softedge_hedsafe="softedge_hedsafe",I.softedge_pidinet="softedge_pidinet",I.softedge_pidisafe="softedge_pidisafe",I.tile_gaussian="tile_gaussian",I.openpose="openpose",I.openpose_face="openpose_face",I.openpose_faceonly="openpose_faceonly",I.openpose_full="openpose_full",I.openpose_hand="openpose_hand",I))(z||{}),se=(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))(se||{}),re=(e=>(e.safetensors="safetensors",e.pickletensor="pickletensor",e))(re||{}),ae=(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))(ae||{}),oe=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))(oe||{}),ie=(h=>(h.canny="canny",h.depth="depth",h.qrcode="qrcode",h.hed="hed",h.scrible="scrible",h.openpose="openpose",h.seg="segmentation",h.openmlsd="openmlsd",h.softedge="softedge",h.normal="normal bae",h.shuffle="shuffle",h.pix2pix="pix2pix",h.inpaint="inpaint",h.lineart="line art",h.sketch="sketch",h.inpaintdepth="inpaint depth",h.tile="tile",h.outfit="outfit",h.blur="blur",h.gray="gray",h.lowquality="low quality",h))(ie||{}),le=(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))(le||{});var P=require("uuid"),J=6e4,ce=1e3,Fe=100,Q={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},ue=(l,t)=>{if(l==null)return;let e=l.indexOf(t);e!==-1&&l.splice(e,1)},D=(l,{debugKey:t="debugKey",timeoutDuration:e=J,shouldThrowError:n=!0})=>(e=e<ce?ce: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))},Fe)})),ge=l=>new Promise(t=>{let e=new FileReader;e.readAsDataURL(l),e.onload=function(){t(e.result)}}),U=()=>(0,P.v4)(),de=l=>(0,P.validate)(l);var pe=({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||{})??{},me=(l,t=1e3)=>new Promise(e=>setTimeout(e,l*t));var ye=(l,t)=>l.filter(e=>e.key!==t.key);var f=({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 me(e),await k(l,{...t,maxRetries:a});else throw o}};var S=class{constructor({apiKey:t,url:e=Q.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:a=2,timeoutDuration:o=J}){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=U();if(typeof t=="string"&&de(t))return{imageURL:t,imageUUID:t,taskUUID:e,taskType:"imageUpload"};let n=typeof t=="string"?t:await ge(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||U();this.send({inputImage:y.imageUUID,taskType:"imageControlNetPreProcess",taskUUID:b,preProcessorType:e,...f({key:"height",value:n}),...f({key:"width",value:a}),...f({key:"outputType",value:o}),...f({key:"outputFormat",value:c}),...f({key:"includeCost",value:g}),...f({key:"highThresholdCanny",value:i}),...f({key:"lowThresholdCanny",value:r}),...f({key:"includeHandsAndFaceOpenPose",value:u})}),p=this.globalListener({taskUUID:b});let T=await D(({resolve:v,reject:x})=>{let _=this.getSingleMessage({taskUUID:b});if(_){if(_?.error)return x(_),!0;if(_)return v(_),!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||U();this.send({taskUUID:r,taskType:"imageCaption",inputImage:i?.imageUUID,...f({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||U();this.send({taskType:"imageBackgroundRemoval",taskUUID:T,inputImage:b?.imageUUID,...f({key:"rgba",value:a}),...f({key:"postProcessMask",value:o}),...f({key:"returnOnlyMask",value:c}),...f({key:"alphaMatting",value:i}),...f({key:"includeCost",value:d}),...f({key:"alphaMattingForegroundThreshold",value:r}),...f({key:"alphaMattingBackgroundThreshold",value:u}),...f({key:"alphaMattingErodeSize",value:g}),...f({key:"outputType",value:e}),...f({key:"outputFormat",value:n})}),y=this.globalListener({taskUUID:T});let v=await D(({resolve:x,reject:_})=>{let h=this.getSingleMessage({taskUUID:T});if(h){if(h?.error)return _(h),!0;if(h)return delete this._globalMessages[T],x(h),!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||U();this.send({taskUUID:d,inputImage:g?.imageUUID,taskType:"imageUpscale",upscaleFactor:e,...f({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||U();this.send({prompt:t,taskUUID:u,promptMaxLength:e,promptVersions:n,...f({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||U();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();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||U();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||U(),listener:a,groupKey:e};return this._listeners.push(o),{destroy:()=>{this._listeners=ye(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){ue(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=pe({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,numberResults:x=1,controlNet:_,lora:h,onPartialImages:ke,includeCost:Re,customTaskUUID:xe,retry:De,refiner:Z}){let I,$,O=[],X=0,ee=De||this._globalMaxRetries;try{await this.ensureConnection();let w=null,W=null,F=[];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[];W=R.imageUUID}if(_?.length)for(let R=0;R<_.length;R++){let A=_[R],{endStep:G,startStep:B,weight:q,guideImage:N,controlMode:ve,startStepPercentage:we,endStepPercentage:Se,model:Ae}=A,Ce=N?await this.uploadImage(N):null;F.push({guideImage:Ce?.imageUUID,model:Ae,endStep:G,startStep:B,weight:q,...f({key:"startStepPercentage",value:we}),...f({key:"endStepPercentage",value:Se}),controlMode:ve||"controlnet"})}return $={taskType:"imageInference",model:s,positivePrompt:o,...c?{negativePrompt:c}:{},...g?{height:g}:{},...d?{width:d}:{},numberResults:x,...h?.length?{lora:h}:{},...t?{outputType:t}:{},...e?{outputFormat:e}:{},...n?{uploadEndpoint:n}:{},...f({key:"checkNsfw",value:a}),...f({key:"strength",value:u}),...f({key:"CFGScale",value:b}),...f({key:"clipSkip",value:T}),...f({key:"usePromptWeighting",value:v}),...f({key:"steps",value:m}),...F.length?{controlNet:F}:{},...y?{seed:y}:{},...p?{scheduler:p}:{},...Z?{refiner:Z}:{},...f({key:"includeCost",value:Re}),...w?{seedImage:w}:{},...W?{maskImage:W}:{}},await k(async()=>{X++,I?.destroy();let R=this._globalImages.filter(N=>O.includes(N.taskUUID)),A=xe||U();O.push(A);let G=x-R.length,B={...$,taskUUID:A,numberResults:G};this.send(B),I=this.listenToImages({onPartialImages:ke,taskUUID:A,groupKey:"REQUEST_IMAGES",positivePrompt:o,negativePrompt:c});let q=await this.getSimilarImages({taskUUID:O,numberResults:x,lis:I});return I.destroy(),q},{maxRetries:ee,callback:()=>{I?.destroy()}})}catch(w){if(w.taskUUID)throw w;if(X>=ee)return this.handleIncompleteImages({taskUUIDs:O,error:w})}}async ensureConnection(){if(this.connected()||this._url===Q.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=ne(Te(),1),C=class extends S{constructor(t){let{shouldReconnect:e,...n}=t;super(n),this._ws=new _e.default(this._url),this.connect()}};var Ue=ne(require("ws"),1);var M=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=>{let n;(n=e?.destroy)==null||n.call(e)}),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 Ue.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 Y;typeof window>"u"?Y=M:Y=C;0&&(module.exports={EControlMode,EModelArchitecture,EModelConditioning,EModelFormat,EModelType,EOpenPosePreProcessor,EPhotoMakerEnum,EPreProcessor,EPreProcessorGroup,ETaskType,Environment,Runware,RunwareClient,RunwareServer,SdkType});
|
|
1
|
+
"use strict";var Me=Object.create;var L=Object.defineProperty;var Oe=Object.getOwnPropertyDescriptor;var Ne=Object.getOwnPropertyNames;var Le=Object.getPrototypeOf,Ee=Object.prototype.hasOwnProperty;var Ke=(l,t)=>()=>(t||l((t={exports:{}}).exports,t),t.exports),Pe=(l,t)=>{for(var e in t)L(l,e,{get:t[e],enumerable:!0})},te=(l,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Ne(t))!Ee.call(l,a)&&a!==e&&L(l,a,{get:()=>t[a],enumerable:!(n=Oe(t,a))||n.enumerable});return l};var ne=(l,t,e)=>(e=l!=null?Me(Le(l)):{},te(t||!l||!l.__esModule?L(e,"default",{value:l,enumerable:!0}):e,l)),We=l=>te(L({},"__esModule",{value:!0}),l);var Te=Ke((Et,be)=>{"use strict";var he=l=>l&&l.CLOSING===2,Ge=()=>typeof WebSocket<"u"&&he(WebSocket),Be=()=>({constructor:Ge()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),qe=(l,t,e)=>{Object.defineProperty(t,e,{get:()=>l[e],set:n=>{l[e]=n},enumerable:!0,configurable:!0})},Ie=l=>l.minReconnectionDelay+Math.random()*l.minReconnectionDelay,He=(l,t)=>{let e=t*l.reconnectionDelayGrowFactor;return e>l.maxReconnectionDelay?l.maxReconnectionDelay:e},Ve=["onopen","onclose","onmessage","onerror"],je=(l,t,e)=>{Object.keys(e).forEach(n=>{e[n].forEach(([a,o])=>{l.addEventListener(n,a,o)})}),t&&Ve.forEach(n=>{l[n]=t[n]})},fe=function(l,t,e={}){let n,a,o=0,c=0,i=!0,r={};if(!(this instanceof fe))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let u=Be();if(Object.keys(u).filter(p=>e.hasOwnProperty(p)).forEach(p=>u[p]=e[p]),!he(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=He(u,o):o=Ie(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&&qe(n,this,y);n.addEventListener("open",()=>{clearTimeout(a),g("open"),o=Ie(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,h])=>{U(x),n.removeEventListener("close",U,h)}),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)}};be.exports=fe});var ze={};Pe(ze,{EControlMode:()=>V,EModelArchitecture:()=>ae,EModelConditioning:()=>ie,EModelFormat:()=>re,EModelType:()=>oe,EOpenPosePreProcessor:()=>se,EPhotoMakerEnum:()=>le,EPreProcessor:()=>z,EPreProcessorGroup:()=>j,ETaskType:()=>K,Environment:()=>H,Runware:()=>Y,RunwareClient:()=>C,RunwareServer:()=>M,SdkType:()=>E});module.exports=We(ze);var H=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))(H||{}),E=(e=>(e.CLIENT="CLIENT",e.SERVER="SERVER",e))(E||{}),K=(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))(K||{}),V=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(V||{}),j=(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))(j||{}),z=(I=>(I.canny="canny",I.depth_leres="depth_leres",I.depth_midas="depth_midas",I.depth_zoe="depth_zoe",I.inpaint_global_harmonious="inpaint_global_harmonious",I.lineart_anime="lineart_anime",I.lineart_coarse="lineart_coarse",I.lineart_realistic="lineart_realistic",I.lineart_standard="lineart_standard",I.mlsd="mlsd",I.normal_bae="normal_bae",I.scribble_hed="scribble_hed",I.scribble_pidinet="scribble_pidinet",I.seg_ofade20k="seg_ofade20k",I.seg_ofcoco="seg_ofcoco",I.seg_ufade20k="seg_ufade20k",I.shuffle="shuffle",I.softedge_hed="softedge_hed",I.softedge_hedsafe="softedge_hedsafe",I.softedge_pidinet="softedge_pidinet",I.softedge_pidisafe="softedge_pidisafe",I.tile_gaussian="tile_gaussian",I.openpose="openpose",I.openpose_face="openpose_face",I.openpose_faceonly="openpose_faceonly",I.openpose_full="openpose_full",I.openpose_hand="openpose_hand",I))(z||{}),se=(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))(se||{}),re=(e=>(e.safetensors="safetensors",e.pickletensor="pickletensor",e))(re||{}),ae=(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))(ae||{}),oe=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))(oe||{}),ie=(h=>(h.canny="canny",h.depth="depth",h.qrcode="qrcode",h.hed="hed",h.scrible="scrible",h.openpose="openpose",h.seg="segmentation",h.openmlsd="openmlsd",h.softedge="softedge",h.normal="normal bae",h.shuffle="shuffle",h.pix2pix="pix2pix",h.inpaint="inpaint",h.lineart="line art",h.sketch="sketch",h.inpaintdepth="inpaint depth",h.tile="tile",h.outfit="outfit",h.blur="blur",h.gray="gray",h.lowquality="low quality",h))(ie||{}),le=(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))(le||{});var P=require("uuid"),J=6e4,ce=1e3,Fe=100,Q={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},ue=(l,t)=>{if(l==null)return;let e=l.indexOf(t);e!==-1&&l.splice(e,1)},D=(l,{debugKey:t="debugKey",timeoutDuration:e=J,shouldThrowError:n=!0})=>(e=e<ce?ce: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))},Fe)})),ge=l=>new Promise(t=>{let e=new FileReader;e.readAsDataURL(l),e.onload=function(){t(e.result)}}),_=()=>(0,P.v4)(),de=l=>(0,P.validate)(l);var pe=({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||{})??{},me=(l,t=1e3)=>new Promise(e=>setTimeout(e,l*t));var ye=(l,t)=>l.filter(e=>e.key!==t.key);var f=({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 me(e),await k(l,{...t,maxRetries:a});else throw o}};var S=class{constructor({apiKey:t,url:e=Q.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:a=2,timeoutDuration:o=J}){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"&&de(t))return{imageURL:t,imageUUID:t,taskUUID:e,taskType:"imageUpload"};let n=typeof t=="string"?t:await ge(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,...f({key:"height",value:n}),...f({key:"width",value:a}),...f({key:"outputType",value:o}),...f({key:"outputFormat",value:c}),...f({key:"includeCost",value:g}),...f({key:"highThresholdCanny",value:i}),...f({key:"lowThresholdCanny",value:r}),...f({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,...f({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,...f({key:"rgba",value:a}),...f({key:"postProcessMask",value:o}),...f({key:"returnOnlyMask",value:c}),...f({key:"alphaMatting",value:i}),...f({key:"includeCost",value:d}),...f({key:"alphaMattingForegroundThreshold",value:r}),...f({key:"alphaMattingBackgroundThreshold",value:u}),...f({key:"alphaMattingErodeSize",value:g}),...f({key:"outputType",value:e}),...f({key:"outputFormat",value:n})}),y=this.globalListener({taskUUID:T});let v=await D(({resolve:x,reject:U})=>{let h=this.getSingleMessage({taskUUID:T});if(h){if(h?.error)return U(h),!0;if(h)return delete this._globalMessages[T],x(h),!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,...f({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,...f({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=ye(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){ue(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=pe({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,numberResults:x=1,controlNet:U,lora:h,onPartialImages:ke,includeCost:Re,customTaskUUID:xe,retry:De,refiner:Z}){let I,$,O=[],X=0,ee=De||this._globalMaxRetries;try{await this.ensureConnection();let w=null,W=null,F=[];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[];W=R.imageUUID}if(U?.length)for(let R=0;R<U.length;R++){let A=U[R],{endStep:G,startStep:B,weight:q,guideImage:N,controlMode:ve,startStepPercentage:we,endStepPercentage:Se,model:Ae}=A,Ce=N?await this.uploadImage(N):null;F.push({guideImage:Ce?.imageUUID,model:Ae,endStep:G,startStep:B,weight:q,...f({key:"startStepPercentage",value:we}),...f({key:"endStepPercentage",value:Se}),controlMode:ve||"controlnet"})}return $={taskType:"imageInference",model:s,positivePrompt:o,...c?{negativePrompt:c}:{},...g?{height:g}:{},...d?{width:d}:{},numberResults:x,...h?.length?{lora:h}:{},...t?{outputType:t}:{},...e?{outputFormat:e}:{},...n?{uploadEndpoint:n}:{},...f({key:"checkNsfw",value:a}),...f({key:"strength",value:u}),...f({key:"CFGScale",value:b}),...f({key:"clipSkip",value:T}),...f({key:"usePromptWeighting",value:v}),...f({key:"steps",value:m}),...F.length?{controlNet:F}:{},...y?{seed:y}:{},...p?{scheduler:p}:{},...Z?{refiner:Z}:{},...f({key:"includeCost",value:Re}),...w?{seedImage:w}:{},...W?{maskImage:W}:{}},await k(async()=>{X++,I?.destroy();let R=this._globalImages.filter(N=>O.includes(N.taskUUID)),A=xe||_();O.push(A);let G=x-R.length,B={...$,taskUUID:A,numberResults:G};this.send(B),I=this.listenToImages({onPartialImages:ke,taskUUID:A,groupKey:"REQUEST_IMAGES",positivePrompt:o,negativePrompt:c});let q=await this.getSimilarImages({taskUUID:O,numberResults:x,lis:I});return I.destroy(),q},{maxRetries:ee,callback:()=>{I?.destroy()}})}catch(w){if(w.taskUUID)throw w;if(X>=ee)return this.handleIncompleteImages({taskUUIDs:O,error:w})}}async ensureConnection(){if(this.connected()||this._url===Q.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 Ue=ne(Te(),1),C=class extends S{constructor(t){let{shouldReconnect:e,...n}=t;super(n),this._ws=new Ue.default(this._url),this.connect()}};var _e=ne(require("ws"),1);var M=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 _e.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 Y;typeof window>"u"?Y=M:Y=C;0&&(module.exports={EControlMode,EModelArchitecture,EModelConditioning,EModelFormat,EModelType,EOpenPosePreProcessor,EPhotoMakerEnum,EPreProcessor,EPreProcessorGroup,ETaskType,Environment,Runware,RunwareClient,RunwareServer,SdkType});
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|