@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) • 31.7 kB
JavaScript
(function(w,T){typeof exports=="object"&&typeof module<"u"?T(exports,require("p-queue")):typeof define=="function"&&define.amd?define(["exports","p-queue"],T):(w=typeof globalThis<"u"?globalThis:w||self,T(w.SubscribeDevClient={},w.PQueue))})(this,function(w,T){"use strict";function M(y){return y&&y.__esModule&&Object.prototype.hasOwnProperty.call(y,"default")?y.default:y}var I={exports:{}};(function(y){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function n(u,c,a){this.fn=u,this.context=c,this.once=a||!1}function p(u,c,a,r,m){if(typeof a!="function")throw new TypeError("The listener must be a function");var h=new n(a,r||u,m),s=t?t+c:c;return u._events[s]?u._events[s].fn?u._events[s]=[u._events[s],h]:u._events[s].push(h):(u._events[s]=h,u._eventsCount++),u}function d(u,c){--u._eventsCount===0?u._events=new i:delete u._events[c]}function l(){this._events=new i,this._eventsCount=0}l.prototype.eventNames=function(){var c=[],a,r;if(this._eventsCount===0)return c;for(r in a=this._events)e.call(a,r)&&c.push(t?r.slice(1):r);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(a)):c},l.prototype.listeners=function(c){var a=t?t+c:c,r=this._events[a];if(!r)return[];if(r.fn)return[r.fn];for(var m=0,h=r.length,s=new Array(h);m<h;m++)s[m]=r[m].fn;return s},l.prototype.listenerCount=function(c){var a=t?t+c:c,r=this._events[a];return r?r.fn?1:r.length:0},l.prototype.emit=function(c,a,r,m,h,s){var f=t?t+c:c;if(!this._events[f])return!1;var o=this._events[f],S=arguments.length,b,g;if(o.fn){switch(o.once&&this.removeListener(c,o.fn,void 0,!0),S){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,r),!0;case 4:return o.fn.call(o.context,a,r,m),!0;case 5:return o.fn.call(o.context,a,r,m,h),!0;case 6:return o.fn.call(o.context,a,r,m,h,s),!0}for(g=1,b=new Array(S-1);g<S;g++)b[g-1]=arguments[g];o.fn.apply(o.context,b)}else{var E=o.length,_;for(g=0;g<E;g++)switch(o[g].once&&this.removeListener(c,o[g].fn,void 0,!0),S){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,r);break;case 4:o[g].fn.call(o[g].context,a,r,m);break;default:if(!b)for(_=1,b=new Array(S-1);_<S;_++)b[_-1]=arguments[_];o[g].fn.apply(o[g].context,b)}}return!0},l.prototype.on=function(c,a,r){return p(this,c,a,r,!1)},l.prototype.once=function(c,a,r){return p(this,c,a,r,!0)},l.prototype.removeListener=function(c,a,r,m){var h=t?t+c:c;if(!this._events[h])return this;if(!a)return d(this,h),this;var s=this._events[h];if(s.fn)s.fn===a&&(!m||s.once)&&(!r||s.context===r)&&d(this,h);else{for(var f=0,o=[],S=s.length;f<S;f++)(s[f].fn!==a||m&&!s[f].once||r&&s[f].context!==r)&&o.push(s[f]);o.length?this._events[h]=o.length===1?o[0]:o:d(this,h)}return this},l.prototype.removeAllListeners=function(c){var a;return c?(a=t?t+c:c,this._events[a]&&d(this,a)):(this._events=new i,this._eventsCount=0),this},l.prototype.off=l.prototype.removeListener,l.prototype.addListener=l.prototype.on,l.prefixed=t,l.EventEmitter=l,y.exports=l})(I);var $=I.exports;const N=M($);class k extends Error{constructor(e,t,i,n,p){super(e),this.name="SubscribeDevError",this.code=t,this.statusCode=i,this.details=n,this.requestId=p}}class R extends k{constructor(e,t,i,n){super(e,"INSUFFICIENT_BALANCE",402,{remainingCredits:t,requiredCredits:i},n),this.name="InsufficientBalanceError"}}class D extends k{constructor(e,t,i,n){super(e,"RATE_LIMIT_EXCEEDED",429,{resetTime:t,retryAfter:i},n),this.name="RateLimitError",this.resetTime=t,this.retryAfter=i}}class j extends k{constructor(e,t){super(e,"AUTHENTICATION_FAILED",401,void 0,t),this.name="AuthenticationError"}}class U extends k{constructor(e,t){super(e,"ACCESS_DENIED",403,void 0,t),this.name="AccessDeniedError"}}class A extends k{constructor(e,t){super(e,"NOT_FOUND",404,void 0,t),this.name="NotFoundError"}}class O extends k{constructor(e,t,i){super(e,"VALIDATION_ERROR",400,t,i),this.name="ValidationError"}}class P extends k{constructor(e,t){super(e,"USER_UNSUBSCRIBED",402,void 0,t),this.name="UnsubscribedError"}}function G(y){const e=Object.values(y).filter(i=>typeof i=="number");return Object.entries(y).filter(([i,n])=>e.indexOf(+i)===-1).map(([i,n])=>n)}class q{constructor(){this._map=new Map,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 Map,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 n={...i,...this._map.get(e)};return Object.keys(n).length?n:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function J(){return new q}const z=J();class B{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??z,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 n=e._zod.def,p={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},d=this.seen.get(e);if(d)return d.count++,t.schemaPath.includes(e)&&(d.cycle=t.path),d.schema;const l={schema:{},count:1,cycle:void 0,path:t.path};this.seen.set(e,l);const u=e._zod.toJSONSchema?.();if(u)l.schema=u;else{const r={...t,schemaPath:[...t.schemaPath,e],path:t.path},m=e._zod.parent;if(m)l.ref=m,this.process(m,r),this.seen.get(m).isParent=!0;else{const h=l.schema;switch(n.type){case"string":{const s=h;s.type="string";const{minimum:f,maximum:o,format:S,patterns:b,contentEncoding:g}=e._zod.bag;if(typeof f=="number"&&(s.minLength=f),typeof o=="number"&&(s.maxLength=o),S&&(s.format=p[S]??S,s.format===""&&delete s.format),g&&(s.contentEncoding=g),b&&b.size>0){const E=[...b];E.length===1?s.pattern=E[0].source:E.length>1&&(l.schema.allOf=[...E.map(_=>({...this.target==="draft-7"||this.target==="draft-4"?{type:"string"}:{},pattern:_.source}))])}break}case"number":{const s=h,{minimum:f,maximum:o,format:S,multipleOf:b,exclusiveMaximum:g,exclusiveMinimum:E}=e._zod.bag;typeof S=="string"&&S.includes("int")?s.type="integer":s.type="number",typeof E=="number"&&(this.target==="draft-4"?(s.minimum=E,s.exclusiveMinimum=!0):s.exclusiveMinimum=E),typeof f=="number"&&(s.minimum=f,typeof E=="number"&&this.target!=="draft-4"&&(E>=f?delete s.minimum:delete s.exclusiveMinimum)),typeof g=="number"&&(this.target==="draft-4"?(s.maximum=g,s.exclusiveMaximum=!0):s.exclusiveMaximum=g),typeof o=="number"&&(s.maximum=o,typeof g=="number"&&this.target!=="draft-4"&&(g<=o?delete s.maximum:delete s.exclusiveMaximum)),typeof b=="number"&&(s.multipleOf=b);break}case"boolean":{const s=h;s.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":{h.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":{h.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const s=h,{minimum:f,maximum:o}=e._zod.bag;typeof f=="number"&&(s.minItems=f),typeof o=="number"&&(s.maxItems=o),s.type="array",s.items=this.process(n.element,{...r,path:[...r.path,"items"]});break}case"object":{const s=h;s.type="object",s.properties={};const f=n.shape;for(const b in f)s.properties[b]=this.process(f[b],{...r,path:[...r.path,"properties",b]});const o=new Set(Object.keys(f)),S=new Set([...o].filter(b=>{const g=n.shape[b]._zod;return this.io==="input"?g.optin===void 0:g.optout===void 0}));S.size>0&&(s.required=Array.from(S)),n.catchall?._zod.def.type==="never"?s.additionalProperties=!1:n.catchall?n.catchall&&(s.additionalProperties=this.process(n.catchall,{...r,path:[...r.path,"additionalProperties"]})):this.io==="output"&&(s.additionalProperties=!1);break}case"union":{const s=h;s.anyOf=n.options.map((f,o)=>this.process(f,{...r,path:[...r.path,"anyOf",o]}));break}case"intersection":{const s=h,f=this.process(n.left,{...r,path:[...r.path,"allOf",0]}),o=this.process(n.right,{...r,path:[...r.path,"allOf",1]}),S=g=>"allOf"in g&&Object.keys(g).length===1,b=[...S(f)?f.allOf:[f],...S(o)?o.allOf:[o]];s.allOf=b;break}case"tuple":{const s=h;s.type="array";const f=n.items.map((b,g)=>this.process(b,{...r,path:[...r.path,"prefixItems",g]}));if(this.target==="draft-2020-12"?s.prefixItems=f:s.items=f,n.rest){const b=this.process(n.rest,{...r,path:[...r.path,"items"]});this.target==="draft-2020-12"?s.items=b:s.additionalItems=b}n.rest&&(s.items=this.process(n.rest,{...r,path:[...r.path,"items"]}));const{minimum:o,maximum:S}=e._zod.bag;typeof o=="number"&&(s.minItems=o),typeof S=="number"&&(s.maxItems=S);break}case"record":{const s=h;s.type="object",this.target!=="draft-4"&&(s.propertyNames=this.process(n.keyType,{...r,path:[...r.path,"propertyNames"]})),s.additionalProperties=this.process(n.valueType,{...r,path:[...r.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 s=h,f=G(n.entries);f.every(o=>typeof o=="number")&&(s.type="number"),f.every(o=>typeof o=="string")&&(s.type="string"),s.enum=f;break}case"literal":{const s=h,f=[];for(const o of n.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");f.push(Number(o))}else f.push(o);if(f.length!==0)if(f.length===1){const o=f[0];s.type=o===null?"null":typeof o,this.target==="draft-4"?s.enum=[o]:s.const=o}else f.every(o=>typeof o=="number")&&(s.type="number"),f.every(o=>typeof o=="string")&&(s.type="string"),f.every(o=>typeof o=="boolean")&&(s.type="string"),f.every(o=>o===null)&&(s.type="null"),s.enum=f;break}case"file":{const s=h,f={type:"string",format:"binary",contentEncoding:"binary"},{minimum:o,maximum:S,mime:b}=e._zod.bag;o!==void 0&&(f.minLength=o),S!==void 0&&(f.maxLength=S),b?b.length===1?(f.contentMediaType=b[0],Object.assign(s,f)):s.anyOf=b.map(g=>({...f,contentMediaType:g})):Object.assign(s,f);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const s=this.process(n.innerType,r);h.anyOf=[s,{type:"null"}];break}case"nonoptional":{this.process(n.innerType,r),l.ref=n.innerType;break}case"success":{const s=h;s.type="boolean";break}case"default":{this.process(n.innerType,r),l.ref=n.innerType,h.default=JSON.parse(JSON.stringify(n.defaultValue));break}case"prefault":{this.process(n.innerType,r),l.ref=n.innerType,this.io==="input"&&(h._prefault=JSON.parse(JSON.stringify(n.defaultValue)));break}case"catch":{this.process(n.innerType,r),l.ref=n.innerType;let s;try{s=n.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}h.default=s;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const s=h,f=e._zod.pattern;if(!f)throw new Error("Pattern not found in template literal");s.type="string",s.pattern=f.source;break}case"pipe":{const s=this.io==="input"?n.in._zod.def.type==="transform"?n.out:n.in:n.out;this.process(s,r),l.ref=s;break}case"readonly":{this.process(n.innerType,r),l.ref=n.innerType,h.readOnly=!0;break}case"promise":{this.process(n.innerType,r),l.ref=n.innerType;break}case"optional":{this.process(n.innerType,r),l.ref=n.innerType;break}case"lazy":{const s=e._zod.innerType;this.process(s,r),l.ref=s;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const c=this.metadataRegistry.get(e);return c&&Object.assign(l.schema,c),this.io==="input"&&v(e)&&(delete l.schema.examples,delete l.schema.default),this.io==="input"&&l.schema._prefault&&((i=l.schema).default??(i.default=l.schema._prefault)),delete l.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},n=this.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const p=a=>{const r=this.target==="draft-2020-12"?"$defs":"definitions";if(i.external){const f=i.external.registry.get(a[0])?.id,o=i.external.uri??(b=>b);if(f)return{ref:o(f)};const S=a[1].defId??a[1].schema.id??`schema${this.counter++}`;return a[1].defId=S,{defId:S,ref:`${o("__shared")}#/${r}/${S}`}}if(a[1]===n)return{ref:"#"};const h=`#/${r}/`,s=a[1].schema.id??`__schema${this.counter++}`;return{defId:s,ref:h+s}},d=a=>{if(a[1].schema.$ref)return;const r=a[1],{ref:m,defId:h}=p(a);r.def={...r.schema},h&&(r.defId=h);const s=r.schema;for(const f in s)delete s[f];s.$ref=m};if(i.cycles==="throw")for(const a of this.seen.entries()){const r=a[1];if(r.cycle)throw new Error(`Cycle detected: #/${r.cycle?.join("/")}/<root>
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const a of this.seen.entries()){const r=a[1];if(e===a[0]){d(a);continue}if(i.external){const h=i.external.registry.get(a[0])?.id;if(e!==a[0]&&h){d(a);continue}}if(this.metadataRegistry.get(a[0])?.id){d(a);continue}if(r.cycle){d(a);continue}if(r.count>1&&i.reused==="ref"){d(a);continue}}const l=(a,r)=>{const m=this.seen.get(a),h=m.def??m.schema,s={...h};if(m.ref===null)return;const f=m.ref;if(m.ref=null,f){l(f,r);const o=this.seen.get(f).schema;o.$ref&&(r.target==="draft-7"||r.target==="draft-4")?(h.allOf=h.allOf??[],h.allOf.push(o)):(Object.assign(h,o),Object.assign(h,s))}m.isParent||this.override({zodSchema:a,jsonSchema:h,path:m.path??[]})};for(const a of[...this.seen.entries()].reverse())l(a[0],{target:this.target});const u={};if(this.target==="draft-2020-12"?u.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?u.$schema="http://json-schema.org/draft-07/schema#":this.target==="draft-4"?u.$schema="http://json-schema.org/draft-04/schema#":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");u.$id=i.external.uri(a)}Object.assign(u,n.def);const c=i.external?.defs??{};for(const a of this.seen.entries()){const r=a[1];r.def&&r.defId&&(c[r.defId]=r.def)}i.external||Object.keys(c).length>0&&(this.target==="draft-2020-12"?u.$defs=c:u.definitions=c);try{return JSON.parse(JSON.stringify(u))}catch{throw new Error("Error converting schema to JSON.")}}}function L(y,e){if(y instanceof q){const i=new B(e),n={};for(const l of y._idmap.entries()){const[u,c]=l;i.process(c)}const p={},d={registry:y,uri:e?.uri,defs:n};for(const l of y._idmap.entries()){const[u,c]=l;p[u]=i.emit(c,{...e,external:d})}if(Object.keys(n).length>0){const l=i.target==="draft-2020-12"?"$defs":"definitions";p.__shared={[l]:n}}return{schemas:p}}const t=new B(e);return t.process(y),t.emit(y,e)}function v(y,e){const t=e??{seen:new Set};if(t.seen.has(y))return!1;t.seen.add(y);const n=y._zod.def;switch(n.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 v(n.element,t);case"object":{for(const p in n.shape)if(v(n.shape[p],t))return!0;return!1}case"union":{for(const p of n.options)if(v(p,t))return!0;return!1}case"intersection":return v(n.left,t)||v(n.right,t);case"tuple":{for(const p of n.items)if(v(p,t))return!0;return!!(n.rest&&v(n.rest,t))}case"record":return v(n.keyType,t)||v(n.valueType,t);case"map":return v(n.keyType,t)||v(n.valueType,t);case"set":return v(n.valueType,t);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return v(n.innerType,t);case"lazy":return v(n.getter(),t);case"default":return v(n.innerType,t);case"prefault":return v(n.innerType,t);case"custom":return!1;case"transform":return!0;case"pipe":return v(n.in,t)||v(n.out,t);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${n.type}`)}class x extends N{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,n)=>{this._promiseResolver=i,this._promiseRejecter=n,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 x(this.sourceIterable)}get isConsumed(){return this._isConsumed}}class C extends N{constructor(e){super();const t=e.baseUrl||"https://api.subscribe.dev";if(this.config={baseUrl:t,authorizationUrl:e.authorizationUrl||t.replace("api","auth"),timeout:e.timeout||3e5,maxRetries:e.maxRetries||2,debug:e.debug||!1,...e},this.queue=new T({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 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:n,response_format:p,stream:d}=t,l=i?.streamBy||"chunk";console.log("[SubscribeDevClient] STREAMING DEBUG - Starting prediction",{model:e,input:typeof n,response_format:p,stream:d,streamFromOptions:t.stream,streamTruthy:!!d,streamType:typeof d,optionsKeys:Object.keys(t)}),console.log("[SubscribeDevClient] STREAMING DEBUG - Stream parameter check",{stream:d,streamFromOptions:t.stream,streamTruthy:!!d,optionsStream:"stream"in t,streamValue:t.stream});const u={model:e,input:t.input};if(t.response_format&&(u.response_format=this.processResponseFormat(t.response_format)),d&&(u.stream=!0,console.log("[SubscribeDevClient] STREAMING DEBUG - Added stream to payload",{stream:d,requestPayload:u})),console.log("[SubscribeDevClient] STREAMING DEBUG - Final request payload",{requestPayload:u,hasStream:"stream"in u,streamValue:u.stream}),console.log("[SubscribeDevClient] STREAMING DEBUG - Request payload stringified",{payloadString:JSON.stringify(u)}),d){console.log("[SubscribeDevClient] STREAMING DEBUG - Creating lazy streaming response");const c=this,a={[Symbol.asyncIterator]:async function*(){try{console.log("[SubscribeDevClient] STREAMING DEBUG - Starting lazy request execution");const r=await c.makeStreamingRequest("POST","/v1/run",u,l);c.debug("Streaming request completed successfully:",{type:typeof r,hasAsyncIterator:!!(r&&typeof r[Symbol.asyncIterator]=="function"),isAsyncIterable:r instanceof Object&&Symbol.asyncIterator in r}),c.emit("usage-changed",{operation:"run",model:e});for await(const m of r)yield m}catch(r){throw c.debug("Streaming request failed:",{error:r instanceof Error?r.message:String(r),errorType:r instanceof Error?r.constructor.name:typeof r}),r}}};return new x(a)}else return console.log("[SubscribeDevClient] STREAMING DEBUG - Making regular request (stream was false)",{stream:d,streamTruthy:!!d,requestPayload:u}),(async()=>{const c=await this.makeRequest("POST","/v1/run",u);if(this.debug("Prediction completed",{hasOutput:!!c.output}),this.emit("usage-changed",{operation:"run",model:e}),this.isZodSchema(t?.response_format))try{const a=t.response_format,r=c.output?.[0]??"{}";c.output[0]=a.parse(typeof r=="string"?JSON.parse(r):r)}catch(a){console.error("Could not parse incoming record to Zod schema: ",a,c.output[0])}return c})()}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:L(e)}}}catch(i){const n=i instanceof Error?i.message:"Unknown error";return this.debug("Failed to convert Zod schema, falling back to json_object",{error:n,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 n=`/v1/storage${i.toString()?"?"+i.toString():""}`;return this.makeRequest("PUT",n,{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 O("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 O("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 O("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 makePlatformRequest(e,t,i){const n=`${this.config.baseUrl}${t}`,p={Authorization:`Bearer ${this.config.userKey}`,"Content-Type":"application/json","User-Agent":"@subscribe.dev/client/0.1.0"},d={method:e,headers:p,signal:AbortSignal.timeout(this.config.timeout)};i&&["POST","PUT","PATCH"].includes(e)&&(d.body=JSON.stringify(i)),this.debug("Making platform request",{method:e,url:n,headers:{...p,Authorization:"[redacted]"}});const l=await this.fetch(n,d),u=await l.text();let c;try{c=u?JSON.parse(u):null}catch{c={error:{message:u}}}return l.ok||this.handleErrorResponse(l,c),this.debug("Platform request successful",{status:l.status,data:c}),c}async makeRequest(e,t,i){return this.queue.add(async()=>{const n=`${this.config.baseUrl}${t}`,p={"Content-Type":"application/json","User-Agent":"@subscribe.dev/client/0.1.0"};this.config.accessToken?(p["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)+"..."})):this.config.apiKey?(p.Authorization=`Bearer ${this.config.apiKey}`,this.debug("Using project auth with Authorization header"),this.config.userKey&&(p["X-User-Token"]=this.config.userKey,this.debug("Adding X-User-Token for user context"))):this.debug("No authentication tokens available - unauthenticated request");const d={method:e,headers:p,signal:AbortSignal.timeout(this.config.timeout)};i&&["POST","PUT","PATCH"].includes(e)&&(d.body=JSON.stringify(i),this.debug("Regular request body stringified:",{originalBody:i,stringifiedBody:d.body,bodyContainsStream:JSON.stringify(i).includes('"stream"'),streamValue:i?.stream})),this.debug("Making request",{method:e,url:n,body:i,hasStream:i?.stream,stringifiedBody:d.body,headers:{...p,Authorization:"[redacted]"}});const l=await this.fetch(n,d),u=await l.text();let c;try{c=u?JSON.parse(u):null}catch{c={error:{message:u}}}return l.ok||this.handleErrorResponse(l,c),this.debug("Request successful",{status:l.status,data:c}),c})}async makeStreamingRequest(e,t,i,n="chunk"){const p=`${this.config.baseUrl}${t}`,d={"Content-Type":"application/json","User-Agent":"@subscribe.dev/client/0.1.0",Accept:"text/event-stream","Cache-Control":"no-cache"};this.config.accessToken?(d["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)+"..."})):this.config.apiKey?(d.Authorization=`Bearer ${this.config.apiKey}`,this.debug("Using project auth with Authorization header for streaming"),this.config.userKey&&(d["X-User-Token"]=this.config.userKey,this.debug("Adding X-User-Token for user context in streaming"))):this.debug("No authentication tokens available for streaming - unauthenticated request");const l={method:e,headers:d,signal:AbortSignal.timeout(this.config.timeout)};i&&["POST","PUT","PATCH"].includes(e)&&(l.body=JSON.stringify(i),this.debug("Streaming request body stringified:",{originalBody:i,stringifiedBody:l.body,bodyContainsStream:JSON.stringify(i).includes('"stream"'),streamValue:i?.stream})),this.debug("Making streaming request",{method:e,url:p,body:i,hasStream:i?.stream,stringifiedBody:l.body,headers:{...d,Authorization:"[redacted]"}}),console.log("[SubscribeDevClient] STREAMING DEBUG - About to fetch streaming request");const u=await this.fetch(p,l);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 m=await u.text();let h;try{h=m?JSON.parse(m):null}catch{h={error:{message:m}}}this.handleErrorResponse(u,h)}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[c,a]=u.body.tee();console.log("[SubscribeDevClient] STREAMING DEBUG - Response body teed for safe reading");const r=this.createStreamIterable(c,n);return console.log("[SubscribeDevClient] STREAMING DEBUG - Stream iterable created:",{type:typeof r,hasAsyncIterator:!!(r&&typeof r[Symbol.asyncIterator]=="function"),constructor:r.constructor.name}),r}createStreamIterable(e,t="chunk"){return console.log("[SubscribeDevClient] STREAMING DEBUG - createStreamIterable called with streamBy:",t),{[Symbol.asyncIterator]:async function*(){const i=e.getReader(),n=new TextDecoder;let p="",d="";try{for(;;){const{done:l,value:u}=await i.read();if(l){if(p){const a=p.split(`
`);for(const r of a)if(r&&r.startsWith("data: ")&&r!=="data: [DONE]")try{const m=r.slice(6),s=JSON.parse(m)?.content||"";s&&(d+=s)}catch(m){console.warn("[SubscribeDevClient] Failed to parse remaining chunk:",r,m)}d&&(yield d)}break}p+=n.decode(u,{stream:!0});const c=p.split(`
`);p=c.pop()||"";for(const a of c)if(!(!a||a==="data: [DONE]")&&a.startsWith("data: "))try{const r=a.slice(6),h=JSON.parse(r)?.content||"";if(h){if(t==="chunk")d+=h,yield d;else if(t==="letter")for(const s of h)d+=s,yield d;else if(t==="word"){const s=h.split(/(\s+)/);for(const f of s)f&&(d+=f,/[\s\p{P}]/u.test(f)&&(yield d))}}}catch(r){console.warn("[SubscribeDevClient] Failed to parse streaming chunk:",a,r)}}}catch(l){throw console.error("[SubscribeDevClient] Streaming error:",l),l}finally{try{i.releaseLock()}catch{}}}}}handleErrorResponse(e,t){const i=e.headers.get("x-request-id")||void 0,n=t?.error||{},p=n.message||`HTTP ${e.status}`;switch(e.status){case 400:throw new O(p,n.details,i);case 401:throw new j(p,i);case 402:throw n.code==="USER_UNSUBSCRIBED"||p.toLowerCase().includes("unsubscribed")||p.toLowerCase().includes("subscription")?new P(p,i):new R(p,n.details?.remainingCredits,n.details?.requiredCredits,i);case 403:throw new U(p,i);case 404:throw new A(p,i);case 429:throw new D(p,n.details?.resetTime,n.details?.retryAfter,i);default:throw new k(p,n.code||"UNKNOWN_ERROR",e.status,n.details,i)}}debug(e,t){this.config.debug&&console.log(`[SubscribeDevClient] ${e}`,t||"")}static create(e){return new C(e)}}w.AccessDeniedError=U,w.AuthenticationError=j,w.InsufficientBalanceError=R,w.NotFoundError=A,w.RateLimitError=D,w.StreamableResponse=x,w.SubscribeDevClient=C,w.SubscribeDevError=k,w.UnsubscribedError=P,w.ValidationError=O,Object.defineProperty(w,Symbol.toStringTag,{value:"Module"})});
//# sourceMappingURL=index.umd.js.map