socaity
Version:
SDK for Generative AI. Build AI-powered applications with ease
17 lines • 59.2 kB
JavaScript
(function(m,F){typeof exports=="object"&&typeof module<"u"?F(exports):typeof define=="function"&&define.amd?define(["exports"],F):(m=typeof globalThis<"u"?globalThis:m||self,F(m.socaity={}))})(this,function(m){"use strict";var be=Object.defineProperty;var _e=(m,F,A)=>F in m?be(m,F,{enumerable:!0,configurable:!0,writable:!0,value:A}):m[F]=A;var l=(m,F,A)=>_e(m,typeof F!="symbol"?F+"":F,A);class F extends Error{constructor(e="Invalid API key format. API keys should start with 'sk_' and be 67 characters long."){super(e),this.name="ApiKeyError",Error.captureStackTrace&&Error.captureStackTrace(this,F)}}const M=class M{constructor(e={}){l(this,"apiKey");l(this,"baseUrl");l(this,"pollInterval");l(this,"maxRetries");this.apiKey=e.apiKey,this.baseUrl=e.baseUrl||"https://api.socaity.ai/v1",this.pollInterval=e.pollInterval||5e3,this.maxRetries=e.maxRetries||3}static getInstance(){return M.instance||(M.instance=new M),M.instance}static update(e){if(e.apiKey!==void 0){if(!e.apiKey.startsWith("sk_")&&!e.apiKey.startsWith("tk_")&&!e.apiKey.startsWith("ey"))throw new F("Invalid authentication token. Use either a Socaity API key from https://www.socaity.ai or a valid JWT token.");if(e.apiKey.startsWith("sk_")&&!e.apiKey.startsWith("tk_")&&e.apiKey.length!==67)throw new F("Invalid API key format. API keys should be 67 characters long. Get your API key from https://www.socaity.ai")}const t=M.getInstance();Object.assign(t,e)}};l(M,"instance");let A=M;var g=(o=>(o.CREATED="CREATED",o.QUEUED="QUEUED",o.PROCESSING="PROCESSING",o.COMPLETED="COMPLETED",o.FAILED="FAILED",o.UNKNOWN="UNKNOWN",o))(g||{}),w=(o=>(o.INITIALIZING="INITIALIZING",o.PREPARING="PREPARING",o.SENDING="SENDING",o.TRACKING="TRACKING",o.PROCESSING_RESULT="PROCESSING_RESULT",o.COMPLETED="COMPLETED",o.FAILED="FAILED",o))(w||{});class re{async parse(e){if(e==null)return this.createErrorJob("No response received");if(typeof e=="string")try{const t=JSON.parse(e);return this.parseObject(t)}catch{return{id:"",status:g.COMPLETED,progress:{progress:1,message:null},result:e,createdAt:new Date,updatedAt:new Date}}return this.parseObject(e)}async parseObject(e){if(typeof e!="object"||e===null)return this.createErrorJob("Invalid response format");console.log("raw_response",e);const t=e,s=typeof t.id=="string"?t.id:"",i=this.parseStatus(t.status),r=this.parseProgress(t,i),n=typeof t.error=="string"?t.error:null,a=typeof t.refresh_job_url=="string"?t.refresh_job_url:void 0,c=this.parseDate(t.createdAt),f=this.parseDate(t.updatedAt);return{id:s,status:i,progress:r,result:t.result,error:n,createdAt:c,updatedAt:f,refresh_job_url:a}}createErrorJob(e){const t=new Date;return{id:"",status:g.FAILED,progress:{progress:0,message:e},result:null,error:e,createdAt:t,updatedAt:t}}parseDate(e){if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){const t=new Date(e);if(!isNaN(t.getTime()))return t}return new Date}parseStatus(e){if(typeof e!="string"||!e)return g.UNKNOWN;const t=e.toUpperCase();return{COMPLETED:g.COMPLETED,SUCCEEDED:g.COMPLETED,FINISHED:g.COMPLETED,CREATED:g.CREATED,FAILED:g.FAILED,ERROR:g.FAILED,IN_PROGRESS:g.PROCESSING,PROCESSING:g.PROCESSING,RUNNING:g.PROCESSING,BOOTING:g.PROCESSING,QUEUED:g.QUEUED,PENDING:g.QUEUED,IN_QUEUE:g.QUEUED,STARTING:g.QUEUED}[t]||g.UNKNOWN}parseProgress(e,t){let s=0,i=null;const r=e.progress;if(typeof r=="number")s=r;else if(typeof r=="string")try{s=parseFloat(r)}catch{s=0}else if(r&&typeof r=="object"){const n=r;if(typeof n.progress=="number")s=n.progress;else if(typeof n.progress=="string")try{s=parseFloat(n.progress)}catch{s=0}i=typeof n.message=="string"?n.message:null}return isNaN(s)&&(s=0),s=Math.max(0,Math.min(1,s)),t===g.COMPLETED&&(s=1),!i&&typeof e.message=="string"&&(i=e.message),{progress:s,message:i}}}var ne=Object.defineProperty,oe=(o,e,t)=>e in o?ne(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,_=(o,e,t)=>oe(o,typeof e!="symbol"?e+"":e,t);const N={mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",aac:"audio/aac",flac:"audio/flac",m4a:"audio/mp4",webm:"audio/webm"},S={mp4:"video/mp4",mov:"video/quicktime",avi:"video/x-msvideo",mkv:"video/x-matroska",wmv:"video/x-ms-wmv",webm:"video/webm","3gp":"video/3gpp",flv:"video/x-flv"},T={jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",tiff:"image/tiff",tif:"image/tiff",avif:"image/avif"},ae={pdf:"application/pdf",txt:"text/plain",html:"text/html",htm:"text/html",json:"application/json",js:"application/javascript",css:"text/css",xml:"application/xml",zip:"application/zip",csv:"text/csv",npz:"application/octet-stream"},ee={...N,...S,...T,...ae};function le(o){const e=[];switch(o){case"audio":e.push(...Object.values(N)),e.push(...Object.keys(N).map(t=>`.${t}`));break;case"video":e.push(...Object.values(S)),e.push(...Object.keys(S).map(t=>`.${t}`));break;case"image":e.push(...Object.values(T)),e.push(...Object.keys(T).map(t=>`.${t}`));break;case"file":default:return["*/*"]}return e}function ce(o){return{audio:"Audio",video:"Video",image:"Images",file:"Files"}[o]||o}function he(o){return Object.values(N).includes(o)?"audio":Object.values(S).includes(o)?"video":Object.values(T).includes(o)?"image":null}function G(o){const e=(o.startsWith(".")?o.slice(1):o).toLowerCase();return e in ee?ee[e]:null}const v=typeof window>"u";async function te(o){if(o==null)return null;if(Array.isArray(o)){const e=o.map(t=>te(t));return Promise.all(e)}if(z(o))try{return await new p().fromDict(o)}catch{return o}return o}async function ue(o){var e;if(o instanceof p)return o.getContentType();if(z(o))return o.content_type;if(Q(o))return o.type;if(typeof o=="string"&&$(o)){const t=(e=new URL(o).pathname.split(".").pop())==null?void 0:e.toLowerCase();if(t){const s=G(t);if(s)return s}try{const s=await fetch(o,{method:"HEAD",headers:{"User-Agent":"MediaFile/1.0.0"}});if(s.ok){const i=s.headers.get("content-type");if(i)return i}}catch{}}if(typeof o=="string"&&o.startsWith("data:")){const t=o.match(/^data:([^;,]+)/);if(t&&t[1])return t[1]}if(typeof o=="string"&&typeof window>"u")try{const t=await import("fs/promises"),s=await import("path");await t.access(o);const i=s.extname(o).slice(1).toLowerCase();if(i){const r=G(i);if(r)return r}}catch{}return typeof Blob<"u"&&o instanceof Blob?o.type:null}function $(o){try{const e=new URL(o);return e.protocol==="http:"||e.protocol==="https:"}catch{return!1}}function fe(o){if(typeof o!="string"||!$(o))return null;try{const e=((new URL(o).pathname||"").split("/").pop()||"").split("?")[0].split("#")[0].split("."),t=e.length>1?e.pop().toLowerCase():"";return t?G(t):null}catch{return null}}function de(o){return o.startsWith("data:")||pe(o)}function pe(o){return/^[A-Za-z0-9+/=]+$/.test(o)&&o.length%4===0}async function V(o){if(!v)return!1;try{return(await(await import("fs/promises")).stat(o)).isFile()}catch{return!1}}function Q(o){return o&&typeof o=="object"&&typeof o.data=="string"&&typeof o.type=="string"&&typeof o.name=="string"}function z(o){return o&&typeof o=="object"&&"file_name"in o&&"content_type"in o&&"content"in o}class L{static async create(e){if(e==null)throw new Error("Cannot create MediaFile from null or undefined data");const t=await ue(e);let s=U.default;return t&&t.startsWith("image/")?s=U.image:t&&t.startsWith("audio/")?s=U.audio:t&&t.startsWith("video/")&&(s=U.video),new s().fromAny(e)}}class p{constructor(e="file",t="application/octet-stream"){_(this,"content_type"),_(this,"file_name"),_(this,"_content",null),this.content_type=t,this.file_name=e}static async create(e){return L.create(e)}async fromAny(e){if(e==null)throw new Error("Cannot create MediaFile from null or undefined data");if(e instanceof p)return e;if(Q(e)){if(this.file_name=e.name||"file",this.content_type=e.type,typeof e.data=="string")return this.fromBase64(e.data);throw new Error("Invalid data format in FileReader object")}if(v&&this._isBuffer(e))return this.fromBytes(e);if(typeof File<"u"&&e instanceof File){this.file_name=e.name,this.content_type=e.type||"application/octet-stream";const t=await e.arrayBuffer();return this.fromBytes(t)}if(typeof Blob<"u"&&e instanceof Blob){const t=await e.arrayBuffer();return this.fromBytes(t)}if(e instanceof ArrayBuffer||e instanceof Uint8Array)return this.fromBytes(e);if(typeof e=="string"){if($(e))return await this.fromUrl(e);if(de(e))return this.fromBase64(e);if(await V(e))return await this.fromFile(e);throw typeof e=="string"?new Error("Invalid data type for MediaFile "+e):new Error("Invalid data type for MediaFile")}return z(e)?await this.fromDict(e):this}async fromFile(e){if(!v)throw new Error("Loading from file path is only supported in Node.js environment");try{const t=await(await import("fs/promises")).readFile(e),s=await import("path");return this.file_name=s.basename(e),this._content=this._bufferToArrayBuffer(t),this._setContentTypeFromFileName(),this}catch(t){throw new Error(`Failed to load file from path: ${e}. ${t.message}`)}}async fromUrl(e,t){const s=async(i,r)=>await fetch(i,{headers:r||{"User-Agent":"MediaFile/1.0.0"}});try{let i=await s(e,t);if(!i.ok){if(i.status===401||i.status===403){const n=new URL(e);n.search="",i=await s(n.toString(),t)}if(!i.ok)throw new Error(`HTTP error! Status: ${i.status}`)}this.content_type=i.headers.get("content-type")||"application/octet-stream";const r=i.headers.get("content-disposition");if(r){const n=r.match(/filename=(?:['"]?)([^'";\n]+)/i);n&&n[1]&&(this.file_name=n[1])}if(!this.file_name||this.file_name==="file"){const n=new URL(e).pathname.split("/"),a=n[n.length-1];a&&a.trim()!==""?this.file_name=decodeURIComponent(a):this.file_name="downloaded_file"}return this._content=await i.arrayBuffer(),this}catch(i){throw new Error(`Failed to load file from URL: ${e}. ${i.message}`)}}fromBase64(e){const{data:t,mediaType:s}=this._parseBase64Uri(e);s&&(this.content_type=s);try{return this._content=v?this._decodeBase64NodeJs(t):this._decodeBase64Browser(t),this}catch(i){throw new Error(`Failed to decode base64 data: ${i.message}`)}}fromBytes(e){if(typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer){const i=new Uint8Array(e),r=new ArrayBuffer(i.byteLength);return new Uint8Array(r).set(i),this._content=r,this}if(e instanceof Uint8Array){if(typeof SharedArrayBuffer<"u"&&e.buffer instanceof SharedArrayBuffer){const i=new ArrayBuffer(e.byteLength);new Uint8Array(i).set(e),this._content=i}else this._content=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);return this}if(v&&this._isBuffer(e)){const i=e;if(typeof SharedArrayBuffer<"u"&&i.buffer instanceof SharedArrayBuffer){const r=new ArrayBuffer(i.byteLength);new Uint8Array(r).set(i),this._content=r}else this._content=i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength);return this}const t=new Uint8Array(e),s=new ArrayBuffer(t.byteLength);return new Uint8Array(s).set(t),this._content=s,this}async fromDict(e){if(!e.content)throw new Error("Invalid FileResult object: missing content");return this.file_name=e.file_name,this.content_type=e.content_type,await this.fromAny(e.content)}toBlob(){if(this._ensureContent(),typeof Blob>"u")throw new Error("Blob is not available in this environment");return new Blob([new Uint8Array(this._content)],{type:this.content_type})}toArrayBuffer(){return this._ensureContent(),this._content}toUint8Array(){return this._ensureContent(),new Uint8Array(this._content)}toBuffer(){if(this._ensureContent(),!v)throw new Error("Buffer is only available in Node.js environment");return Buffer.from(this._content)}toBase64(e=!0){this._ensureContent();let t;if(v)t=Buffer.from(this._content).toString("base64");else{const s=new Uint8Array(this._content);let i="";const r=10240;for(let n=0;n<s.length;n+=r){const a=s.subarray(n,Math.min(n+r,s.length));i+=String.fromCharCode.apply(null,Array.from(a))}t=btoa(i)}return e?`data:${this.content_type};base64,${t}`:t}toJson(){return{file_name:this.file_name,content_type:this.content_type,content:this.toBase64()}}async save(e){this._ensureContent();const t=e||this.file_name;if(v)try{const s=await import("fs/promises").then(n=>n.default||n),i=await import("path").then(n=>n.default||n);if(!i||typeof i.dirname!="function")throw new Error("Failed to load 'path' module.");const r=i.dirname(t);r!=="."&&await s.mkdir(r,{recursive:!0}).catch(()=>{}),await s.writeFile(t,Buffer.from(this._content))}catch(s){throw new Error(`Failed to save file: ${s.message}`)}else{const s=this.toBlob(),i=URL.createObjectURL(s),r=document.createElement("a");r.href=i,r.download=t,document.body.appendChild(r),r.click(),setTimeout(()=>{document.body.removeChild(r),URL.revokeObjectURL(i)},100)}}fileSize(e="bytes"){if(!this._content)return 0;const t=this._content.byteLength;switch(e){case"kb":return t/1024;case"mb":return t/(1024*1024);case"gb":return t/(1024*1024*1024);default:return t}}get extension(){var e;if(this.content_type&&this.content_type!=="application/octet-stream"){const t={"image/jpeg":"jpg","image/png":"png","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","audio/mpeg":"mp3","audio/wav":"wav","audio/ogg":"ogg","video/mp4":"mp4","video/quicktime":"mov","application/pdf":"pdf","text/plain":"txt","text/html":"html","application/json":"json"};if(this.content_type in t)return t[this.content_type];if(v)try{const s=require("mime-types").extension(this.content_type);if(s)return s}catch{}}return this.file_name&&this.file_name.includes(".")&&((e=this.file_name.split(".").pop())==null?void 0:e.toLowerCase())||null}getFileName(){return this.file_name}setFileName(e){this.file_name=e}getContentType(){return this.content_type}setContentType(e){this.content_type=e}read(){return this._ensureContent(),this._content}isEmpty(){return!this._content||this._content.byteLength===0}getInfo(){return{fileName:this.file_name,contentType:this.content_type,size:this.fileSize(),extension:this.extension}}_setContentTypeFromFileName(){var e;if(!this.file_name)return;const t=(e=this.file_name.split(".").pop())==null?void 0:e.toLowerCase();if(!t)return;if(v)try{const i=require("mime-types").lookup(this.file_name);if(i){this.content_type=i;return}}catch{}const s={jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",mp4:"video/mp4",mov:"video/quicktime",pdf:"application/pdf",txt:"text/plain",html:"text/html",htm:"text/html",json:"application/json",js:"application/javascript",css:"text/css",xml:"application/xml",zip:"application/zip"};t in s&&(this.content_type=s[t])}_parseBase64Uri(e){if(e.startsWith("data:")){const[t,s]=e.split(",",2),i=t.match(/^data:([^;,]+)/),r=i?i[1]:null;return{data:s,mediaType:r}}return{data:e,mediaType:null}}_ensureContent(){if(!this._content)throw new Error("No content available. Load content first using fromFile, fromUrl, etc.")}_isBuffer(e){return v&&Buffer.isBuffer(e)}_decodeBase64NodeJs(e){const t=Buffer.from(e,"base64");return this._bufferToArrayBuffer(t)}_decodeBase64Browser(e){const t=atob(e),s=new Uint8Array(t.length);for(let i=0;i<t.length;i++)s[i]=t.charCodeAt(i);return s.buffer}_bufferToArrayBuffer(e){if(typeof SharedArrayBuffer<"u"&&e.buffer instanceof SharedArrayBuffer){const t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(new Uint8Array(e)),t}else return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}}class O extends p{constructor(e="image",t="image/png"){super(e,t)}static async create(e){if(e==null)throw new Error("Cannot create ImageFile from null or undefined data");return new O().fromAny(e)}async fromAny(e){if(e instanceof O)return e;if(e instanceof p&&!(e instanceof O)){if(e.isEmpty())throw new Error("Cannot create ImageFile from empty MediaFile");return this.file_name=e.getFileName()||"image",this.content_type=e.getContentType(),this._content=e.read(),this._validateImageContentType(),this}const t=await super.fromAny(e);return t.file_name=t.file_name||"image",t._validateImageContentType(),t}toImageElement(e={}){if(typeof window>"u")throw new Error("Image elements are only available in browser environments");this._ensureContent();const t=this.toBase64(),{width:s,height:i,alt:r="",className:n=""}=e,a=s?` width="${s}"`:"",c=i?` height="${i}"`:"",f=n?` class="${n}"`:"";return`<img src="${t}" alt="${r}"${a}${c}${f}>`}toDOMImageElement(e={}){if(typeof window>"u")throw new Error("DOM Image elements are only available in browser environments");this._ensureContent();const t=this.toBlob(),s=URL.createObjectURL(t),i=new Image;return e.width&&(i.width=e.width),e.height&&(i.height=e.height),e.alt&&(i.alt=e.alt),e.className&&(i.className=e.className),i.src=s,i.addEventListener("load",()=>{setTimeout(()=>URL.revokeObjectURL(s),1e3)}),i}async getDimensions(){if(typeof window>"u")throw new Error("Getting image dimensions is only available in browser environments");return new Promise((e,t)=>{const s=new Image;s.onload=()=>{e({width:s.naturalWidth,height:s.naturalHeight})},s.onerror=()=>{t(new Error("Failed to load image for dimension calculation"))};const i=this.toBlob(),r=URL.createObjectURL(i);s.src=r,s.addEventListener("load",()=>{URL.revokeObjectURL(r)},{once:!0})})}_validateImageContentType(){var e;if(this.content_type.startsWith("image/"))return;const t=(e=this.extension)==null?void 0:e.toLowerCase();if(t&&t in T){this.content_type=T[t];return}this._content&&this._detectImageFormat()}_detectImageFormat(){const e=new Uint8Array(this._content).slice(0,12);if(e[0]===255&&e[1]===216&&e[2]===255){this.content_type=T.jpeg;return}if(e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71&&e[4]===13&&e[5]===10&&e[6]===26&&e[7]===10){this.content_type=T.png;return}if(e[0]===71&&e[1]===73&&e[2]===70&&e[3]===56&&(e[4]===55||e[4]===57)&&e[5]===97){this.content_type=T.gif;return}if(e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80){this.content_type=T.webp;return}if(this._content.byteLength>100&&new TextDecoder().decode(new Uint8Array(this._content.slice(0,100))).indexOf("<svg")!==-1){this.content_type=T.svg;return}this.content_type=T.png}}class B extends p{constructor(e="audio",t="audio/wav"){super(e,t)}static async create(e){if(e==null)throw new Error("Cannot create AudioFile from null or undefined data");return new B().fromAny(e)}async fromAny(e){if(e instanceof B)return e;if(e instanceof p&&!(e instanceof B)){if(e.isEmpty())throw new Error("Cannot create AudioFile from empty MediaFile");return this.file_name=e.getFileName()||"audio",this.content_type=e.getContentType(),this._content=e.read(),this._validateAudioContentType(),this}const t=await super.fromAny(e);return t.file_name=t.file_name||"audio",t._validateAudioContentType(),t}toAudioElement(){if(typeof window>"u")throw new Error("Audio elements are only available in browser environments");this._ensureContent();const e=this.toBlob(),t=URL.createObjectURL(e),s=new Audio(t);return s.addEventListener("canplaythrough",()=>{setTimeout(()=>URL.revokeObjectURL(t),1e3)}),s}async play(){if(typeof window>"u")throw new Error("Audio playback is only available in browser environments");const e=this.toAudioElement();return new Promise((t,s)=>{e.addEventListener("play",()=>t()),e.addEventListener("error",i=>s(new Error(`Audio playback error: ${i}`))),e.play().catch(s)})}async getDuration(){if(typeof window>"u")throw new Error("Getting audio duration is only available in browser environments");const e=this.toAudioElement();return new Promise(t=>{if(e.duration&&!isNaN(e.duration)){t(e.duration);return}e.addEventListener("loadedmetadata",()=>{t(e.duration)})})}toHTMLPlayer(e={}){const t=this.toBase64(),{controls:s=!0,autoplay:i=!1,loop:r=!1}=e;return`<audio
src="${t}"
${s?"controls":""}
${i?"autoplay":""}
${r?"loop":""}>
Your browser does not support the audio element.
</audio>`}_validateAudioContentType(){var e;if(this.content_type.startsWith("audio/"))return;const t=(e=this.extension)==null?void 0:e.toLowerCase();if(t&&t in N){this.content_type=N[t];return}this._content&&this._detectAudioFormat()}_detectAudioFormat(){const e=new Uint8Array(this._content).slice(0,12);if(e[0]===73&&e[1]===68&&e[2]===51){this.content_type=N.mp3;return}if(e[0]===255&&(e[1]&224)===224){this.content_type=N.mp3;return}if(e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===65&&e[10]===86&&e[11]===69){this.content_type=N.wav;return}if(e[0]===79&&e[1]===103&&e[2]===103&&e[3]===83){this.content_type=N.ogg;return}if(e[0]===102&&e[1]===76&&e[2]===97&&e[3]===67){this.content_type=N.flac;return}this.content_type=N.mp3}}class R extends p{constructor(e="video",t="video/mp4"){super(e,t)}static async create(e){if(e==null)throw new Error("Cannot create VideoFile from null or undefined data");return new R().fromAny(e)}async fromAny(e){if(e instanceof R)return e;if(e instanceof p&&!(e instanceof R)){if(e.isEmpty())throw new Error("Cannot create VideoFile from empty MediaFile");return this.file_name=e.getFileName()||"video",this.content_type=e.getContentType(),this._content=e.read(),this._validateVideoContentType(),this}const t=await super.fromAny(e);return t.file_name=t.file_name||"video",t._validateVideoContentType(),t}toVideoElement(){if(typeof window>"u")throw new Error("Video elements are only available in browser environments");this._ensureContent();const e=this.toBlob(),t=URL.createObjectURL(e),s=document.createElement("video");return s.src=t,s.addEventListener("loadedmetadata",()=>{setTimeout(()=>URL.revokeObjectURL(t),1e3)}),s}async play(){if(typeof window>"u")throw new Error("Video playback is only available in browser environments");const e=this.toVideoElement();return new Promise((t,s)=>{e.addEventListener("play",()=>t()),e.addEventListener("error",i=>s(new Error(`Video playback error: ${i}`))),e.play().catch(s)})}async getDuration(){if(typeof window>"u")throw new Error("Getting video duration is only available in browser environments");const e=this.toVideoElement();return new Promise(t=>{if(e.duration&&!isNaN(e.duration)){t(e.duration);return}e.addEventListener("loadedmetadata",()=>{t(e.duration)})})}async getDimensions(){if(typeof window>"u")throw new Error("Getting video dimensions is only available in browser environments");const e=this.toVideoElement();return new Promise(t=>{if(e.videoWidth&&e.videoHeight){t({width:e.videoWidth,height:e.videoHeight});return}e.addEventListener("loadedmetadata",()=>{t({width:e.videoWidth,height:e.videoHeight})})})}async createThumbnail(e=0){if(typeof window>"u")throw new Error("Creating thumbnails is only available in browser environments");const t=this.toVideoElement();return new Promise((s,i)=>{t.addEventListener("loadedmetadata",async()=>{try{t.currentTime=e,await new Promise(a=>{const c=()=>{t.removeEventListener("seeked",c),a()};t.addEventListener("seeked",c)});const r=document.createElement("canvas");r.width=t.videoWidth,r.height=t.videoHeight;const n=r.getContext("2d");if(!n)throw new Error("Failed to get canvas context");n.drawImage(t,0,0,r.width,r.height),r.toBlob(a=>{a?s(a):i(new Error("Failed to create thumbnail blob"))},"image/jpeg",.95)}catch(r){i(r)}}),t.addEventListener("error",r=>{i(new Error(`Video loading error: ${r}`))})})}toHtmlPlayer(e={}){const t=this.toBase64(),{controls:s=!0,autoplay:i=!1,loop:r=!1,muted:n=!1,width:a,height:c,poster:f}=e;return`<video
src="${t}"
${s?"controls":""}
${i?"autoplay":""}
${r?"loop":""}
${n?"muted":""}
${a?`width="${a}"`:""}
${c?`height="${c}"`:""}
${f?`poster="${f}"`:""}>
Your browser does not support the video element.
</video>`}_validateVideoContentType(){var e;if(this.content_type.startsWith("video/"))return;const t=(e=this.extension)==null?void 0:e.toLowerCase();if(t&&t in S){this.content_type=S[t];return}this._content&&this._detectVideoFormat()}_detectVideoFormat(){const e=new Uint8Array(this._content).slice(0,16);if(e[4]===102&&e[5]===116&&e[6]===121&&e[7]===112){this.content_type=S.mp4;return}if(e[4]===119&&e[5]===105&&e[6]===100&&e[7]===101||e[4]===109&&e[5]===100&&e[6]===97&&e[7]===116||e[4]===102&&e[5]===114&&e[6]===101&&e[7]===101||e[4]===112&&e[5]===110&&e[6]===111&&e[7]===116||e[4]===115&&e[5]===107&&e[6]===105&&e[7]===112||e[4]===109&&e[5]===111&&e[6]===111&&e[7]===118){this.content_type=S.mov;return}if(e[0]===26&&e[1]===69&&e[2]===223&&e[3]===163){this.content_type=S.webm;return}if(e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===65&&e[9]===86&&e[10]===73&&e[11]===32){this.content_type=S.avi;return}if(e[0]===70&&e[1]===76&&e[2]===86){this.content_type=S.flv;return}if(e[4]===102&&e[5]===116&&e[6]===121&&e[7]===112&&e[8]===51&&e[9]===103&&e[10]===112){this.content_type=S["3gp"];return}this.content_type=S.mp4}}class E{constructor(e={}){_(this,"_mediaFiles",[]),_(this,"_urlFiles",[]),_(this,"_nonProcessableFiles",[]),_(this,"_mediaContainers",[]),_(this,"downloadFiles"),_(this,"readSystemFiles"),_(this,"fileName"),this.fileName=e.fileName||"MediaList",this.downloadFiles=e.downloadFiles!==void 0?e.downloadFiles:!0,this.readSystemFiles=e.readSystemFiles!==void 0?e.readSystemFiles:!0,e.files&&this._initializeFiles(e.files)}_initializeFiles(e){for(const t of e)t instanceof p?this._addMediaFile(t):this._nonProcessableFiles.push(t)}async fromAny(e){if(!e||!Array.isArray(e))return this;for(const t of e)await this._processFile(t);return this}async _processFile(e){if(e instanceof p)return this._addMediaFile(e),e;if(e==null||typeof e=="string"&&e.length===0)return this._nonProcessableFiles.push(e),e;if(typeof e=="string"){if($(e)){if(!this.downloadFiles)return this._urlFiles.push(e),e;try{const t=await L.create(e);return this._addMediaFile(t),t}catch{return this._nonProcessableFiles.push(e),e}}if(await V(e)){if(!this.readSystemFiles)return this._nonProcessableFiles.push(e),e;try{const t=await L.create(e);return this._addMediaFile(t),t}catch{return this._nonProcessableFiles.push(e),e}}}try{const t=await L.create(e);return this._addMediaFile(t),t}catch{return this._nonProcessableFiles.push(e),e}}_addMediaFile(e){this._mediaFiles.push(e),this._isMediaContainer(e)&&this._mediaContainers.push(e)}_isMediaContainer(e){return e&&typeof e=="object"&&"getProcessableFiles"in e&&"getLeafFiles"in e}get _allItems(){return[...this._mediaFiles,...this._urlFiles,...this._nonProcessableFiles]}getLeafFiles(){const e=[],t=[];for(let s=0;s<this._mediaFiles.length;s++){const i=this._mediaFiles[s];this._mediaContainers.includes(i)||(e.push(i),t.push(s))}return{files:e,indices:t}}getMediaContainers(){const e=[],t=[];for(const s of this._mediaContainers){const i=this._mediaFiles.indexOf(s);i!==-1&&(e.push(s),t.push(i))}return{containers:e,indices:t}}getProcessableFiles(e={}){const{ignoreErrors:t=!1,raiseException:s=!0,silent:i=!1}=e;if(t)return new E({files:this._mediaFiles,downloadFiles:this.downloadFiles,readSystemFiles:this.readSystemFiles,fileName:this.fileName});const r=[];for(const n of this._mediaFiles)this._mediaContainers.includes(n)||r.push(n);for(const n of this._mediaContainers){const a=n.getProcessableFiles({raiseException:!1,silent:!0});if(a.length>0)for(const c of a)r.push(c)}if(this._urlFiles.length+this._nonProcessableFiles.length>0&&(s||!i)){const n=[...this._urlFiles,...this._nonProcessableFiles],a=`Files not processed: ${JSON.stringify(n)}. Check configuration (downloadFiles=${this.downloadFiles}, readSystemFiles=${this.readSystemFiles})`;if(s)throw new Error(a);i||console.warn(a)}return new E({files:r,downloadFiles:this.downloadFiles,readSystemFiles:this.readSystemFiles,fileName:this.fileName})}getUrlFiles(){return[...this._urlFiles]}getFilePathFiles(){const e=[];for(const t of this._nonProcessableFiles)typeof t=="string"&&!$(t)&&e.push(t);return e}getNonFileParams(e=!0){const t=[...this._nonProcessableFiles];e&&t.push(...this._urlFiles);for(const s of this._mediaContainers){const i=s.getNonFileParams(e);i.length>0&&t.push(...i)}return t}toBase64(e=!0){return this._mediaFiles.map(t=>t.toBase64(e))}toBlob(){return this._mediaFiles.map(e=>e.toBlob())}toArrayBuffer(){return this._mediaFiles.map(e=>e.toArrayBuffer())}toUint8Array(){return this._mediaFiles.map(e=>e.toUint8Array())}toBuffer(){return this._mediaFiles.map(e=>e.toBuffer())}toJson(){const e=[];return e.push(...this._mediaFiles.map(t=>t.toJson())),e.push(...this._urlFiles),e.push(...this._nonProcessableFiles),e}fileSize(e="bytes"){return this._mediaFiles.reduce((t,s)=>t+s.fileSize(e),0)}async save(e){e||(e=v?process.cwd():".");let t=!1,s="",i=e;if(v){const r=await import("path"),n=r.extname(e);n&&(t=!0,s=r.basename(e,n),i=r.dirname(e));const a=await import("fs/promises");await a.mkdir(i,{recursive:!0});for(let c=0;c<this._mediaFiles.length;c++){const f=this._mediaFiles[c];let h;if(t){const b=f.extension||"bin";h=`${s}.${b}`}else h=f.getFileName()||`file_${c}`;let u=r.join(i,h),d=1;for(;;)try{await a.access(u);const b=r.extname(h),y=r.basename(h,b);u=r.join(i,`${y}_${d}${b}`),d++}catch{break}await f.save(u)}}else for(const r of this._mediaFiles)await r.save(r.getFileName())}async append(e){await this._processFile(e)}async extend(e){for(const t of e)await this._processFile(t)}pop(e=-1){const t=this._allItems;if(e<0&&(e=t.length+e),e<0||e>=t.length)throw new RangeError("Index out of range");const s=t[e],i=this._mediaFiles.indexOf(s);if(i!==-1){this._mediaFiles.splice(i,1);const a=this._mediaContainers.indexOf(s);return a!==-1&&this._mediaContainers.splice(a,1),s}const r=this._urlFiles.indexOf(s);if(r!==-1)return this._urlFiles.splice(r,1),s;const n=this._nonProcessableFiles.indexOf(s);if(n!==-1)return this._nonProcessableFiles.splice(n,1),s;throw new Error("File not found in any internal list")}get(e){const t=this._allItems;if(e<0&&(e=t.length+e),e<0||e>=t.length)throw new RangeError("Index out of range");return t[e]}toList(){return this._allItems}get length(){return this._mediaFiles.length+this._urlFiles.length+this._nonProcessableFiles.length}isEmpty(){return this.length===0}getInfo(){return{fileName:this.fileName,totalFiles:this.length,mediaFiles:this._mediaFiles.length,urlFiles:this._urlFiles.length,nonProcessableFiles:this._nonProcessableFiles.length,totalSize:this.fileSize("bytes")}}getFileName(){return this.fileName}setFileName(e){this.fileName=e}getContentType(){return"application/x-media-list"}setContentType(e){throw new Error("Cannot set content type on MediaList")}[Symbol.iterator](){let e=0;const t=this._allItems;return{next(){return e<t.length?{value:t[e++],done:!1}:{value:void 0,done:!0}}}}}class I{constructor(e={}){_(this,"_allItems",new Map),_(this,"_mediaFiles",new Set),_(this,"_urlFiles",new Set),_(this,"_nonProcessableFiles",new Set),_(this,"_mediaContainers",new Set),_(this,"downloadFiles"),_(this,"readSystemFiles"),_(this,"fileName"),this.fileName=e.fileName||"MediaDict",this.downloadFiles=e.downloadFiles!==void 0?e.downloadFiles:!0,this.readSystemFiles=e.readSystemFiles!==void 0?e.readSystemFiles:!0,e.files&&this._initializeFiles(e.files)}_initializeFiles(e){for(const[t,s]of Object.entries(e))s instanceof p||s instanceof E||s instanceof I?this._addToStorage(t,s):(this._allItems.set(t,s),this._nonProcessableFiles.add(t))}_isEmptyFile(e){return Array.isArray(e)&&e.every(t=>this._isEmptyFile(t))?!0:e==null||typeof e=="string"&&e.length===0}_removeFromAllSets(e){this._mediaFiles.delete(e),this._urlFiles.delete(e),this._nonProcessableFiles.delete(e),this._mediaContainers.delete(e)}_addToStorage(e,t){this._removeFromAllSets(e),this._allItems.set(e,t),(t instanceof p||t instanceof E||t instanceof I)&&(this._mediaFiles.add(e),(t instanceof E||t instanceof I)&&this._mediaContainers.add(e))}async _processFile(e,t){if(this._removeFromAllSets(e),t instanceof p||t instanceof E||t instanceof I)return this._addToStorage(e,t),t;if(this._isEmptyFile(t))return this._allItems.set(e,t),this._nonProcessableFiles.add(e),t;if(typeof t=="string"){if($(t)){if(!this.downloadFiles)return this._allItems.set(e,t),this._urlFiles.add(e),t;try{const s=await L.create(t);return this._addToStorage(e,s),s}catch{return this._allItems.set(e,t),this._nonProcessableFiles.add(e),t}}if(await V(t)){if(!this.readSystemFiles)return this._allItems.set(e,t),this._nonProcessableFiles.add(e),t;try{const s=await L.create(t);return this._addToStorage(e,s),s}catch{return this._allItems.set(e,t),this._nonProcessableFiles.add(e),t}}}if(z(t))try{const s=await L.create(t);return this._addToStorage(e,s),s}catch{return this._allItems.set(e,t),this._nonProcessableFiles.add(e),t}if(Array.isArray(t)){const s=new E({downloadFiles:this.downloadFiles,readSystemFiles:this.readSystemFiles,fileName:e});return await s.fromAny(t),this._addToStorage(e,s),s}if(t&&typeof t=="object"&&t.constructor===Object){const s=new I({files:t,downloadFiles:this.downloadFiles,readSystemFiles:this.readSystemFiles,fileName:e});return await s.update(t),this._addToStorage(e,s),s}try{const s=await L.create(t);return this._addToStorage(e,s),s}catch{return this._allItems.set(e,t),this._nonProcessableFiles.add(e),t}}async fromAny(e){return await this.update(e),this}getLeafFiles(){const e=[],t=[];return Array.from(this._mediaFiles).filter(s=>!this._mediaContainers.has(s)).forEach((s,i)=>{const r=this._allItems.get(s);r instanceof p&&(e.push(r),t.push(i))}),{files:e,indices:t}}getMediaContainers(){const e={};for(const t of this._mediaContainers)e[t]=this._allItems.get(t);return this._shallowCopyWithSettings(e)}getProcessableFiles(e={}){const{ignoreErrors:t=!1,raiseException:s=!0,silent:i=!1}=e;if(t)return this;const r={};for(const n of this._mediaFiles)this._mediaContainers.has(n)||(r[n]=this._allItems.get(n));for(const n of this._mediaContainers){const a=this._allItems.get(n).getProcessableFiles({raiseException:!1,silent:!0});a.length>0&&(r[n]=a)}if(this._urlFiles.size+this._nonProcessableFiles.size>0&&(s||!i)){const n=[...this._urlFiles,...this._nonProcessableFiles],a=`Files not processed: ${JSON.stringify(n)}. Check configuration (downloadFiles=${this.downloadFiles}, readSystemFiles=${this.readSystemFiles})`;if(s)throw new Error(a);i||console.warn(a)}return this._shallowCopyWithSettings(r)}getUrlFiles(){const e={};return this._urlFiles.forEach(t=>{e[t]=this._allItems.get(t)}),e}getFilePathFiles(){const e={};return this._nonProcessableFiles.forEach(t=>{e[t]=this._allItems.get(t)}),e}getNonFileParams(e=!0){const t=new Set(this._nonProcessableFiles);e&&this._urlFiles.forEach(i=>t.add(i));const s={};for(const i of t)s[i]=this._allItems.get(i);for(const i of this._mediaContainers){const r=this._allItems.get(i).getNonFileParams(e);r.length>0&&(s[i]=r)}return s}_shallowCopyWithSettings(e){const t=new I({fileName:this.fileName,downloadFiles:this.downloadFiles,readSystemFiles:this.readSystemFiles});if(!e)return t;const s=new Set(Object.keys(e));for(const[i,r]of Object.entries(e))t._allItems.set(i,r);return t._mediaFiles=new Set([...this._mediaFiles].filter(i=>s.has(i))),t._urlFiles=new Set([...this._urlFiles].filter(i=>s.has(i))),t._nonProcessableFiles=new Set([...this._nonProcessableFiles].filter(i=>s.has(i))),t._mediaContainers=new Set([...this._mediaContainers].filter(i=>s.has(i))),t}toBase64(e=!0){const t={};for(const s of this._mediaFiles){const i=this._allItems.get(s);i instanceof p&&(t[s]=i.toBase64(e))}return t}toBlob(){const e={};for(const t of this._mediaFiles){const s=this._allItems.get(t);s instanceof p&&(e[t]=s.toBlob())}return e}toArrayBuffer(){const e={};for(const t of this._mediaFiles){const s=this._allItems.get(t);s instanceof p&&(e[t]=s.toArrayBuffer())}return e}toUint8Array(){const e={};for(const t of this._mediaFiles){const s=this._allItems.get(t);s instanceof p&&(e[t]=s.toUint8Array())}return e}toBuffer(){const e={};for(const t of this._mediaFiles){const s=this._allItems.get(t);s instanceof p&&(e[t]=s.toBuffer())}return e}toJson(){const e={};for(const[t,s]of this._allItems)this._mediaFiles.has(t)&&s&&typeof s=="object"&&"toJson"in s?e[t]=s.toJson():e[t]=s;return e}fileSize(e="bytes"){let t=0;for(const s of this._mediaFiles){const i=this._allItems.get(s);i&&typeof i=="object"&&"fileSize"in i&&(t+=i.fileSize(e))}return t}async save(e,t=!0){if(e||(e=v?process.cwd():"."),!v){for(const[h,u]of this._allItems)this._mediaFiles.has(h)&&u&&typeof u=="object"&&"save"in u&&await u.save(h);return}const s=await import("path"),i=await import("fs/promises"),r=s.extname(e),n=r!=="",a=n?s.basename(e,r):"",c=n?s.dirname(e):e;await i.mkdir(c,{recursive:!0});let f=0;for(const h of this._mediaFiles){const u=this._allItems.get(h);if(!u)continue;if(this._mediaContainers.has(h)){if(t){const j=s.join(c,n?a:h);await i.mkdir(j,{recursive:!0}),await u.save(j)}else await u.save(c);continue}let d,b;n?(d=a,b=r.substring(1)):(d=h,b=u.extension||"bin");let y=s.join(c,`${d}.${b}`),P=f;for(;;)try{await i.access(y),y=s.join(c,`${d}_${P}.${b}`),P++}catch{break}await u.save(y),f++}}get(e){return this._allItems.get(e)}async set(e,t){await this._processFile(e,t)}delete(e){return this._removeFromAllSets(e),this._allItems.delete(e)}has(e){return this._allItems.has(e)}keys(){return Array.from(this._allItems.keys())}values(){return Array.from(this._allItems.values())}entries(){return Array.from(this._allItems.entries())}async update(e){if(!e)return;const t=e instanceof I?e.entries():Object.entries(e);for(const[s,i]of t)await this._processFile(s,i)}clear(){this._allItems.clear(),this._mediaFiles.clear(),this._urlFiles.clear(),this._nonProcessableFiles.clear(),this._mediaContainers.clear()}get length(){return this._allItems.size}isEmpty(){return this._allItems.size===0}getInfo(){return{fileName:this.fileName,totalFiles:this._allItems.size,mediaFiles:this._mediaFiles.size,urlFiles:this._urlFiles.size,nonProcessableFiles:this._nonProcessableFiles.size,containers:this._mediaContainers.size,totalSize:this.fileSize("bytes")}}getFileName(){return this.fileName}setFileName(e){this.fileName=e}getContentType(){return"application/x-media-dict"}setContentType(e){throw new Error("Cannot set content type on MediaDict")}toDict(){const e={};for(const[t,s]of this._allItems)s instanceof I?e[t]=s.toDict():e[t]=s;return e}[Symbol.iterator](){return this._allItems.keys()}}const U={};U.default=p,U.image=O,U.audio=B,U.video=R,U.media=p,typeof window<"u"&&(window.MediaFile=p,window.ImageFile=O,window.AudioFile=B,window.VideoFile=R,window.MediaList=E,window.MediaDict=I),typeof module<"u"&&typeof module.exports<"u"&&(module.exports={MediaFile:p,ImageFile:O,AudioFile:B,VideoFile:R,MediaList:E,MediaDict:I,MediaFileFactory:L});class me{constructor(e){l(this,"uploadEndpoint");l(this,"apiKey");l(this,"defaultTimeout",6e4);this.uploadEndpoint=e.uploadEndpoint||"https://api.socaity.ai/sdk/v1/files",this.apiKey=e.apiKey}setApiKey(e){this.apiKey=e}getAuthHeaders(){return{Authorization:`Bearer ${this.apiKey}`}}async processUploadResponse(e){if(e.status===401)throw new Error("Unauthorized: Invalid API key");if(!e.ok)throw console.error("Failed to get temporary upload URL:",e),new Error(`Failed to get temporary upload URL: ${e.status} ${e.statusText}`);try{const t=await e.text(),s=JSON.parse(t);return Array.isArray(s)?s:[s]}catch(t){throw console.error("Error parsing response:",t),new Error("Failed to parse response body as JSON")}}async uploadToTemporaryUrl(e,t){const s={"x-ms-blob-type":"BlockBlob","x-ms-if-none-match":"*"},i=t instanceof p?await t.toArrayBuffer():t,r=await fetch(e,{method:"PUT",headers:s,body:i});if(r.status!==201)throw new Error(`Failed to upload to temporary URL ${e}. Response: ${r.statusText}`)}async upload(e){const s=e.getProcessableFiles({raiseException:!1,silent:!0}).toList().filter(h=>h instanceof p);if(s.length===0)throw new Error("MediaList contains no processable files");const i=s.map(h=>h.extension).filter(h=>h!==null),r={"Content-Type":"application/json",...this.getAuthHeaders()},n=await fetch(this.uploadEndpoint,{method:"POST",headers:r,body:JSON.stringify({n_files:s.length,file_extensions:i.length>0?i:void 0}),signal:AbortSignal.timeout(this.defaultTimeout)}),a=await this.processUploadResponse(n),c=a.map((h,u)=>this.uploadToTemporaryUrl(h,s[u]));return await Promise.all(c),a.map(h=>h.split("?")[0])}async download(e,t){const s=await new p(e).fromUrl(e,this.getAuthHeaders());return t?(await s.save(t),t):s}}class se{constructor(){l(this,"config");l(this,"uploadFileThresholdMB",5);l(this,"maxFileUploadLimitMB",1e3);l(this,"fastCloud");l(this,"abortController");l(this,"responseParser");this.config=A.getInstance(),this.abortController=new AbortController,this.responseParser=new re,this.fastCloud=new me({uploadEndpoint:`${this.config.baseUrl}/sdk/files`,apiKey:this.config.apiKey?this.config.apiKey:""})}isFileTypeParam(e){const t=["file","image","audio","video"];if(e.definition&&!Array.isArray(e.definition)){const s=e.definition;return!!(s.format&&t.includes(s.format))}return Array.isArray(e.definition)?e.definition.some(s=>!!(s.format&&t.includes(s.format))):!1}async formatRequestParams(e,t){const s={queryParams:{},bodyParams:{},fileParams:{},headers:{},url:""};if(!e.parameters||e.parameters.length===0)return s.url=this.buildRequestUrl(e.path,s.queryParams),s;const i={},r={};for(const n of e.parameters){const a=t[n.name]??n.default;if(a===void 0&&n.required)throw new Error(`Required parameter '${n.name}' is missing`);a!==void 0&&(r[n.name]=n.location==="query"?"query":"body",this.isFileTypeParam(n)?i[n.name]=a:n.location==="query"?s.queryParams[n.name]=a:s.bodyParams[n.name]=a)}if(Object.keys(i).length>0){const{fileParams:n,nonFileParams:a}=await this.processFileParams(i);s.fileParams=n;for(const[c,f]of Object.entries(a))(r[c]||"body")==="query"?s.queryParams[c]=f:s.bodyParams[c]=f}return s.bodyParams.is_public=t.is_public?t.is_public:!0,s.bodyParams.keep=t.keep?t.keep:!0,s.url=this.buildRequestUrl(e.path,s.queryParams),s}async loadFiles(e){const t=new I({downloadFiles:!1,readSystemFiles:!0,fileName:"fileParams"});return await t.fromAny(e),t}async uploadFiles(e){const t={};for(const s of e.keys()){const i=e.get(s);if(i instanceof I){const a=i.getProcessableFiles({ignoreErrors:!0,silent:!0});a.length>0&&(t[s]=await this.uploadFiles(a));continue}if(i instanceof E){const a=i.getProcessableFiles({ignoreErrors:!0,silent:!0});if(a.length>0){const c=await this.fastCloud.upload(a);t[s]=a.length===1?c[0]:c}continue}const r=new E({files:[i]}),n=await this.fastCloud.upload(r);t[s]=n[0]}return t}prepareFilesForSend(e){const t={};for(const s of e.keys()){const i=e.get(s);if(i instanceof I){const a=i.getProcessableFiles({ignoreErrors:!0,silent:!0});a.length>0&&(t[s]=this.prepareFilesForSend(a));continue}if(i instanceof E){const a=i.getProcessableFiles({ignoreErrors:!0,silent:!0});if(a.length>0){const c=a.toBlob();t[s]=a.length===1?c[0]:c}continue}const n=new E({files:[i]}).toBlob();t[s]=n[0]}return t}async processFileParams(e){const t=await this.loadFiles(e),s=t.getNonFileParams(!1),i=t.getProcessableFiles({ignoreErrors:!0,silent:!0}),r=t.getUrlFiles();if(i.length>0){const n=i.fileSize("mb");if(n>this.maxFileUploadLimitMB)throw new Error(`Total file size exceeds maximum limit of ${this.maxFileUploadLimitMB}MB`);const a=n>this.uploadFileThresholdMB?await this.uploadFiles(i):this.prepareFilesForSend(i);for(const c of i.keys())c in a||(s[c]=e[c]);Object.assign(r,a)}return{fileParams:r,nonFileParams:s}}buildRequestUrl(e,t){let s=`${this.config.baseUrl}/${e}`;const i=this.buildQueryString(t);return i?`${s}?${i}`:s}matchParams(e,t){const s={};for(const[i,r]of Object.entries(e))i in t?s[i]=t[i]:r!==void 0&&(s[i]=r);return s}validateAPIKey(e){const t=e||this.config.apiKey;if(!t)throw new Error("API key not provided");return this.fastCloud.setApiKey(t),t}buildQueryString(e){if(!e||Object.keys(e).length===0)return"";const t=new URLSearchParams;for(const[i,r]of Object.entries(e))if(r!=null)if(r instanceof E){const n=r.toBase64(!0);t.append(i,n.length===1?n[0]:JSON.stringify(n))}else typeof r=="object"?t.append(i,JSON.stringify(r)):t.append(i,String(r));const s=t.toString();return s?`?${s}`:""}async formatErrorResponse(e){const t=e.status;let s;try{const i=e.headers.get("content-type");if(i&&i.includes("application/json")){const r=await e.json();s=JSON.stringify(r)}else s=await e.text()}catch(i){console.log("error",i),s="Could not parse error response"}return console.log("errorText",s),new Error(`API error (${t}): ${s}`)}async sendRequest(e,t="POST",s={},i={},r={},n){const a=this.validateAPIKey(n);this.abortController=new AbortController;const{signal:c}=this.abortController,f={Authorization:`Bearer ${a}`};let h=`${this.config.baseUrl}/${e}`,u=null;if(t==="GET"){const d={...s,...i,...r};h+=this.buildQueryString(d)}else{h+=this.buildQueryString(s);const d=new FormData,b={...i,...r};for(const[y,P]of Object.entries(b))P!=null&&(P instanceof Blob||P instanceof File?d.append(y,P):Array.isArray(P)?P.forEach((j,Fe)=>{j instanceof Blob||j instanceof File?d.append(y,j):typeof j=="object"?d.append(y,new Blob([JSON.stringify(j)],{type:"application/json"})):d.append(y,String(j))}):typeof P=="object"?d.append(y,new Blob([JSON.stringify(P)],{type:"application/json"})):d.append(y,String(P)));u=d}try{const d=setTimeout(()=>this.abort(),3e4),b=await fetch(h,{method:t,headers:f,body:u,signal:c});if(clearTimeout(d),!b.ok)throw await this.formatErrorResponse(b);const y=b.headers.get("content-type");return y!=null&&y.includes("application/json")?await b.json():await b.text()}catch(d){throw d instanceof DOMException&&d.name==="AbortError"?new Error("Request canceled"):d instanceof Error?d:new Error(`Network error: ${String(d)}`)}}async request_endpoint(e,t,s){const i=await this.formatRequestParams(e,t),r=await this.sendRequest(e.path,e.method,i.queryParams,i.bodyParams,i.fileParams,s);return this.responseParser.parse(r)}async refresh_status(e,t){let s;if(t){console.log("refresh_url",t);const i=await this.requestUrl(t,"POST");if(!i.ok)throw await this.formatErrorResponse(i);const r=i.headers.get("content-type");r!=null&&r.includes("application/json")?s=await i.json():s=await i.text()}else s=await this.sendRequest("status","POST",{job_id:e});return this.responseParser.parse(s)}async requestUrl(e,t="GET",s,i=60,r,n){const a=this.validateAPIKey(r);!e.startsWith("http://")&&!e.startsWith("https://")&&(e=`${this.config.baseUrl}/${e.replace(/^\//,"")}`),console.log("Request URL:",e,n);const c={Authorization:`Bearer ${a}`};this.abortController=new AbortController;const{signal:f}=this.abortController,h=setTimeout(()=>{this.abort()},i*1e3);try{const u=t.toUpperCase();let d={method:u,headers:c,signal:f};if(u==="GET"){if(n){const y=this.buildQueryString(n);e+=y?`?${y}`:""}}else if(s){const y=new FormData;Object.entries(s).forEach(([P,j])=>{j!=null&&y.append(P,j)}),d.body=y}else n&&(c["Content-Type"]="application/json",d.body=JSON.stringify(n));const b=await fetch(e,d);return clearTimeout(h),b}catch(u){throw clearTimeout(h),u instanceof DOMException&&u.name==="AbortError"?new Error("Request canceled"):u instanceof Error?u:new Error(`Network error: ${String(u)}`)}}abort(){this.abortController.abort(),this.abortController=new AbortController}}const D=class D{constructor(e){l(this,"requestHandler");l(this,"config");l(this,"jobs");l(this,"mediaHandler");this.requestHandler=e,this.config=A.getInstance(),this.jobs=new Map,this.mediaHandler=new p}static getInstance(e){return D.instance||(e||(e=new se),D.instance=new D(e)),D.instance}async submitJob(e,t,s){try{const i=await this.requestHandler.request_endpoint(e,t,s);return this.jobs.set(i.id,i),i}catch(i){throw i instanceof Error?i:new Error(`Failed to submit job: ${String(i)}`)}}getAllJobs(){return Array.from(this.jobs.values())}getJob(e){return this.jobs.get(e)}async cancelJob(e){try{return await this.requestHandler.sendRequest("cancel","GET",{job_id:e}),this.jobs.delete(e),!0}catch{return!1}}clearCompletedJobs(){for(const[e,t]of this.jobs.entries())(t.status===g.COMPLETED||t.status===g.FAILED)&&this.jobs.delete(e)}};l(D,"instance");let K=D;const q=typeof process<"u"&&process.stdout&&process.stdout.clearLine;let x;if(q)try{x=require("cli-progress")}catch{console.warn("cli-progress package not found. Using basic console output for progress.")}const k=class k{constructor(){l(this,"multiBar");l(this,"bars",new Map);l(this,"isInitialized",!1);q&&x&&(this.multiBar=new x.MultiBar({clearOnComplete:!1,hideCursor:!0,format:"{bar} {percentage}% | {jobId} | {phase} | {message}"}),this.isInitialized=!0)}static getInstance(){return k.instance||(k.instance=new k),k.instance}createBar(e,t){if(!this.isInitialized)return null;const s=this.multiBar.create(100,0,{jobId:e,phase:t,message:"Starting..."});return this.bars.set(e,s),s}updateBar(e,t,s){const i=this.bars.get(e);i&&i.update(t,s)}removeBar(e){const t=this.bars.get(e);t&&(t.stop(),this.multiBar.remove(t),this.bars.delete(e))}stopAll(){this.isInitialized&&(this.multiBar.stop(),this.bars.clear())}};l(k,"instance");let Z=k;class ie{constructor(e,t,s,i,r=!0){l(this,"apiJob");l(this,"endpoint");l(this,"processingState");l(this,"jobManager");l(this,"result",null);l(this,"error",null);l(this,"completed",!1);l(this,"resolvePromise");l(this,"rejectPromise");l(this,"promise");l(this,"eventListeners",new Map);l(this,"verbose");l(this,"progressBar",null);l(this,"progressBarManager");l(this,"parseResultCallbacks",[]);l(this,"_pollErrorCount",0);l(this,"_lastLoggedMessage",null);this.apiJob=e,this.jobManager=t,this.endpoint=s,this.verbose=r,this.processingState={phase:w.INITIALIZING,progress:0},this.progressBarManager=Z.getInstance(),this.eventListeners=new Map,this.promise=new Promise((n,a)=>{this.resolvePromise=n,this.rejectPromise=a}),i&&this.onParseResult(i),this.verbose&&this.initProgressDisplay(),setTimeout(()=>this.startTracking(),0)}initProgressDisplay(){this.verbose&&(q&&x?(this.progressBar=this.progressBarManager.createBar(this.apiJob.id||"initializing",this.processingState.phase),this.updateProgressDisplay()):this.logProgress())}updateProgressDisplay(){if(!this.verbose)return;const e=this.processingState.phase,t=this.calculateProgressPercent(),s=this.formatProgressMessage();q&&x&&this.progressBar?this.progressBarManager.updateBar(this.apiJob.id,t,{phase:e,message:s.replace(/^.*\| /,"")}):this.logProgress()}calculateProgres