Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@aigur/client

Package Overview
Dependencies
Maintainers
1
Versions
39
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@aigur/client - npm Package Compare versions

Comparing version 0.35.0 to 1.0.0

6

CHANGELOG.md
# @aigur/client
## 1.0.0
### Major Changes
- 95e8e087: send pipeline events to specific pipelineInstanceId
## 0.35.0

@@ -4,0 +10,0 @@

11

dist/index.d.ts

@@ -23,4 +23,4 @@ import { z } from 'zod';

apiKeys: APIKeys;
eventListener?: (cb: (event: PipelineEvent) => void) => void;
eventPublisher?: (event: PipelineEvent) => Promise<any>;
eventListener?: (pipelineInstanceId: string, cb: (event: PipelineEvent) => void) => void;
eventPublisher?: (pipelineInstanceId: string, event: PipelineEvent) => Promise<any>;
}

@@ -34,4 +34,4 @@ interface PipelineConf<Input extends Record<string, unknown>, Output extends Record<string, unknown> | ReadableStream> {

updateProgress?: boolean;
eventListener?: (cb: (event: PipelineEvent) => void) => void;
eventPublisher?: (event: PipelineEvent) => Promise<any>;
eventListener?: (pipelineInstanceId: string, cb: (event: PipelineEvent) => void) => void;
eventPublisher?: (pipelineInstanceId: string, event: PipelineEvent) => Promise<any>;
validateInput?: (input: Input) => {

@@ -74,4 +74,5 @@ valid: boolean;

readonly onFinishListeners: Map<string, () => void>;
private readonly pipelineInstanceId;
constructor(conf: PipelineConf<Input, Output>, flow: FlowBuilder<Input, Output, any, any>, apiKeys: APIKeys);
invoke(input: Input): Promise<Output>;
invoke(input: Input, pipelineInstanceId?: string): Promise<Output>;
invokeRemote(endpoint: string, input: Input): Promise<Output>;

@@ -78,0 +79,0 @@ invokeStream(endpoint: string, input: Input, cb: (chunk: string) => void): Promise<void>;

@@ -1,2 +0,2 @@

var E=Object.defineProperty;var L=Object.getOwnPropertyDescriptor;var z=Object.getOwnPropertyNames;var D=Object.prototype.hasOwnProperty;var k=(n,e)=>{for(var t in e)E(n,t,{get:e[t],enumerable:!0})},M=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of z(e))!D.call(n,r)&&r!==t&&E(n,r,{get:()=>e[r],enumerable:!(o=L(e,r))||o.enumerable});return n};var K=n=>M(E({},"__esModule",{value:!0}),n);var xe={};k(xe,{Pipeline:()=>v,createClient:()=>J,dalleBase64TextToImage:()=>Z,dalleUrlTextToImage:()=>q,enhanceWithKeywords:()=>re,googleImageLabeling:()=>V,googleTextToSpeech:()=>ye,gpt3Prediction:()=>pe,gpt3PredictionStream:()=>ue,inputSchema:()=>N,output:()=>R,outputSchema:()=>se,replaceString:()=>ae,stabilityClipGuidancePreset:()=>C,stabilityModel:()=>U,stabilityTextToImage:()=>ee,stringToArrayBuffer:()=>le,vercelGenericEdge:()=>G,whisperApi:()=>Se});module.exports=K(xe);async function R(n){return n}var x=class{constructor(e){this.nodes=e}static create(){return new x([])}node(e,t){let o=this.createDynamicPlaceholders("input"),r=this.nodes.length>0?this.nodes[this.nodes.length-1]:o,a={action:e,input:t({nodes:this.nodes,prev:r.output,input:o}),output:this.createDynamicPlaceholders(this.nodes.length)};return this.nodes.push(a),this}createDynamicPlaceholders(e){let t={},o={get:function(a,c){return`$context.${e}.${c}$`}};return new Proxy(t,o)}output(e){return this.node(R,e)}getNodes(){return this.nodes}};function O(n){return new Promise(e=>setTimeout(e,n))}function j(n,e){if(typeof n=="string")return r(n);let t={...n};return o(t);function o(i){let s={};for(let d in i)s[d]=r(i[d]);return s}function r(i){if(Array.isArray(i))return i.map(u=>o(u));if(typeof i=="object"&&i!==null)return o(i);let s=i,d=a(i);for(let u of d){let h=e[u.nodeId][u.property];if(h instanceof ArrayBuffer){s=h;continue}s=s?.replace(new RegExp(c(u.value)),h),s==="undefined"?s=void 0:s!==h&&s===h.toString()&&(s=h)}return s}function a(i){if(typeof i!="string")return[];let s=/\$context\.(\d+|input)\.(\w+)\$/g,d=i.matchAll(s),u=[];for(let f of d)u.push({value:f[0],nodeId:f[1],property:f[2]});return u}function c(i){return i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}}function T(n=16){let e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",o=t.length;for(let r=0;r<n;r++)e+=t.charAt(Math.floor(Math.random()*o));return e}var B=2,$=350,v=class{constructor(e,t,o){this.conf=e;this.flow=t;this.apiKeys=o;this.onProgressListeners=new Map;this.onStartListeners=new Map;this.onFinishListeners=new Map;this.vercel={invoke:e=>this.invokeRemote(`/api/pipelines/${this.conf.id}?_vercel_no_cache=1`,e),invokeStream:(e,t)=>this.invokeStream(`/api/pipelines/${this.conf.id}?_vercel_no_cache=1`,e,t)};this.listenToEvents()}invoke(e){return this.processPipeline(e)}invokeRemote(e,t){return fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}).then(o=>o.json())}async invokeStream(e,t,o){let r=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok)throw new Error(r.statusText);let a=r.body;if(!a)return;let c=a.getReader(),i=new TextDecoder,s=!1;for(;!s;){let{value:d,done:u}=await c.read();s=u;let f=i.decode(d);o(f)}}onProgress(e){let t=T();return this.onProgressListeners.set(t,e),()=>{this.onProgressListeners.delete(t)}}onStart(e){let t=T();return this.onStartListeners.set(t,e),()=>{this.onStartListeners.delete(t)}}onFinish(e){let t=T();return this.onFinishListeners.set(t,e),()=>{this.onFinishListeners.delete(t)}}async processPipeline(e){let t=this.conf.retries??B;try{if(await this.notifyEvent("pipeline:start"),this.conf.validateInput){let i=this.conf.validateInput(e);if(!i.valid)throw new Error(i.message)}let o={input:e},r={},a=this.flow.getNodes(),c;for(let i=0;i<a.length;i++){c=this.notifyEvent("node:start",{node:a[i].name,index:i});let s=0,d=!1;do{s++;try{r=await this.executeAction(a,i,o),o[i]=r,d=!0}catch(u){if(s>t)throw u;await O((this.conf.retryDelayInMs??$)*s)}}while(!d&&s<=t);await c,await this.notifyEvent("node:finish",{node:a[i].name,index:i})}return await this.notifyEvent("pipeline:finish"),r}catch(o){throw console.error(o),o}}async executeAction(e,t,o){let{action:r,input:a}=e[t],c=j(a,o);return r(c,this.apiKeys)}listenToEvents(){!this.conf.updateProgress||typeof window>"u"||!this.conf.eventListener||this.conf.eventListener(e=>{e.pipelineId===this.conf.id&&(e.type==="pipeline:start"?this.triggerListeners(this.onStartListeners):e.type==="pipeline:finish"?this.triggerListeners(this.onFinishListeners):(e.type==="node:start"||e.type==="node:finish")&&this.triggerListeners(this.onProgressListeners,{...e.data,type:e.type}))})}triggerListeners(e,...t){for(let o of e.values())o(...t)}notifyEvent(e,t){if(!(!this.conf.updateProgress||!this.conf.eventPublisher))return this.conf.eventPublisher({type:e,data:t,pipelineId:this.conf.id})}};var W=2,F=350,J=n=>{let{apiKeys:e}=n;return{apiKeys:e,pipeline:{create:t=>{let o={...t,retries:t.retries??W,retryDelayInMs:t.retryDelayInMs??F,eventListener:n.eventListener,eventPublisher:n.eventPublisher},r=t.flow(new x([]));return new v(o,r,e)}}}};async function G(n,e){let t=await e.json(),{searchParams:o}=new URL(e.url);if(!o.has("id"))return new Response("Missing id",{status:400});let r=o.get("id"),a=n[r];return{output:await a.invoke(t),pipeline:a}}var b=require("zod"),H=b.z.object({image:b.z.string()}),Le=b.z.object({labels:b.z.array(b.z.string())});async function V(n,e){let t=H.parse(n),o=`https://vision.googleapis.com/v1/images:annotate?key=${e.googleapis}`,r={requests:[{image:{content:t.image},features:[{type:"LABEL_DETECTION"}]}]};return{labels:(await(await fetch(o,{method:"POST",body:JSON.stringify(r)})).json()).responses[0].labelAnnotations.map(i=>i.description)}}var P=require("zod"),Y=P.z.object({prompt:P.z.string(),size:P.z.enum(["256x256","512x512","1024x1024"]).default("512x512")}),De=P.z.object({url:P.z.string().url()});async function q(n,e){let t=Y.parse(n),r=await fetch("https://api.openai.com/v1/images/generations",{headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.openai}`},method:"POST",body:JSON.stringify(t)}),{data:a}=await r.json();return{url:a[0].url}}var S=require("zod"),X=S.z.object({prompt:S.z.string(),response_format:S.z.literal("b64_json").default("b64_json"),size:S.z.enum(["256x256","512x512","1024x1024"]).default("512x512")}),Me=S.z.object({result:S.z.string()});async function Z(n,e){let t=X.parse(n),r=await fetch("https://api.openai.com/v1/images/generations",{headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.openai}`},method:"POST",body:JSON.stringify(t)}),{data:a}=await r.json();return{result:a[0].b64_json}}var p=require("zod"),U=p.z.enum(["stable-diffusion-v1-5","stable-diffusion-512-v2-0","stable-diffusion-768-v2-0","stable-diffusion-512-v2-1","stable-diffusion-768-v2-1"]),C=p.z.enum(["NONE","FAST_BLUE","FAST_GREEN","SIMPLE","SLOW","SLOWER","SLOWEST"]),Q=p.z.object({text_prompts:p.z.array(p.z.object({text:p.z.string(),weight:p.z.number().min(-1).max(1).default(1)})).refine(n=>n.length>0,"Must have at least one text prompt"),model:U.default("stable-diffusion-v1-5"),clip_guidance_preset:C.optional(),steps:p.z.number().min(0).max(150).optional(),sampler:p.z.enum(["DDIM","DDPM","K_DPMPP_2M","K_DPMPP_2S_ANCESTRAL","K_DPM_2","K_DPM_2_ANCESTRAL","K_EULER","K_EULER_ANCESTRAL","K_HEUN","K_LMS"]).optional(),cfg_scale:p.z.number().min(0).max(35).optional(),seed:p.z.number().min(0).optional(),height:p.z.number().min(128).optional().refine(n=>typeof n<"u"?n%64===0:!0,"Must be a multiple of 64"),width:p.z.number().min(128).optional().refine(n=>typeof n<"u"?n%64===0:!0,"Must be a multiple of 64")}),Be=p.z.object({result:p.z.instanceof(ArrayBuffer)});async function ee(n,e){let t=Q.parse(n),o=`https://api.stability.ai/v1beta/generation/${t.model}/text-to-image`;return{result:await(await fetch(o,{headers:{"Content-Type":"application/json",Accept:"image/png",Authorization:e.stability},method:"POST",body:JSON.stringify(t)})).arrayBuffer()}}var w=require("zod"),te=w.z.object({text:w.z.string(),amount:w.z.number().optional().default(8)}),We=w.z.object({text:w.z.string()}),ne={"Colonial-style home":"Colonial, traditional, classic, historical, timeless, elegant, regal, grand, spacious, architectural, wood-framed, brick-exterior, symmetrical, gabled roof, columns, portico, fireplace, formal, ornate, landscaped".split(", "),"High-end penthouse apartment":"Luxury, high-end, penthouse, apartment, upscale, contemporary, modern, stylish, designer, elite, high-rise, rooftop, panoramic, views, spacious, open-plan, top-floor, amenities, concierge, service, exclusive".split(", ")};function oe(n){return Object.entries(ne).map(([e,t])=>`Title: ${e}
var E=Object.defineProperty;var z=Object.getOwnPropertyDescriptor;var _=Object.getOwnPropertyNames;var D=Object.prototype.hasOwnProperty;var k=(n,e)=>{for(var t in e)E(n,t,{get:e[t],enumerable:!0})},M=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of _(e))!D.call(n,r)&&r!==t&&E(n,r,{get:()=>e[r],enumerable:!(o=z(e,r))||o.enumerable});return n};var K=n=>M(E({},"__esModule",{value:!0}),n);var xe={};k(xe,{Pipeline:()=>I,createClient:()=>J,dalleBase64TextToImage:()=>Z,dalleUrlTextToImage:()=>q,enhanceWithKeywords:()=>re,googleImageLabeling:()=>V,googleTextToSpeech:()=>ye,gpt3Prediction:()=>pe,gpt3PredictionStream:()=>ue,inputSchema:()=>N,output:()=>R,outputSchema:()=>se,replaceString:()=>ae,stabilityClipGuidancePreset:()=>C,stabilityModel:()=>U,stabilityTextToImage:()=>ee,stringToArrayBuffer:()=>le,vercelGenericEdge:()=>G,whisperApi:()=>Se});module.exports=K(xe);async function R(n){return n}var x=class{constructor(e){this.nodes=e}static create(){return new x([])}node(e,t){let o=this.createDynamicPlaceholders("input"),r=this.nodes.length>0?this.nodes[this.nodes.length-1]:o,a={action:e,input:t({nodes:this.nodes,prev:r.output,input:o}),output:this.createDynamicPlaceholders(this.nodes.length)};return this.nodes.push(a),this}createDynamicPlaceholders(e){let t={},o={get:function(a,p){return`$context.${e}.${p}$`}};return new Proxy(t,o)}output(e){return this.node(R,e)}getNodes(){return this.nodes}};function v(n=16){let e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",o=t.length;for(let r=0;r<n;r++)e+=t.charAt(Math.floor(Math.random()*o));return e}function O(n,e){if(typeof n=="string")return r(n);let t={...n};return o(t);function o(s){let i={};for(let c in s)i[c]=r(s[c]);return i}function r(s){if(Array.isArray(s))return s.map(u=>o(u));if(typeof s=="object"&&s!==null)return o(s);let i=s,c=a(s);for(let u of c){let h=e[u.nodeId][u.property];if(h instanceof ArrayBuffer){i=h;continue}i=i?.replace(new RegExp(p(u.value)),h),i==="undefined"?i=void 0:i!==h&&i===h.toString()&&(i=h)}return i}function a(s){if(typeof s!="string")return[];let i=/\$context\.(\d+|input)\.(\w+)\$/g,c=s.matchAll(i),u=[];for(let f of c)u.push({value:f[0],nodeId:f[1],property:f[2]});return u}function p(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}}function j(n){return new Promise(e=>setTimeout(e,n))}var B=2,$=350,I=class{constructor(e,t,o){this.conf=e;this.flow=t;this.apiKeys=o;this.onProgressListeners=new Map;this.onStartListeners=new Map;this.onFinishListeners=new Map;this.pipelineInstanceId=v(16);this.vercel={invoke:e=>this.invokeRemote(`/api/pipelines/${this.conf.id}`,e),invokeStream:(e,t)=>this.invokeStream(`/api/pipelines/${this.conf.id}`,e,t)};this.listenToEvents()}invoke(e,t=this.pipelineInstanceId){return this.processPipeline(e,t)}invokeRemote(e,t){return fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:t,pipelineInstanceId:this.pipelineInstanceId})}).then(o=>o.json())}async invokeStream(e,t,o){let r=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:t,pipelineInstanceId:this.pipelineInstanceId})});if(!r.ok)throw new Error(r.statusText);let a=r.body;if(!a)return;let p=a.getReader(),s=new TextDecoder,i=!1;for(;!i;){let{value:c,done:u}=await p.read();i=u;let f=s.decode(c);o(f)}}onProgress(e){let t=v();return this.onProgressListeners.set(t,e),()=>{this.onProgressListeners.delete(t)}}onStart(e){let t=v();return this.onStartListeners.set(t,e),()=>{this.onStartListeners.delete(t)}}onFinish(e){let t=v();return this.onFinishListeners.set(t,e),()=>{this.onFinishListeners.delete(t)}}async processPipeline(e,t){let o=this.conf.retries??B;try{if(await this.notifyEvent("pipeline:start",t),this.conf.validateInput){let i=this.conf.validateInput(e);if(!i.valid)throw new Error(i.message)}let r={input:e},a={},p=this.flow.getNodes(),s;for(let i=0;i<p.length;i++){s=this.notifyEvent("node:start",t,{node:p[i].name,index:i});let c=0,u=!1;do{c++;try{a=await this.executeAction(p,i,r),r[i]=a,u=!0}catch(f){if(c>o)throw f;await j((this.conf.retryDelayInMs??$)*c)}}while(!u&&c<=o);await s,await this.notifyEvent("node:finish",t,{node:p[i].name,index:i})}return await this.notifyEvent("pipeline:finish",t),a}catch(r){throw console.error(r),r}}async executeAction(e,t,o){let{action:r,input:a}=e[t],p=O(a,o);return r(p,this.apiKeys)}listenToEvents(){!this.conf.updateProgress||typeof window>"u"||!this.conf.eventListener||this.conf.eventListener(this.pipelineInstanceId,e=>{e.pipelineId===this.conf.id&&(e.type==="pipeline:start"?this.triggerListeners(this.onStartListeners):e.type==="pipeline:finish"?this.triggerListeners(this.onFinishListeners):(e.type==="node:start"||e.type==="node:finish")&&this.triggerListeners(this.onProgressListeners,{...e.data,type:e.type}))})}triggerListeners(e,...t){for(let o of e.values())o(...t)}notifyEvent(e,t,o){if(!(!this.conf.updateProgress||!this.conf.eventPublisher))return this.conf.eventPublisher(t,{type:e,data:o,pipelineId:this.conf.id})}};var W=2,F=350,J=n=>{let{apiKeys:e}=n;return{apiKeys:e,pipeline:{create:t=>{let o={...t,retries:t.retries??W,retryDelayInMs:t.retryDelayInMs??F,eventListener:n.eventListener,eventPublisher:n.eventPublisher},r=t.flow(new x([]));return new I(o,r,e)}}}};async function G(n,e){let{pipelineInstanceId:t,input:o}=await e.json(),{searchParams:r}=new URL(e.url);if(!r.has("id"))return new Response("Missing id",{status:400});let a=r.get("id"),p=n[a];return{output:await p.invoke(o,t),pipeline:p}}var b=require("zod"),H=b.z.object({image:b.z.string()}),ze=b.z.object({labels:b.z.array(b.z.string())});async function V(n,e){let t=H.parse(n),o=`https://vision.googleapis.com/v1/images:annotate?key=${e.googleapis}`,r={requests:[{image:{content:t.image},features:[{type:"LABEL_DETECTION"}]}]};return{labels:(await(await fetch(o,{method:"POST",body:JSON.stringify(r)})).json()).responses[0].labelAnnotations.map(s=>s.description)}}var P=require("zod"),Y=P.z.object({prompt:P.z.string(),size:P.z.enum(["256x256","512x512","1024x1024"]).default("512x512")}),De=P.z.object({url:P.z.string().url()});async function q(n,e){let t=Y.parse(n),r=await fetch("https://api.openai.com/v1/images/generations",{headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.openai}`},method:"POST",body:JSON.stringify(t)}),{data:a}=await r.json();return{url:a[0].url}}var S=require("zod"),X=S.z.object({prompt:S.z.string(),response_format:S.z.literal("b64_json").default("b64_json"),size:S.z.enum(["256x256","512x512","1024x1024"]).default("512x512")}),Me=S.z.object({result:S.z.string()});async function Z(n,e){let t=X.parse(n),r=await fetch("https://api.openai.com/v1/images/generations",{headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.openai}`},method:"POST",body:JSON.stringify(t)}),{data:a}=await r.json();return{result:a[0].b64_json}}var d=require("zod"),U=d.z.enum(["stable-diffusion-v1-5","stable-diffusion-512-v2-0","stable-diffusion-768-v2-0","stable-diffusion-512-v2-1","stable-diffusion-768-v2-1"]),C=d.z.enum(["NONE","FAST_BLUE","FAST_GREEN","SIMPLE","SLOW","SLOWER","SLOWEST"]),Q=d.z.object({text_prompts:d.z.array(d.z.object({text:d.z.string(),weight:d.z.number().min(-1).max(1).default(1)})).refine(n=>n.length>0,"Must have at least one text prompt"),model:U.default("stable-diffusion-v1-5"),clip_guidance_preset:C.optional(),steps:d.z.number().min(0).max(150).optional(),sampler:d.z.enum(["DDIM","DDPM","K_DPMPP_2M","K_DPMPP_2S_ANCESTRAL","K_DPM_2","K_DPM_2_ANCESTRAL","K_EULER","K_EULER_ANCESTRAL","K_HEUN","K_LMS"]).optional(),cfg_scale:d.z.number().min(0).max(35).optional(),seed:d.z.number().min(0).optional(),height:d.z.number().min(128).optional().refine(n=>typeof n<"u"?n%64===0:!0,"Must be a multiple of 64"),width:d.z.number().min(128).optional().refine(n=>typeof n<"u"?n%64===0:!0,"Must be a multiple of 64")}),Be=d.z.object({result:d.z.instanceof(ArrayBuffer)});async function ee(n,e){let t=Q.parse(n),o=`https://api.stability.ai/v1beta/generation/${t.model}/text-to-image`;return{result:await(await fetch(o,{headers:{"Content-Type":"application/json",Accept:"image/png",Authorization:e.stability},method:"POST",body:JSON.stringify(t)})).arrayBuffer()}}var w=require("zod"),te=w.z.object({text:w.z.string(),amount:w.z.number().optional().default(8)}),We=w.z.object({text:w.z.string()}),ne={"Colonial-style home":"Colonial, traditional, classic, historical, timeless, elegant, regal, grand, spacious, architectural, wood-framed, brick-exterior, symmetrical, gabled roof, columns, portico, fireplace, formal, ornate, landscaped".split(", "),"High-end penthouse apartment":"Luxury, high-end, penthouse, apartment, upscale, contemporary, modern, stylish, designer, elite, high-rise, rooftop, panoramic, views, spacious, open-plan, top-floor, amenities, concierge, service, exclusive".split(", ")};function oe(n){return Object.entries(ne).map(([e,t])=>`Title: ${e}
Description: ${t.slice(0,n).join(", ")}

@@ -7,2 +7,2 @@ `).join(`

Title: ${e.text}
Description:`}}var g=require("zod"),ie=g.z.object({text:g.z.string().or(g.z.array(g.z.string())),modifier:g.z.string()}),Je=g.z.object({text:g.z.string()});async function ae(n){let e=ie.parse(n);return{text:e.modifier.replace(/\$\(text\)\$/gm,Array.isArray(e.text)?e.text.join(", "):e.text)}}var m=require("zod"),N=m.z.object({prompt:m.z.string(),model:m.z.enum(["text-davinci-003","text-curie-001","text-babbage-001","text-ada-001","code-davinci-002","code-cushman-002"]).default("text-davinci-003"),temperature:m.z.number().min(0).max(2).default(.7),top_p:m.z.number().min(0).max(1).default(1),frequency_penalty:m.z.number().min(-2).max(2).default(0),presence_penalty:m.z.number().min(-2).max(2).default(0),max_tokens:m.z.number().default(200),n:m.z.number().default(1)}),se=m.z.object({text:m.z.string()});async function pe(n,e){let t=N.parse(n);return{text:(await(await fetch("https://api.openai.com/v1/completions",{headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.openai}`},method:"POST",body:JSON.stringify(t)})).json()).choices[0]?.text.replace(/^(?:\n)+/gm,"")}}var _=require("eventsource-parser"),I=require("zod");var ce=N.merge(I.z.object({stream:I.z.literal(!0).optional().default(!0)})),Xe=I.z.object({stream:I.z.instanceof(globalThis.ReadableStream??Object)});async function ue(n,e){let t=ce.parse(n),o=await fetch("https://api.openai.com/v1/completions",{headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.openai}`},method:"POST",body:JSON.stringify(t)});return{stream:await de(o)}}async function de(n){let e=new TextEncoder,t=new TextDecoder,o=0;return new ReadableStream({async start(a){function c(s){if(s.type==="event"){let d=s.data;if(d==="[DONE]"){a.close();return}try{let f=JSON.parse(d).choices[0].text;if(o<2&&(f.match(/\n/)||[]).length)return;let h=e.encode(f);a.enqueue(h),o++}catch(u){a.error(u)}}}let i=(0,_.createParser)(c);for await(let s of n.body)i.feed(t.decode(s))}})}var A=require("zod"),me=A.z.object({string:A.z.string()}),Qe=A.z.object({arrayBuffer:A.z.instanceof(ArrayBuffer)});async function le(n){let e=me.parse(n);return{arrayBuffer:Uint8Array.from(atob(e.string),o=>o.charCodeAt(0)).buffer}}var l=require("zod"),fe=l.z.object({text:l.z.string(),speakingRate:l.z.number().min(.25).max(4).optional().default(1),pitch:l.z.number().min(-20).max(20).optional().default(0),encoding:l.z.enum(["MP3","FLAC","LINEAR16","MULAW","AMR","AMR_WB","OGG_OPUS","SPEEX_WITH_HEADER_BYTE","WEBM_OPUS"]).optional().default("MP3"),voice:l.z.object({language:l.z.string().optional().default("en-US"),name:l.z.enum(["en-US-Standard-A","en-US-Standard-C","en-US-Standard-D","en-US-Standard-E","en-US-Standard-F","en-US-Standard-G","en-US-Standard-H","en-US-Standard-I","en-US-Standard-J","en-US-Studio-M","en-US-Studio-O","en-US-Wavenet-A","en-US-Wavenet-B","en-US-Wavenet-C","en-US-Wavenet-D","en-US-Wavenet-E","en-US-Wavenet-F","en-US-Wavenet-G","en-US-Wavenet-H","en-US-Wavenet-I","en-US-Wavenet-J","en-US-News-K","en-US-News-L","en-US-News-M","en-US-News-N","en-US-Standard-A","en-US-Standard-B","en-US-Standard-C","en-US-Standard-D","en-US-Standard-E","en-US-Standard-F","en-US-Standard-G","en-US-Standard-H","en-US-Standard-I","en-US-Standard-J"]).or(l.z.string()).optional().default("en-US-Neural2-C")}).optional().default({language:"en-US",name:"en-US-Neural2-C"})}),tt=l.z.object({audio:l.z.string()});async function ye(n,e){let t=fe.parse(n),o=`https://us-central1-texttospeech.googleapis.com/v1beta1/text:synthesize?key=${e.googleapis}`,r={input:{text:t.text},voice:{languageCode:t.voice.language,name:t.voice.name},audioConfig:{audioEncoding:t.encoding,speakingRate:t.speakingRate,pitch:t.pitch}};return{audio:(await(await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)})).json()).audioContent}}var y=require("zod"),he="https://transcribe.whisperapi.com",ge=y.z.object({audioUrl:y.z.string().url(),language:y.z.string().default("en"),autoDetectLanguage:y.z.boolean().default(!1),fileType:y.z.string().default("mp3"),task:y.z.enum(["transcribe","translate"]).default("transcribe")}),ot=y.z.object({text:y.z.string()});async function Se(n,e){let t=ge.parse(n),o=new FormData;o.append("url",t.audioUrl),t.autoDetectLanguage||o.append("language",t.language),o.append("fileType",t.fileType),o.append("task",t.task);let r=await fetch(he,{method:"POST",headers:{contentType:"application/json",Authorization:"Bearer "+e.whisperapi},body:o});if(!r.ok)throw new Error(r.statusText);return{text:(await r.json()).text.trim()}}0&&(module.exports={Pipeline,createClient,dalleBase64TextToImage,dalleUrlTextToImage,enhanceWithKeywords,googleImageLabeling,googleTextToSpeech,gpt3Prediction,gpt3PredictionStream,inputSchema,output,outputSchema,replaceString,stabilityClipGuidancePreset,stabilityModel,stabilityTextToImage,stringToArrayBuffer,vercelGenericEdge,whisperApi});
Description:`}}var g=require("zod"),ie=g.z.object({text:g.z.string().or(g.z.array(g.z.string())),modifier:g.z.string()}),Je=g.z.object({text:g.z.string()});async function ae(n){let e=ie.parse(n);return{text:e.modifier.replace(/\$\(text\)\$/gm,Array.isArray(e.text)?e.text.join(", "):e.text)}}var m=require("zod"),N=m.z.object({prompt:m.z.string(),model:m.z.enum(["text-davinci-003","text-curie-001","text-babbage-001","text-ada-001","code-davinci-002","code-cushman-002"]).default("text-davinci-003"),temperature:m.z.number().min(0).max(2).default(.7),top_p:m.z.number().min(0).max(1).default(1),frequency_penalty:m.z.number().min(-2).max(2).default(0),presence_penalty:m.z.number().min(-2).max(2).default(0),max_tokens:m.z.number().default(200),n:m.z.number().default(1)}),se=m.z.object({text:m.z.string()});async function pe(n,e){let t=N.parse(n);return{text:(await(await fetch("https://api.openai.com/v1/completions",{headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.openai}`},method:"POST",body:JSON.stringify(t)})).json()).choices[0]?.text.replace(/^(?:\n)+/gm,"")}}var L=require("eventsource-parser"),A=require("zod");var ce=N.merge(A.z.object({stream:A.z.literal(!0).optional().default(!0)})),Xe=A.z.object({stream:A.z.instanceof(globalThis.ReadableStream??Object)});async function ue(n,e){let t=ce.parse(n),o=await fetch("https://api.openai.com/v1/completions",{headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.openai}`},method:"POST",body:JSON.stringify(t)});return{stream:await de(o)}}async function de(n){let e=new TextEncoder,t=new TextDecoder,o=0;return new ReadableStream({async start(a){function p(i){if(i.type==="event"){let c=i.data;if(c==="[DONE]"){a.close();return}try{let f=JSON.parse(c).choices[0].text;if(o<2&&(f.match(/\n/)||[]).length)return;let h=e.encode(f);a.enqueue(h),o++}catch(u){a.error(u)}}}let s=(0,L.createParser)(p);for await(let i of n.body)s.feed(t.decode(i))}})}var T=require("zod"),me=T.z.object({string:T.z.string()}),Qe=T.z.object({arrayBuffer:T.z.instanceof(ArrayBuffer)});async function le(n){let e=me.parse(n);return{arrayBuffer:Uint8Array.from(atob(e.string),o=>o.charCodeAt(0)).buffer}}var l=require("zod"),fe=l.z.object({text:l.z.string(),speakingRate:l.z.number().min(.25).max(4).optional().default(1),pitch:l.z.number().min(-20).max(20).optional().default(0),encoding:l.z.enum(["MP3","FLAC","LINEAR16","MULAW","AMR","AMR_WB","OGG_OPUS","SPEEX_WITH_HEADER_BYTE","WEBM_OPUS"]).optional().default("MP3"),voice:l.z.object({language:l.z.string().optional().default("en-US"),name:l.z.enum(["en-US-Standard-A","en-US-Standard-C","en-US-Standard-D","en-US-Standard-E","en-US-Standard-F","en-US-Standard-G","en-US-Standard-H","en-US-Standard-I","en-US-Standard-J","en-US-Studio-M","en-US-Studio-O","en-US-Wavenet-A","en-US-Wavenet-B","en-US-Wavenet-C","en-US-Wavenet-D","en-US-Wavenet-E","en-US-Wavenet-F","en-US-Wavenet-G","en-US-Wavenet-H","en-US-Wavenet-I","en-US-Wavenet-J","en-US-News-K","en-US-News-L","en-US-News-M","en-US-News-N","en-US-Standard-A","en-US-Standard-B","en-US-Standard-C","en-US-Standard-D","en-US-Standard-E","en-US-Standard-F","en-US-Standard-G","en-US-Standard-H","en-US-Standard-I","en-US-Standard-J"]).or(l.z.string()).optional().default("en-US-Neural2-C")}).optional().default({language:"en-US",name:"en-US-Neural2-C"})}),tt=l.z.object({audio:l.z.string()});async function ye(n,e){let t=fe.parse(n),o=`https://us-central1-texttospeech.googleapis.com/v1beta1/text:synthesize?key=${e.googleapis}`,r={input:{text:t.text},voice:{languageCode:t.voice.language,name:t.voice.name},audioConfig:{audioEncoding:t.encoding,speakingRate:t.speakingRate,pitch:t.pitch}};return{audio:(await(await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)})).json()).audioContent}}var y=require("zod"),he="https://transcribe.whisperapi.com",ge=y.z.object({audioUrl:y.z.string().url(),language:y.z.string().default("en"),autoDetectLanguage:y.z.boolean().default(!1),fileType:y.z.string().default("mp3"),task:y.z.enum(["transcribe","translate"]).default("transcribe")}),ot=y.z.object({text:y.z.string()});async function Se(n,e){let t=ge.parse(n),o=new FormData;o.append("url",t.audioUrl),t.autoDetectLanguage||o.append("language",t.language),o.append("fileType",t.fileType),o.append("task",t.task);let r=await fetch(he,{method:"POST",headers:{contentType:"application/json",Authorization:"Bearer "+e.whisperapi},body:o});if(!r.ok)throw new Error(r.statusText);return{text:(await r.json()).text.trim()}}0&&(module.exports={Pipeline,createClient,dalleBase64TextToImage,dalleUrlTextToImage,enhanceWithKeywords,googleImageLabeling,googleTextToSpeech,gpt3Prediction,gpt3PredictionStream,inputSchema,output,outputSchema,replaceString,stabilityClipGuidancePreset,stabilityModel,stabilityTextToImage,stringToArrayBuffer,vercelGenericEdge,whisperApi});
{
"name": "@aigur/client",
"version": "0.35.0",
"version": "1.0.0",
"description": "",

@@ -5,0 +5,0 @@ "main": "./dist/index.js",

@@ -0,6 +1,6 @@

import { APIKeys, ConcreteNode, EventType, PipelineConf, ProgressEventType } from './types';
import { makeid } from './makeid';
import { getInputByContext } from './getInputByContext';
import { delay } from './delay';
import { FlowBuilder } from './builder';
import { delay } from './delay';
import { getInputByContext } from './getInputByContext';
import { makeid } from './makeid';
import { APIKeys, ConcreteNode, EventType, PipelineConf, ProgressEventType } from './types';

@@ -20,2 +20,3 @@ const DEFAULT_RETRIES = 2;

public readonly onFinishListeners: Map<string, () => void> = new Map();
private readonly pipelineInstanceId = makeid(16);

@@ -30,4 +31,4 @@ constructor(

public invoke(input: Input) {
return this.processPipeline(input);
public invoke(input: Input, pipelineInstanceId: string = this.pipelineInstanceId) {
return this.processPipeline(input, pipelineInstanceId);
}

@@ -42,3 +43,6 @@

},
body: JSON.stringify(input),
body: JSON.stringify({
input,
pipelineInstanceId: this.pipelineInstanceId,
}),
})

@@ -63,3 +67,6 @@ // TODO: check response.ok

},
body: JSON.stringify(input),
body: JSON.stringify({
input,
pipelineInstanceId: this.pipelineInstanceId,
}),
});

