UNPKG

@subscribe.dev/client

Version:

JavaScript/TypeScript client for SubscribeDev API - A drop-in for AI generation across 100+ models with built-in billing and rate limiting

8 lines (5 loc) 35.2 kB
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const M=require("p-queue");function G(S){return S&&S.__esModule&&Object.prototype.hasOwnProperty.call(S,"default")?S.default:S}var x={exports:{}},I;function z(){return I||(I=1,(function(S){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function s(d,u,a){this.fn=d,this.context=u,this.once=a||!1}function p(d,u,a,n,m){if(typeof a!="function")throw new TypeError("The listener must be a function");var c=new s(a,n||d,m),r=t?t+u:u;return d._events[r]?d._events[r].fn?d._events[r]=[d._events[r],c]:d._events[r].push(c):(d._events[r]=c,d._eventsCount++),d}function h(d,u){--d._eventsCount===0?d._events=new i:delete d._events[u]}function f(){this._events=new i,this._eventsCount=0}f.prototype.eventNames=function(){var u=[],a,n;if(this._eventsCount===0)return u;for(n in a=this._events)e.call(a,n)&&u.push(t?n.slice(1):n);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(a)):u},f.prototype.listeners=function(u){var a=t?t+u:u,n=this._events[a];if(!n)return[];if(n.fn)return[n.fn];for(var m=0,c=n.length,r=new Array(c);m<c;m++)r[m]=n[m].fn;return r},f.prototype.listenerCount=function(u){var a=t?t+u:u,n=this._events[a];return n?n.fn?1:n.length:0},f.prototype.emit=function(u,a,n,m,c,r){var l=t?t+u:u;if(!this._events[l])return!1;var o=this._events[l],b=arguments.length,y,g;if(o.fn){switch(o.once&&this.removeListener(u,o.fn,void 0,!0),b){case 1:return o.fn.call(o.context),!0;case 2:return o.fn.call(o.context,a),!0;case 3:return o.fn.call(o.context,a,n),!0;case 4:return o.fn.call(o.context,a,n,m),!0;case 5:return o.fn.call(o.context,a,n,m,c),!0;case 6:return o.fn.call(o.context,a,n,m,c,r),!0}for(g=1,y=new Array(b-1);g<b;g++)y[g-1]=arguments[g];o.fn.apply(o.context,y)}else{var v=o.length,E;for(g=0;g<v;g++)switch(o[g].once&&this.removeListener(u,o[g].fn,void 0,!0),b){case 1:o[g].fn.call(o[g].context);break;case 2:o[g].fn.call(o[g].context,a);break;case 3:o[g].fn.call(o[g].context,a,n);break;case 4:o[g].fn.call(o[g].context,a,n,m);break;default:if(!y)for(E=1,y=new Array(b-1);E<b;E++)y[E-1]=arguments[E];o[g].fn.apply(o[g].context,y)}}return!0},f.prototype.on=function(u,a,n){return p(this,u,a,n,!1)},f.prototype.once=function(u,a,n){return p(this,u,a,n,!0)},f.prototype.removeListener=function(u,a,n,m){var c=t?t+u:u;if(!this._events[c])return this;if(!a)return h(this,c),this;var r=this._events[c];if(r.fn)r.fn===a&&(!m||r.once)&&(!n||r.context===n)&&h(this,c);else{for(var l=0,o=[],b=r.length;l<b;l++)(r[l].fn!==a||m&&!r[l].once||n&&r[l].context!==n)&&o.push(r[l]);o.length?this._events[c]=o.length===1?o[0]:o:h(this,c)}return this},f.prototype.removeAllListeners=function(u){var a;return u?(a=t?t+u:u,this._events[a]&&h(this,a)):(this._events=new i,this._eventsCount=0),this},f.prototype.off=f.prototype.removeListener,f.prototype.addListener=f.prototype.on,f.prefixed=t,f.EventEmitter=f,S.exports=f})(x)),x.exports}var J=z();const U=G(J);class _ extends Error{constructor(e,t,i,s,p){super(e),this.name="SubscribeDevError",this.code=t,this.statusCode=i,this.details=s,this.requestId=p}}class D extends _{constructor(e,t,i,s){super(e,"INSUFFICIENT_BALANCE",402,{remainingCredits:t,requiredCredits:i},s),this.name="InsufficientBalanceError"}}class N extends _{constructor(e,t,i,s){super(e,"RATE_LIMIT_EXCEEDED",429,{resetTime:t,retryAfter:i},s),this.name="RateLimitError",this.resetTime=t,this.retryAfter=i}}class A extends _{constructor(e,t){super(e,"AUTHENTICATION_FAILED",401,void 0,t),this.name="AuthenticationError"}}class C extends _{constructor(e,t){super(e,"ACCESS_DENIED",403,void 0,t),this.name="AccessDeniedError"}}class P extends _{constructor(e,t){super(e,"NOT_FOUND",404,void 0,t),this.name="NotFoundError"}}class k extends _{constructor(e,t,i){super(e,"VALIDATION_ERROR",400,t,i),this.name="ValidationError"}}class j extends _{constructor(e,t){super(e,"USER_UNSUBSCRIBED",402,void 0,t),this.name="UnsubscribedError"}}class q extends _{constructor(e,t,i,s,p,h){super(e,"PLAN_UPGRADE_REQUIRED",402,{upgradeUrl:t,currentPlan:i,currentLimit:s,required:p},h),this.name="PlanUpgradeRequiredError",this.upgradeUrl=t,this.currentPlan=i,this.currentLimit=s,this.required=p}}class L extends _{constructor(e,t){super(e,"WORKFLOW_UNAVAILABLE",503,void 0,t),this.name="WorkflowUnavailableError"}}function K(S){const e=Object.values(S).filter(i=>typeof i=="number");return Object.entries(S).filter(([i,s])=>e.indexOf(+i)===-1).map(([i,s])=>s)}class ${constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const i=t[0];if(this._map.set(e,i),i&&typeof i=="object"&&"id"in i){if(this._idmap.has(i.id))throw new Error(`ID ${i.id} already exists in the registry`);this._idmap.set(i.id,e)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&typeof t=="object"&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const i={...this.get(t)??{}};delete i.id;const s={...i,...this._map.get(e)};return Object.keys(s).length?s:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function V(){return new $}const F=V();class R{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??F,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,t={path:[],schemaPath:[]}){var i;const s=e._zod.def,p={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},h=this.seen.get(e);if(h)return h.count++,t.schemaPath.includes(e)&&(h.cycle=t.path),h.schema;const f={schema:{},count:1,cycle:void 0,path:t.path};this.seen.set(e,f);const d=e._zod.toJSONSchema?.();if(d)f.schema=d;else{const n={...t,schemaPath:[...t.schemaPath,e],path:t.path},m=e._zod.parent;if(m)f.ref=m,this.process(m,n),this.seen.get(m).isParent=!0;else{const c=f.schema;switch(s.type){case"string":{const r=c;r.type="string";const{minimum:l,maximum:o,format:b,patterns:y,contentEncoding:g}=e._zod.bag;if(typeof l=="number"&&(r.minLength=l),typeof o=="number"&&(r.maxLength=o),b&&(r.format=p[b]??b,r.format===""&&delete r.format),g&&(r.contentEncoding=g),y&&y.size>0){const v=[...y];v.length===1?r.pattern=v[0].source:v.length>1&&(f.schema.allOf=[...v.map(E=>({...this.target==="draft-7"||this.target==="draft-4"||this.target==="openapi-3.0"?{type:"string"}:{},pattern:E.source}))])}break}case"number":{const r=c,{minimum:l,maximum:o,format:b,multipleOf:y,exclusiveMaximum:g,exclusiveMinimum:v}=e._zod.bag;typeof b=="string"&&b.includes("int")?r.type="integer":r.type="number",typeof v=="number"&&(this.target==="draft-4"||this.target==="openapi-3.0"?(r.minimum=v,r.exclusiveMinimum=!0):r.exclusiveMinimum=v),typeof l=="number"&&(r.minimum=l,typeof v=="number"&&this.target!=="draft-4"&&(v>=l?delete r.minimum:delete r.exclusiveMinimum)),typeof g=="number"&&(this.target==="draft-4"||this.target==="openapi-3.0"?(r.maximum=g,r.exclusiveMaximum=!0):r.exclusiveMaximum=g),typeof o=="number"&&(r.maximum=o,typeof g=="number"&&this.target!=="draft-4"&&(g<=o?delete r.maximum:delete r.exclusiveMaximum)),typeof y=="number"&&(r.multipleOf=y);break}case"boolean":{const r=c;r.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{this.target==="openapi-3.0"?(c.type="string",c.nullable=!0,c.enum=[null]):c.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{c.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const r=c,{minimum:l,maximum:o}=e._zod.bag;typeof l=="number"&&(r.minItems=l),typeof o=="number"&&(r.maxItems=o),r.type="array",r.items=this.process(s.element,{...n,path:[...n.path,"items"]});break}case"object":{const r=c;r.type="object",r.properties={};const l=s.shape;for(const y in l)r.properties[y]=this.process(l[y],{...n,path:[...n.path,"properties",y]});const o=new Set(Object.keys(l)),b=new Set([...o].filter(y=>{const g=s.shape[y]._zod;return this.io==="input"?g.optin===void 0:g.optout===void 0}));b.size>0&&(r.required=Array.from(b)),s.catchall?._zod.def.type==="never"?r.additionalProperties=!1:s.catchall?s.catchall&&(r.additionalProperties=this.process(s.catchall,{...n,path:[...n.path,"additionalProperties"]})):this.io==="output"&&(r.additionalProperties=!1);break}case"union":{const r=c,l=s.options.map((o,b)=>this.process(o,{...n,path:[...n.path,"anyOf",b]}));r.anyOf=l;break}case"intersection":{const r=c,l=this.process(s.left,{...n,path:[...n.path,"allOf",0]}),o=this.process(s.right,{...n,path:[...n.path,"allOf",1]}),b=g=>"allOf"in g&&Object.keys(g).length===1,y=[...b(l)?l.allOf:[l],...b(o)?o.allOf:[o]];r.allOf=y;break}case"tuple":{const r=c;r.type="array";const l=this.target==="draft-2020-12"?"prefixItems":"items",o=this.target==="draft-2020-12"||this.target==="openapi-3.0"?"items":"additionalItems",b=s.items.map((E,B)=>this.process(E,{...n,path:[...n.path,l,B]})),y=s.rest?this.process(s.rest,{...n,path:[...n.path,o,...this.target==="openapi-3.0"?[s.items.length]:[]]}):null;this.target==="draft-2020-12"?(r.prefixItems=b,y&&(r.items=y)):this.target==="openapi-3.0"?(r.items={anyOf:b},y&&r.items.anyOf.push(y),r.minItems=b.length,y||(r.maxItems=b.length)):(r.items=b,y&&(r.additionalItems=y));const{minimum:g,maximum:v}=e._zod.bag;typeof g=="number"&&(r.minItems=g),typeof v=="number"&&(r.maxItems=v);break}case"record":{const r=c;r.type="object",(this.target==="draft-7"||this.target==="draft-2020-12")&&(r.propertyNames=this.process(s.keyType,{...n,path:[...n.path,"propertyNames"]})),r.additionalProperties=this.process(s.valueType,{...n,path:[...n.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{const r=c,l=K(s.entries);l.every(o=>typeof o=="number")&&(r.type="number"),l.every(o=>typeof o=="string")&&(r.type="string"),r.enum=l;break}case"literal":{const r=c,l=[];for(const o of s.values)if(o===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof o=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");l.push(Number(o))}else l.push(o);if(l.length!==0)if(l.length===1){const o=l[0];r.type=o===null?"null":typeof o,this.target==="draft-4"||this.target==="openapi-3.0"?r.enum=[o]:r.const=o}else l.every(o=>typeof o=="number")&&(r.type="number"),l.every(o=>typeof o=="string")&&(r.type="string"),l.every(o=>typeof o=="boolean")&&(r.type="string"),l.every(o=>o===null)&&(r.type="null"),r.enum=l;break}case"file":{const r=c,l={type:"string",format:"binary",contentEncoding:"binary"},{minimum:o,maximum:b,mime:y}=e._zod.bag;o!==void 0&&(l.minLength=o),b!==void 0&&(l.maxLength=b),y?y.length===1?(l.contentMediaType=y[0],Object.assign(r,l)):r.anyOf=y.map(g=>({...l,contentMediaType:g})):Object.assign(r,l);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const r=this.process(s.innerType,n);this.target==="openapi-3.0"?(f.ref=s.innerType,c.nullable=!0):c.anyOf=[r,{type:"null"}];break}case"nonoptional":{this.process(s.innerType,n),f.ref=s.innerType;break}case"success":{const r=c;r.type="boolean";break}case"default":{this.process(s.innerType,n),f.ref=s.innerType,c.default=JSON.parse(JSON.stringify(s.defaultValue));break}case"prefault":{this.process(s.innerType,n),f.ref=s.innerType,this.io==="input"&&(c._prefault=JSON.parse(JSON.stringify(s.defaultValue)));break}case"catch":{this.process(s.innerType,n),f.ref=s.innerType;let r;try{r=s.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}c.default=r;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const r=c,l=e._zod.pattern;if(!l)throw new Error("Pattern not found in template literal");r.type="string",r.pattern=l.source;break}case"pipe":{const r=this.io==="input"?s.in._zod.def.type==="transform"?s.out:s.in:s.out;this.process(r,n),f.ref=r;break}case"readonly":{this.process(s.innerType,n),f.ref=s.innerType,c.readOnly=!0;break}case"promise":{this.process(s.innerType,n),f.ref=s.innerType;break}case"optional":{this.process(s.innerType,n),f.ref=s.innerType;break}case"lazy":{const r=e._zod.innerType;this.process(r,n),f.ref=r;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}case"function":{if(this.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema");break}}}}const u=this.metadataRegistry.get(e);return u&&Object.assign(f.schema,u),this.io==="input"&&w(e)&&(delete f.schema.examples,delete f.schema.default),this.io==="input"&&f.schema._prefault&&((i=f.schema).default??(i.default=f.schema._prefault)),delete f.schema._prefault,this.seen.get(e).schema}emit(e,t){const i={cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0},s=this.seen.get(e);if(!s)throw new Error("Unprocessed schema. This is a bug in Zod.");const p=a=>{const n=this.target==="draft-2020-12"?"$defs":"definitions";if(i.external){const l=i.external.registry.get(a[0])?.id,o=i.external.uri??(y=>y);if(l)return{ref:o(l)};const b=a[1].defId??a[1].schema.id??`schema${this.counter++}`;return a[1].defId=b,{defId:b,ref:`${o("__shared")}#/${n}/${b}`}}if(a[1]===s)return{ref:"#"};const c=`#/${n}/`,r=a[1].schema.id??`__schema${this.counter++}`;return{defId:r,ref:c+r}},h=a=>{if(a[1].schema.$ref)return;const n=a[1],{ref:m,defId:c}=p(a);n.def={...n.schema},c&&(n.defId=c);const r=n.schema;for(const l in r)delete r[l];r.$ref=m};if(i.cycles==="throw")for(const a of this.seen.entries()){const n=a[1];if(n.cycle)throw new Error(`Cycle detected: #/${n.cycle?.join("/")}/<root> Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const a of this.seen.entries()){const n=a[1];if(e===a[0]){h(a);continue}if(i.external){const c=i.external.registry.get(a[0])?.id;if(e!==a[0]&&c){h(a);continue}}if(this.metadataRegistry.get(a[0])?.id){h(a);continue}if(n.cycle){h(a);continue}if(n.count>1&&i.reused==="ref"){h(a);continue}}const f=(a,n)=>{const m=this.seen.get(a),c=m.def??m.schema,r={...c};if(m.ref===null)return;const l=m.ref;if(m.ref=null,l){f(l,n);const o=this.seen.get(l).schema;o.$ref&&(n.target==="draft-7"||n.target==="draft-4"||n.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(o)):(Object.assign(c,o),Object.assign(c,r))}m.isParent||this.override({zodSchema:a,jsonSchema:c,path:m.path??[]})};for(const a of[...this.seen.entries()].reverse())f(a[0],{target:this.target});const d={};if(this.target==="draft-2020-12"?d.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?d.$schema="http://json-schema.org/draft-07/schema#":this.target==="draft-4"?d.$schema="http://json-schema.org/draft-04/schema#":this.target==="openapi-3.0"||console.warn(`Invalid target: ${this.target}`),i.external?.uri){const a=i.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");d.$id=i.external.uri(a)}Object.assign(d,s.def);const u=i.external?.defs??{};for(const a of this.seen.entries()){const n=a[1];n.def&&n.defId&&(u[n.defId]=n.def)}i.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?d.$defs=u:d.definitions=u);try{return JSON.parse(JSON.stringify(d))}catch{throw new Error("Error converting schema to JSON.")}}}function W(S,e){if(S instanceof $){const i=new R(e),s={};for(const f of S._idmap.entries()){const[d,u]=f;i.process(u)}const p={},h={registry:S,uri:e?.uri,defs:s};for(const f of S._idmap.entries()){const[d,u]=f;p[d]=i.emit(u,{...e,external:h})}if(Object.keys(s).length>0){const f=i.target==="draft-2020-12"?"$defs":"definitions";p.__shared={[f]:s}}return{schemas:p}}const t=new R(e);return t.process(S),t.emit(S,e)}function w(S,e){const t=e??{seen:new Set};if(t.seen.has(S))return!1;t.seen.add(S);const s=S._zod.def;switch(s.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return w(s.element,t);case"object":{for(const p in s.shape)if(w(s.shape[p],t))return!0;return!1}case"union":{for(const p of s.options)if(w(p,t))return!0;return!1}case"intersection":return w(s.left,t)||w(s.right,t);case"tuple":{for(const p of s.items)if(w(p,t))return!0;return!!(s.rest&&w(s.rest,t))}case"record":return w(s.keyType,t)||w(s.valueType,t);case"map":return w(s.keyType,t)||w(s.valueType,t);case"set":return w(s.valueType,t);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return w(s.innerType,t);case"lazy":return w(s.getter(),t);case"default":return w(s.innerType,t);case"prefault":return w(s.innerType,t);case"custom":return!1;case"transform":return!0;case"pipe":return w(s.in,t)||w(s.out,t);case"success":return!1;case"catch":return!1;case"function":return!1}throw new Error(`Unknown schema type: ${s.type}`)}class T extends U{constructor(e){super(),this._isConsumed=!1,this._accumulatedResult=null,this._promiseResolver=null,this._promiseRejecter=null,this._consumePromise=null,this.sourceIterable=e}async*[Symbol.asyncIterator](){if(this._isConsumed)throw new Error("StreamableResponse can only be consumed once. Use .clone() to consume multiple times.");this._isConsumed=!0;try{for await(const e of this.sourceIterable)this._accumulatedResult=e,this.emit("data",e),yield e;this.emit("end"),this._promiseResolver&&this._accumulatedResult!==null&&this._promiseResolver(this._accumulatedResult)}catch(e){const t=e instanceof Error?e:new Error(String(e));throw this.emit("error",t),this._promiseRejecter&&this._promiseRejecter(t),t}}then(e,t){return this._consumePromise||(this._consumePromise=new Promise((i,s)=>{this._promiseResolver=i,this._promiseRejecter=s,this._isConsumed||this._consumeInBackground()})),this._consumePromise.then(e,t)}catch(e){return this.then(void 0,e)}finally(e){return this.then(t=>(e?.(),t),t=>{throw e?.(),t})}on(e,t){return e==="data"&&!this._isConsumed&&!this._consumePromise&&this._consumeInBackground(),super.on(e,t)}once(e,t){return e==="data"&&!this._isConsumed&&!this._consumePromise&&this._consumeInBackground(),super.once(e,t)}async _consumeInBackground(){try{for await(const e of this);}catch{}}clone(){if(this._isConsumed)throw new Error("Cannot clone a StreamableResponse that has already been consumed");return new T(this.sourceIterable)}get isConsumed(){return this._isConsumed}}function Z(){return`req_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}class O extends U{constructor(e){super(),this.__LOCAL_CLIENT_WITH_EVENTS__=!0;const t=e.baseUrl||"https://api.subscribe.dev";if(this._config={baseUrl:t,authorizationUrl:e.authorizationUrl||t.replace("api","auth"),timeout:e.timeout||6e5,maxRetries:e.maxRetries||2,debug:e.debug||!1,...e},this.queue=new M({concurrency:10,interval:6e4,intervalCap:60}),this.fetch=globalThis.fetch?.bind(globalThis),!this.fetch)throw new Error("fetch is not available. Please provide a fetch polyfill.");this.debug("SubscribeDevClient initialized",{baseUrl:this._config.baseUrl})}get config(){return this._config}get pricingUrl(){return`${this._config.baseUrl}/subscribe`}get authorizationUrl(){return!this._config.accessToken&&!this._config.apiKey?`${this._config.authorizationUrl}/demo`:this._config.authorizationUrl}run(e,t,i){const{input:s,response_format:p,stream:h}=t,f=i?.streamBy||"chunk",d=Z(),u=Date.now();this.emit("ai-call-start",{type:"ai-call-start",timestamp:u,requestId:d,model:e,input:s,responseFormat:p,isStreaming:!!h}),console.log("[SubscribeDevClient] STREAMING DEBUG - Starting prediction",{model:e,input:typeof s,response_format:p,stream:h,streamFromOptions:t.stream,streamTruthy:!!h,streamType:typeof h,optionsKeys:Object.keys(t)}),console.log("[SubscribeDevClient] STREAMING DEBUG - Stream parameter check",{stream:h,streamFromOptions:t.stream,streamTruthy:!!h,optionsStream:"stream"in t,streamValue:t.stream});const a={model:e,input:t.input};if(t.response_format&&(a.response_format=this.processResponseFormat(t.response_format)),h&&(a.stream=!0,console.log("[SubscribeDevClient] STREAMING DEBUG - Added stream to payload",{stream:h,requestPayload:a})),console.log("[SubscribeDevClient] STREAMING DEBUG - Final request payload",{requestPayload:a,hasStream:"stream"in a,streamValue:a.stream}),console.log("[SubscribeDevClient] STREAMING DEBUG - Request payload stringified",{payloadString:JSON.stringify(a)}),h){console.log("[SubscribeDevClient] STREAMING DEBUG - Creating lazy streaming response");const n=this,m={[Symbol.asyncIterator]:async function*(){try{console.log("[SubscribeDevClient] STREAMING DEBUG - Starting lazy request execution");const c=await n.makeStreamingRequest("POST","/v1/run",a,f,t.signal);n.debug("Streaming request completed successfully:",{type:typeof c,hasAsyncIterator:!!(c&&typeof c[Symbol.asyncIterator]=="function"),isAsyncIterable:c instanceof Object&&Symbol.asyncIterator in c}),n.emit("usage-changed",{operation:"run",model:e});let r=[];for await(const l of c)r.push(l),yield l;n.emit("ai-call-complete",{type:"ai-call-complete",timestamp:Date.now(),requestId:d,model:e,input:s,output:r,duration:Date.now()-u,success:!0,responseFormat:p,isStreaming:!0})}catch(c){throw n.debug("Streaming request failed:",{error:c instanceof Error?c.message:String(c),errorType:c instanceof Error?c.constructor.name:typeof c}),n.emit("ai-call-error",{type:"ai-call-error",timestamp:Date.now(),requestId:d,model:e,input:s,error:c instanceof Error?c.message:String(c),duration:Date.now()-u,success:!1,responseFormat:p,isStreaming:!0}),c}}};return new T(m)}else return console.log("[SubscribeDevClient] STREAMING DEBUG - Making regular request (stream was false)",{stream:h,streamTruthy:!!h,requestPayload:a}),(async()=>{try{const n=await this.makeRequest("POST","/v1/run",a,t.signal);if(this.debug("Prediction completed",{hasOutput:!!n.output}),this.emit("usage-changed",{operation:"run",model:e}),this.isZodSchema(t?.response_format))try{const m=t.response_format,c=n.output?.[0]??"{}";n.output[0]=m.parse(typeof c=="string"?JSON.parse(c):c)}catch(m){console.error("Could not parse incoming record to Zod schema: ",m,n.output[0])}return this.emit("ai-call-complete",{type:"ai-call-complete",timestamp:Date.now(),requestId:d,model:e,input:s,output:n.output,duration:Date.now()-u,success:!0,responseFormat:p,isStreaming:!1}),n}catch(n){throw this.emit("ai-call-error",{type:"ai-call-error",timestamp:Date.now(),requestId:d,model:e,input:s,error:n instanceof Error?n.message:String(n),duration:Date.now()-u,success:!1,responseFormat:p,isStreaming:!1}),n}})()}processResponseFormat(e){return this.isZodSchema(e)?this.convertZodSchema(e,"native Zod schema"):e}isZodSchema(e){return e&&typeof e=="object"&&(typeof e._def=="object"||typeof e.parse=="function")&&!e.type}convertZodSchema(e,t){if(!e||typeof e!="object")return this.debug("Invalid Zod schema provided, falling back to json_object",{source:t}),{type:"json_object"};try{return{type:"json_schema",json_schema:{name:e._def?.typeName||"ZodSchema",strict:!0,schema:W(e)}}}catch(i){const s=i instanceof Error?i.message:"Unknown error";return this.debug("Failed to convert Zod schema, falling back to json_object",{error:s,source:t}),{type:"json_object"}}}async getBalance(){const t=(await this.makeRequest("GET","/v1/subscriptions/usage")).credits?.userBalance;return{allocatedCredits:t?.allocatedCredits||0,usedCredits:t?.usedCredits||0,remainingCredits:t?.remainingCredits||0}}async getStorage(e={}){const t=new URLSearchParams;e.appVersion&&t.set("appVersion",e.appVersion);const i=`/v1/storage${t.toString()?"?"+t.toString():""}`;return this.makeRequest("GET",i)}async setStorage(e,t={}){const i=new URLSearchParams;t.appVersion&&i.set("appVersion",t.appVersion);const s=`/v1/storage${i.toString()?"?"+i.toString():""}`;return this.makeRequest("PUT",s,{sessionData:e})}async deleteStorage(e={}){const t=new URLSearchParams;e.appVersion&&t.set("appVersion",e.appVersion);const i=`/v1/storage${t.toString()?"?"+t.toString():""}`;await this.makeRequest("DELETE",i)}async getSubscriptionStatus(){if(console.log("[SubscribeDevClient] getSubscriptionStatus called"),!this._config.userKey)throw console.log("[SubscribeDevClient] No userKey provided, throwing ValidationError"),new k("User key is required to get subscription status. Provide userKey in client configuration.",{method:"getSubscriptionStatus"});console.log("[SubscribeDevClient] Making request to /v1/subscriptions/plan with userKey:",this._config.userKey.substring(0,10)+"...");try{const e=await this.makeRequest("GET","/v1/subscriptions/plan");console.log("[SubscribeDevClient] Received response:",{hasUserPlan:!!e.userPlan,planId:e.userPlan?.planId,status:e.userPlan?.status,hasPlanDetails:!!e.userPlan?.plan});const t=e.userPlan;if(!t||t.status==="none"||!t.plan)return console.log("[SubscribeDevClient] User has no active subscription, returning none status"),{hasActiveSubscription:!1,status:t?.status||"none"};const i={hasActiveSubscription:t.status==="active",plan:t.plan?{id:t.plan.id||t.planId,name:t.plan.name,price:t.plan.price,tokenLimit:t.plan.tokenLimit||t.plan.token_limit,subtitle:t.plan.subtitle,description:t.plan.description,features:t.plan.features}:void 0,status:t.status,startedAt:t.startedAt,endsAt:t.endsAt};return console.log("[SubscribeDevClient] Returning subscription statuSSSSs:",{hasActiveSubscription:i.hasActiveSubscription,status:i.status,planName:i.plan?.name}),i}catch(e){throw console.log("[SubscribeDevClient] Error in getSubscriptionStatus:",{errorType:e.constructor.name,message:e.message}),e}}async getUsageLimits(){if(!this._config.userKey)throw new k("User key is required to get usage limits. Provide userKey in client configuration.",{method:"getUsageLimits"});return this.makeRequest("GET","/v1/subscriptions/usage")}async getUsage(){return this.getUsageLimits()}async getDemoProject(){if(!this._config.userKey)throw new k("User key is required to get demo project. Provide userKey in client configuration.",{method:"getDemoProject"});this.debug("Getting demo project");const e=await this.makePlatformRequest("POST","/v1/platform/projects/demo");this.debug("Demo project retrieved",{hasApiKey:!!e.apiKey,projectId:e.id,isDemo:e.isDemo});const t=e.apiKey;return console.log("Demo project API key (public and safe to share):",t),e}async uploadFile(e,t){this.debug("Starting file upload",{filename:e.name,size:e.size,type:e.type,userId:t?.userId});const i=new URLSearchParams;i.set("filename",e.name),i.set("contentType",e.type),t?.userId&&i.set("userId",t.userId);const s=`/v1/upload-url?${i.toString()}`,p=await this.makeRequest("GET",s);this.debug("Got presigned URL",{key:p.key,expiresIn:p.expiresIn});try{const h=await this.fetch(p.presignedUrl,{method:"PUT",body:e,headers:{"Content-Type":e.type},signal:AbortSignal.timeout(this._config.timeout)});if(!h.ok)throw new Error(`S3 upload failed: ${h.status} ${h.statusText}`);return this.debug("File uploaded successfully",{downloadUrl:p.downloadUrl}),p.downloadUrl}catch(h){throw this.debug("S3 upload failed",{error:h instanceof Error?h.message:String(h)}),new Error(`Failed to upload file to S3: ${h instanceof Error?h.message:"Unknown error"}`)}}async makePlatformRequest(e,t,i){const s=`${this._config.baseUrl}${t}`,p={Authorization:`Bearer ${this._config.userKey}`,"Content-Type":"application/json","User-Agent":"@subscribe.dev/client/0.1.0"},h={method:e,headers:p,signal:AbortSignal.timeout(this._config.timeout)};i&&["POST","PUT","PATCH"].includes(e)&&(h.body=JSON.stringify(i)),this.debug("Making platform request",{method:e,url:s,headers:{...p,Authorization:"[redacted]"}});const f=await this.fetch(s,h),d=await f.text();let u;try{u=d?JSON.parse(d):null}catch{u={error:{message:d}}}return f.ok||this.handleErrorResponse(f,u),this.debug("Platform request successful",{status:f.status,data:u}),u}async makeRequest(e,t,i,s){return this.queue.add(async()=>{const p=`${this._config.baseUrl}${t}`,h={"Content-Type":"application/json","User-Agent":"@subscribe.dev/client/0.1.0"};if(this._config.accessToken)h["x-sub-dev-access-token"]=this._config.accessToken,this.debug("Using universal auth with x-sub-dev-access-token",{tokenPrefix:this._config.accessToken.substring(0,10)+"..."});else if(this._config.apiKey){const n=this._config.apiKey.trim().replace(/=+$/,"");h.Authorization=`Bearer ${n}`,this.debug("Using project auth with Authorization header"),this._config.userKey&&(h["X-User-Token"]=this._config.userKey,this.debug("Adding X-User-Token for user context"))}else this.debug("No authentication tokens available - unauthenticated request");const f={method:e,headers:h,signal:s||AbortSignal.timeout(this._config.timeout)};i&&["POST","PUT","PATCH"].includes(e)&&(f.body=JSON.stringify(i),this.debug("Regular request body stringified:",{originalBody:i,stringifiedBody:f.body,bodyContainsStream:JSON.stringify(i).includes('"stream"'),streamValue:i?.stream})),this.debug("Making request",{method:e,url:p,body:i,hasStream:i?.stream,stringifiedBody:f.body,headers:{...h,Authorization:"[redacted]"}});const d=await this.fetch(p,f),u=await d.text();let a;try{a=u?JSON.parse(u):null}catch{a={error:{message:u}}}return d.ok||this.handleErrorResponse(d,a),this.debug("Request successful",{status:d.status,data:a}),a})}async makeStreamingRequest(e,t,i,s="chunk",p){const h=`${this._config.baseUrl}${t}`,f={"Content-Type":"application/json","User-Agent":"@subscribe.dev/client/0.1.0",Accept:"text/event-stream","Cache-Control":"no-cache"};if(this._config.accessToken)f["x-sub-dev-access-token"]=this._config.accessToken,this.debug("Using universal auth with x-sub-dev-access-token for streaming",{tokenPrefix:this._config.accessToken.substring(0,10)+"..."});else if(this._config.apiKey){const c=this._config.apiKey.trim().replace(/=+$/,"");f.Authorization=`Bearer ${c}`,this.debug("Using project auth with Authorization header for streaming"),this._config.userKey&&(f["X-User-Token"]=this._config.userKey,this.debug("Adding X-User-Token for user context in streaming"))}else this.debug("No authentication tokens available for streaming - unauthenticated request");const d={method:e,headers:f,signal:p||AbortSignal.timeout(this._config.timeout)};i&&["POST","PUT","PATCH"].includes(e)&&(d.body=JSON.stringify(i),this.debug("Streaming request body stringified:",{originalBody:i,stringifiedBody:d.body,bodyContainsStream:JSON.stringify(i).includes('"stream"'),streamValue:i?.stream})),this.debug("Making streaming request",{method:e,url:h,body:i,hasStream:i?.stream,stringifiedBody:d.body,headers:{...f,Authorization:"[redacted]"}}),console.log("[SubscribeDevClient] STREAMING DEBUG - About to fetch streaming request");const u=await this.fetch(h,d);if(console.log("[SubscribeDevClient] STREAMING DEBUG - Streaming response received:",{status:u.status,statusText:u.statusText,headers:Object.fromEntries(u.headers.entries()),contentType:u.headers.get("content-type"),hasBody:!!u.body,bodyLocked:u.body?.locked,ok:u.ok}),!u.ok){const c=await u.text();let r;try{r=c?JSON.parse(c):null}catch{r={error:{message:c}}}this.handleErrorResponse(u,r)}if(!u.body)throw console.log("[SubscribeDevClient] STREAMING DEBUG - No response body received"),new Error("No response body received for streaming request");console.log("[SubscribeDevClient] STREAMING DEBUG - Creating stream iterable from response body");const[a,n]=u.body.tee();console.log("[SubscribeDevClient] STREAMING DEBUG - Response body teed for safe reading");const m=this.createStreamIterable(a,s);return console.log("[SubscribeDevClient] STREAMING DEBUG - Stream iterable created:",{type:typeof m,hasAsyncIterator:!!(m&&typeof m[Symbol.asyncIterator]=="function"),constructor:m.constructor.name}),m}createStreamIterable(e,t="chunk"){return console.log("[SubscribeDevClient] STREAMING DEBUG - createStreamIterable called with streamBy:",t),{[Symbol.asyncIterator]:async function*(){const i=e.getReader(),s=new TextDecoder;let p="",h="";try{for(;;){const{done:f,value:d}=await i.read();if(f){if(p){const a=p.split(` `);for(const n of a)if(n&&n.startsWith("data: ")&&n!=="data: [DONE]")try{const m=n.slice(6),r=JSON.parse(m)?.content||"";r&&(h+=r)}catch(m){console.warn("[SubscribeDevClient] Failed to parse remaining chunk:",n,m)}h&&(yield h)}break}p+=s.decode(d,{stream:!0});const u=p.split(` `);p=u.pop()||"";for(const a of u)if(!(!a||a==="data: [DONE]")&&a.startsWith("data: "))try{const n=a.slice(6),c=JSON.parse(n)?.content||"";if(c){if(t==="chunk")h+=c,yield h;else if(t==="letter")for(const r of c)h+=r,yield h;else if(t==="word"){const r=c.split(/(\s+)/);for(let l=0;l<r.length;l++){const o=r[l];o&&(h+=o,(/[\s\p{P}]/u.test(o)||l===r.length-1)&&(yield h))}}}}catch(n){console.warn("[SubscribeDevClient] Failed to parse streaming chunk:",a,n)}}}catch(f){throw console.error("[SubscribeDevClient] Streaming error:",f),f}finally{try{i.releaseLock()}catch{}}}}}handleErrorResponse(e,t){const i=e.headers.get("x-request-id")||void 0,s=t?.error||{},p=s.message||`HTTP ${e.status}`;switch(e.status){case 400:throw new k(p,s.details,i);case 401:throw new A(p,i);case 402:throw s.code==="PLAN_UPGRADE_REQUIRED"?new q(p,s.context?.upgradeUrl,s.context?.currentPlan,s.context?.currentLimit,s.context?.required,i):s.code==="USER_UNSUBSCRIBED"||p.toLowerCase().includes("unsubscribed")||p.toLowerCase().includes("subscription")?new j(p,i):new D(p,s.details?.remainingCredits||s.context?.available,s.details?.requiredCredits||s.context?.required,i);case 403:throw new C(p,i);case 404:throw new P(p,i);case 429:throw new N(p,s.details?.resetTime,s.details?.retryAfter,i);case 503:throw s.code==="WORKFLOW_UNAVAILABLE"?new L(p,i):new _(p,s.code||"SERVICE_UNAVAILABLE",e.status,s.details||s.context,i);default:throw new _(p,s.code||"UNKNOWN_ERROR",e.status,s.details||s.context,i)}}debug(e,t){this._config.debug&&console.log(`[SubscribeDevClient] ${e}`,t||"")}static create(e){return new O(e)}}exports.AccessDeniedError=C;exports.AuthenticationError=A;exports.InsufficientBalanceError=D;exports.NotFoundError=P;exports.PlanUpgradeRequiredError=q;exports.RateLimitError=N;exports.StreamableResponse=T;exports.SubscribeDevClient=O;exports.SubscribeDevError=_;exports.UnsubscribedError=j;exports.ValidationError=k;exports.WorkflowUnavailableError=L; //# sourceMappingURL=index.cjs.map