@@ -88,7 +95,7 @@ if (!response.ok) {

// TODO: move base url to "create" optional param
return this.invokeRemote(`/api/pipelines/${this.conf.id}?_vercel_no_cache=1`, input);
return this.invokeRemote(`/api/pipelines/${this.conf.id}`, input);
},
invokeStream: (input: Input, cb: (chunk: string) => void) => {
// TODO: move base url to "create" optional param
return this.invokeStream(`/api/pipelines/${this.conf.id}?_vercel_no_cache=1`, input, cb);
return this.invokeStream(`/api/pipelines/${this.conf.id}`, input, cb);
},

@@ -123,6 +130,6 @@ };

private async processPipeline(input: Input): Promise<Output> {
private async processPipeline(input: Input, pipelineInstanceId: string): Promise<Output> {
const retriesCount = this.conf.retries ?? DEFAULT_RETRIES;
try {
await this.notifyEvent('pipeline:start');
await this.notifyEvent('pipeline:start', pipelineInstanceId);
if (this.conf.validateInput) {

@@ -141,3 +148,6 @@ const result = this.conf.validateInput(input);

for (let i = 0; i < nodes.length; i++) {
startProgressPromise = this.notifyEvent('node:start', { node: nodes[i].name, index: i });
startProgressPromise = this.notifyEvent('node:start', pipelineInstanceId, {
node: nodes[i].name,
index: i,
});
let attemptCount = 0;

@@ -160,6 +170,9 @@ let isSuccess = false;

await startProgressPromise;
await this.notifyEvent('node:finish', { node: nodes[i].name, index: i });
await this.notifyEvent('node:finish', pipelineInstanceId, {
node: nodes[i].name,
index: i,
});
}
await this.notifyEvent('pipeline:finish');
await this.notifyEvent('pipeline:finish', pipelineInstanceId);
return output;

@@ -183,3 +196,3 @@ } catch (e) {

this.conf.eventListener((event) => {
this.conf.eventListener(this.pipelineInstanceId, (event) => {
if (event.pipelineId !== this.conf.id) {

@@ -204,8 +217,8 @@ return;

private notifyEvent(type: EventType, data?: Record<any, any>) {
private notifyEvent(type: EventType, pipelineInstanceId: string, data?: Record<any, any>) {
if (!this.conf.updateProgress || !this.conf.eventPublisher) {
return;
}
return this.conf.eventPublisher({ type, data, pipelineId: this.conf.id });
return this.conf.eventPublisher(pipelineInstanceId, { type, data, pipelineId: this.conf.id });
}
}

@@ -7,4 +7,4 @@ import { z } from 'zod';

apiKeys: APIKeys;
eventListener?: (cb: (event: PipelineEvent) => void) => void;
eventPublisher?: (event: PipelineEvent) => Promise<any>;
eventListener?: (pipelineInstanceId: string, cb: (event: PipelineEvent) => void) => void;
eventPublisher?: (pipelineInstanceId: string, event: PipelineEvent) => Promise<any>;
}

@@ -24,4 +24,4 @@

updateProgress?: boolean;
eventListener?: (cb: (event: PipelineEvent) => void) => void;
eventPublisher?: (event: PipelineEvent) => Promise<any>;
eventListener?: (pipelineInstanceId: string, cb: (event: PipelineEvent) => void) => void;
eventPublisher?: (pipelineInstanceId: string, event: PipelineEvent) => Promise<any>;
validateInput?: (input: Input) => { valid: boolean; message?: string };

@@ -44,3 +44,7 @@ }

export type PipelineEvent = { type: EventType; data?: Record<any, any>; pipelineId: string };
export type PipelineEvent = {
type: EventType;
data?: Record<any, any>;
pipelineId: string;
};
export type EventType = PipelineEventType | ProgressEventType;

@@ -47,0 +51,0 @@ export type PipelineEventType = 'pipeline:start' | 'pipeline:finish';

export async function vercelGenericEdge(pipelines, req) {
const input = await req.json();
const { pipelineInstanceId, input } = await req.json();
const { searchParams } = new URL(req.url);

@@ -9,4 +9,4 @@ if (!searchParams.has('id')) {

const pipeline = (pipelines as any)[id];
const output = await pipeline.invoke(input);
const output = await pipeline.invoke(input, pipelineInstanceId);
return { output, pipeline };
}

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc