@bereasoftware/nexa 1.1.0 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +179 -335
- package/README.md +177 -22
- package/dist/bereasoftware-nexa-1.3.0.tgz +0 -0
- package/dist/nexa.cjs.js +462 -1
- package/dist/nexa.cjs.js.map +1 -1
- package/dist/nexa.es.js +1103 -890
- package/dist/nexa.es.js.map +1 -1
- package/dist/nexa.iife.js +462 -1
- package/dist/nexa.iife.js.map +1 -1
- package/dist/nexa.umd.js +462 -1
- package/dist/nexa.umd.js.map +1 -1
- package/dist/types/dev-overlay/index.d.ts +15 -0
- package/dist/types/dev-overlay/overlay.d.ts +26 -0
- package/dist/types/dev-overlay/tracker.d.ts +16 -0
- package/dist/types/dev-overlay/types.d.ts +33 -0
- package/dist/types/http-client/http-client.d.ts +51 -23
- package/dist/types/http-client/index.d.ts +2 -2
- package/dist/types/http-client/node-http-adapter.d.ts +7 -2
- package/dist/types/index.d.ts +6 -3
- package/dist/types/realtime/plugin.d.ts +5 -1
- package/dist/types/realtime/sse-client.d.ts +4 -1
- package/dist/types/realtime/websocket-client.d.ts +4 -1
- package/dist/types/types/index.d.ts +50 -44
- package/dist/types/utils/index.d.ts +7 -71
- package/package.json +32 -23
- package/dist/bereasoftware-nexa-1.1.0.tgz +0 -0
- package/dist/types/testing/index.d.ts +0 -5
- package/dist/types/testing/mock-client.d.ts +0 -152
package/dist/nexa.cjs.js
CHANGED
|
@@ -1,2 +1,463 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.defineProperty,t=(e,t)=>()=>(e&&(t=e(e=0)),t),n=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r},r=e=>({ok:!0,value:e}),i=e=>({ok:!1,error:e});function a(e){return{validate(t){let n=t;for(let[t,r]of Object.entries(e))if(!r(n[t]))return i({message:`Validation failed: field "${t}" is invalid`,code:`VALIDATION_ERROR`});return r(t)}}}function o(e){return{validate(t){let n=t,a=e.filter(e=>!(e in n));return a.length>0?i({message:`Validation failed: missing fields: ${a.join(`, `)}`,code:`VALIDATION_ERROR`}):r(t)}}}var s={validate(e){return Array.isArray(e)?r(e):i({message:`Expected array response`,code:`VALIDATION_ERROR`})}},c={validate(e){return e&&typeof e==`object`&&!Array.isArray(e)?r(e):i({message:`Expected object response`,code:`VALIDATION_ERROR`})}},l={transform(e){return v(e,_)}},u={transform(e){return v(e,ee)}},d={transform(e){return y(e)}};function f(e){return{transform(t){return Array.isArray(t)?t.map(t=>b(t,e)):b(t,e)}}}function p(e){return{transform(t){return{[e]:t}}}}var m=class{maxAttempts;constructor(e=5){this.maxAttempts=e}shouldRetry(e){return e<this.maxAttempts}delayMs(e){return e*50}},h=class{retryableStatuses=[408,429,500,502,503,504];maxAttempts;constructor(e=3){this.maxAttempts=e}shouldRetry(e,t){return e>=this.maxAttempts?!1:this.retryableStatuses.includes(t.status??0)||t.code===`TIMEOUT`}delayMs(e){return Math.min(1e3*2**(e-1),1e4)}},g=class{failureCount=0;lastFailureTime=0;maxAttempts;failureThreshold;resetTimeMs;constructor(e=3,t=5,n=6e4){this.maxAttempts=e,this.failureThreshold=t,this.resetTimeMs=n}shouldRetry(e){return e>=this.maxAttempts||(Date.now()-this.lastFailureTime>this.resetTimeMs&&(this.failureCount=0),this.failureCount>=this.failureThreshold)?!1:(this.failureCount++,this.lastFailureTime=Date.now(),!0)}delayMs(e){return 100*2**(e-1)}reset(){this.failureCount=0,this.lastFailureTime=0}};function _(e){return e.replace(/_([a-z])/g,(e,t)=>t.toUpperCase())}function ee(e){return e.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function v(e,t){if(!e||typeof e!=`object`)return e;if(Array.isArray(e))return e.map(e=>v(e,t));let n={};for(let[r,i]of Object.entries(e))n[t(r)]=v(i,t);return n}function y(e,t=``){let n={};if(Array.isArray(e))e.forEach((e,r)=>{let i=t?`${t}[${r}]`:`[${r}]`;Object.assign(n,y(e,i))});else if(e&&typeof e==`object`)for(let[r,i]of Object.entries(e)){let e=t?`${t}.${r}`:r;i&&typeof i==`object`&&!Array.isArray(i)?Object.assign(n,y(i,e)):n[e]=i}return n}function b(e,t){if(!e||typeof e!=`object`)return{};let n=e,r={};for(let e of t)e in n&&(r[e]=n[e]);return r}function te(e){let t=new AbortController,n=setTimeout(()=>t.abort(),e);return t.signal.addEventListener(`abort`,()=>clearTimeout(n),{once:!0}),t}async function x(e,t=3){try{return await e()}catch(n){if(t<=0)throw n;return x(e,t-1)}}var S=class{cache=new Map;get(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp>t.ttlMs?(this.cache.delete(e),null):t.data:null}set(e,t,n=6e4){this.cache.set(e,{data:t,timestamp:Date.now(),ttlMs:n})}clear(){this.cache.clear()}has(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp>t.ttlMs?(this.cache.delete(e),!1):!0:!1}delete(e){this.cache.delete(e)}};function C(e={}){let t=e.cache||new S,n=e.ttlMs||6e4,r=e.cacheableStatuses||[200,304];return async(e,i)=>{let a=(e.request.method||`GET`).toUpperCase(),o=a===`GET`,s=`${a}:${e.request.url}`;if(o&&t.has(s)){let n=t.get(s);if(n){e.response=n,e.state.cacheHit=!0;return}}await i(),o&&e.response&&r.includes(e.response.status)&&(t.set(s,e.response,n),e.state.cacheMiss=!0)}}var ne=C(),w=class{pending=new Map;async execute(e,t){if(this.pending.has(e))return this.pending.get(e);let n=t().finally(()=>{this.pending.delete(e)});return this.pending.set(e,n),n}clear(){this.pending.clear()}};function T(e={}){let t=e.deduplicator||new w,n=e.includeBody??!1,r=e.methods||[`GET`];return async(e,i)=>{let a=(e.request.method||`GET`).toUpperCase();if(!r.includes(a)){await i();return}let o=`${a}:${e.request.url}`;n&&e.request.body&&(o+=`:${JSON.stringify(e.request.body)}`);try{e.response=await t.execute(o,async()=>(await i(),e.response)),e.state.deduped=!0}catch(t){throw e.error=t,t}}}var re=T();function E(e={maxRequests:100,windowMs:6e4}){let t=e.windowMs??6e4,n=e.maxRequests,r=e.keyGenerator??(e=>`${e.request.method}:${e.request.url}`),i=new Map;return async(a,o)=>{let s=r(a),c=Date.now();if(i.size>1e3)for(let[e,t]of i.entries())c>t.resetTime&&i.delete(e);let l=i.get(s);if((!l||c>l.resetTime)&&(l={count:0,resetTime:c+t},i.set(s,l)),l.count>=n){a.response={status:e.errorResponse?.status??429,headers:{"Content-Type":`application/json`},body:e.errorResponse?.body??{error:`Too Many Requests`,message:`Rate limit exceeded`}},a.state.rateLimited=!0;return}l.count++,a.state.rateLimit={limit:n,remaining:n-l.count,reset:l.resetTime},await o()}}var ie=E();function D(e={}){let t=e.failureThreshold??5,n=e.resetTimeout??3e4,r=e.isFailure??(e=>e.response.status>=500),i=e.keyGenerator??(e=>`${e.request.method}:${e.request.url}`),a=new Map;return async(e,o)=>{let s=i(e),c=a.get(s);if(c||(c={state:`closed`,failures:0,lastFailure:0,successCount:0},a.set(s,c)),c.state===`open`)if(Date.now()-c.lastFailure>n)c.state=`half-open`,c.successCount=0;else{e.response={status:503,headers:{"Content-Type":`application/json`},body:{error:`Service Unavailable`,message:`Circuit breaker is open`}},e.state.circuitOpen=!0;return}try{await o(),r(e)?(c.failures++,c.lastFailure=Date.now(),(c.failures>=t||c.state===`half-open`)&&(c.state=`open`)):(c.failures=0,c.state===`half-open`&&(c.successCount++,c.successCount>=3&&(c.state=`closed`,c.successCount=0)))}catch(e){throw c.failures++,c.lastFailure=Date.now(),(c.failures>=t||c.state===`half-open`)&&(c.state=`open`),e}}}var ae=D();function O(e){return async t=>{let n=-1;async function r(i){if(i<=n)throw Error(`next() called multiple times`);n=i;let a=e[i];a&&await a(t,()=>r(i+1))}await r(0)}}var oe=class{middlewares=[];use(e){return this.middlewares.push(e),this}async execute(e){if(e&&typeof e==`object`&&`request`in e&&`response`in e){let t=e;return await O(this.middlewares.map(e=>typeof e==`function`&&e.length===2?e:async(t,n)=>{let r=e;t.response.body=await r(t.response.body),await n()}))(t),t.response.body}let t=e;for(let e of this.middlewares)t=await e(t);return t}clear(){this.middlewares=[]}};function se(e,t,n,r={}){return{ok:e>=200&&e<300,data:t,error:n,status:e,headers:r}}function k(e){return async(t,n)=>{let r=e.path,i;switch(e.method){case`GET`:i=await t.get(r);break;case`POST`:i=await t.post(r,n);break;case`PUT`:i=await t.put(r,n);break;case`PATCH`:i=await t.patch(r,n);break;case`DELETE`:i=await t.delete(r);break;default:throw Error(`Unsupported method: ${e.method}`)}return i}}function ce(e){return{request:async(t,n,r)=>{let i=e[n];return await k(i)(t,r)}}}var le=class e{subscribers=[];errorSubscribers=[];completeSubscribers=[];subscribe(e,t,n){return e&&this.subscribers.push(e),t&&this.errorSubscribers.push(t),n&&this.completeSubscribers.push(n),{unsubscribe:()=>{this.subscribers=this.subscribers.filter(t=>t!==e),this.errorSubscribers=this.errorSubscribers.filter(e=>e!==t),this.completeSubscribers=this.completeSubscribers.filter(e=>e!==n)}}}next(e){this.subscribers.forEach(t=>t(e))}error(e){this.errorSubscribers.forEach(t=>t(e))}complete(){this.completeSubscribers.forEach(e=>e())}map(t){let n=new e;return this.subscribe(e=>n.next(t(e)),e=>n.error(e),()=>n.complete()),n}filter(t){let n=new e;return this.subscribe(e=>{t(e)&&n.next(e)},e=>n.error(e),()=>n.complete()),n}};function ue(e){return t=>{if(!e(t))throw TypeError(`Value does not match expected type`);return t}}function A(e){return e}function de(e){return A(e)}var fe=class{_promise;resolveFunc;rejectFunc;constructor(){this._promise=new Promise((e,t)=>{this.resolveFunc=e,this.rejectFunc=t})}resolve(e){this.resolveFunc(e)}reject(e){this.rejectFunc(e)}get promise(){return this._promise}promise_(){return this._promise}};async function j(e,t={}){let n=e.body?.getReader();if(!n)throw Error(`Response body is not readable`);let r=[],i=0,a=parseInt(e.headers.get(`content-length`)||`0`,10);for(;;){let{done:e,value:o}=await n.read();if(e)break;r.push(o),i+=o.length,t.onChunk&&await t.onChunk(o),t.onProgress&&a>0&&t.onProgress(i,a)}return M(r,i)}function M(e,t){let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.byteLength;return n}async function pe(e,t){let n=await j(e);if(typeof window>`u`)await(await import(`fs`).then(e=>e.promises)).writeFile(t,n);else{let e=new Blob([n.buffer],{type:`application/octet-stream`}),r=URL.createObjectURL(e),i=document.createElement(`a`);i.href=r,i.download=t,i.click(),URL.revokeObjectURL(r)}}function N(e={}){return async(t,n)=>{if(await n(),t.response&&t.response.body&&typeof t.response.body==`object`&&`getReader`in t.response.body){let n=t.response.body.getReader(),r=[],i=0,a=parseInt(t.response.headers?.[`content-length`]||`0`,10);try{for(;;){let{done:o,value:s}=await n.read();if(o)break;r.push(s),i+=s.length,e.onChunk&&await e.onChunk(s),e.onProgress&&a>0&&e.onProgress(i,a),t.state.streamedChunks=t.state.streamedChunks||[],t.state.streamedChunks.push(s)}let o=M(r,i);t.response.body=o,t.state.streaming=!0,t.state.streamedBytes=i}finally{n.releaseLock()}}}}var me=N({onProgress:(e,t)=>{if(t>0){let n=Math.round(e/t*100);console.log(`⬇️ Streaming: ${n}% (${e}/${t} bytes)`)}}}),P=class{plugins=[];cache=new S;deduplicator=new w;middlewares=[];listeners=new Map;register(e){return this.plugins.push(e),e.setup(this),this.emit(`plugin:registered`,e.name),this}addMiddleware(e){return this.middlewares.push(e),this}getCache(){return this.cache}getDeduplicator(){return this.deduplicator}getPipeline(){return O(this.middlewares)}async executePipeline(e){await this.getPipeline()(e)}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e)?.add(t),this}emit(e,...t){let n=this.listeners.get(e);if(n)for(let e of n)e(...t)}off(e,t){return this.listeners.get(e)?.delete(t),this}getPlugins(){return[...this.plugins]}clear(){this.plugins=[],this.middlewares=[],this.listeners.clear(),this.cache.clear(),this.deduplicator.clear()}},he={name:`logger`,setup(e){e.on(`request:start`,(...e)=>{let t=e[0];console.log(`📤 Request started: ${t}`)}),e.on(`request:success`,(...e)=>{let t=e[0],n=e[1];console.log(`✅ Request succeeded: ${t} (${n})`)}),e.on(`request:error`,(...e)=>{let t=e[0],n=e[1];console.error(`❌ Request failed: ${t}`,n)})}},ge=class{name=`metrics`;metrics={requests:0,errors:0,totalTime:0,avgTime:0};setup(e){e.on(`request:complete`,(...e)=>{let t=e[0],n=e[1];this.metrics.requests++,this.metrics.totalTime+=t,this.metrics.avgTime=this.metrics.totalTime/this.metrics.requests,n||this.metrics.errors++})}getMetrics(){return{...this.metrics}}},_e=class{name=`cache`;ttlMs;constructor(e=6e4){this.ttlMs=e}setup(e){e.addMiddleware(C({ttlMs:this.ttlMs}))}},ve=class{name=`dedupe`;setup(e){e.addMiddleware(T())}},ye=class{name=`rate-limit`;options;constructor(e={}){this.options=e}setup(e){e.addMiddleware(E({maxRequests:this.options.maxRequests??100,windowMs:this.options.windowMs??6e4,keyGenerator:this.options.keyGenerator,errorResponse:this.options.errorResponse}))}},be=class{name=`circuit-breaker`;options;constructor(e={}){this.options=e}setup(e){e.addMiddleware(D({failureThreshold:this.options.failureThreshold??5,resetTimeout:this.options.resetTimeout??3e4,isFailure:this.options.isFailure,keyGenerator:this.options.keyGenerator}))}},F=n({Http2SessionPool:()=>B,closeHttp2SessionPool:()=>De,getHttp2SessionPoolStats:()=>Oe,nodeHttp2Adapter:()=>Ee,nodeHttpAdapter:()=>Te});async function xe(){return L||(L=await import(`http`),R=await import(`https`)),{http:L,https:R}}async function Se(){return z||=await import(`http2`),z}function I(e,t){let n,r,i,a,o;if(typeof e==`string`)n=e,r=t?.method||`GET`,i=t?.headers||{},a=t?.body,o=t?.signal===null?void 0:t?.signal;else{n=e.url,r=t?.method||e.method||`GET`;let s=new Headers(e.headers),c=new Headers(t?.headers),l=new Headers(s);c.forEach((e,t)=>l.set(t,e)),i=Object.fromEntries(l.entries()),a=t?.body??e.body??void 0,o=t?.signal===null?e.signal:t?.signal}return{url:n,method:r,headers:i,body:a,signal:o}}function Ce(e,t,n,r,i=!1){if(i)return null;let a=e.startsWith(`https:`)?n.Agent:t.Agent,o={keepAlive:r?.keepAlive??!0,maxSockets:r?.maxSockets??50,maxFreeSockets:r?.maxFreeSockets??10,timeout:r?.timeout??6e4};return r?.maxRequestsPerSocket!==void 0&&(o.maxRequestsPerSocket=r.maxRequestsPerSocket),new a(o)}async function we(e){let t=new Headers;for(let[n,r]of Object.entries(e.headers))Array.isArray(r)?r.forEach(e=>t.append(n,e)):r!==void 0&&t.set(n,String(r));let n=[];return e.on(`data`,e=>n.push(e)),new Promise(r=>{e.on(`end`,()=>{let i=Buffer.concat(n);r(new Response(i,{status:e.statusCode||200,statusText:e.statusMessage||`OK`,headers:t}))})})}async function Te(e,t,n){let{http:r,https:i}=await xe(),{url:a,method:o,headers:s,body:c,signal:l}=I(e,t),u=new URL(a),d=u.protocol===`https:`,f=d?i:r,p=Ce(a,r,i,n,!1);return new Promise((e,t)=>{let r=f.request({hostname:u.hostname,port:u.port||(d?443:80),path:u.pathname+u.search,method:o,headers:s,agent:p});if(l){if(l.aborted){r.destroy(),t(Error(`Request aborted`));return}let e=()=>{r.destroy(),t(Error(`Request aborted`))};l.addEventListener(`abort`,e);let n=()=>l.removeEventListener(`abort`,e);r.on(`close`,n),r.on(`error`,n)}r.setTimeout(n?.timeout??6e4,()=>{r.destroy(),t(Error(`Request timed out`))}),r.on(`response`,async n=>{try{e(await we(n))}catch(e){t(e)}}),r.on(`error`,t),c&&(typeof c==`string`?r.write(c):c instanceof Uint8Array?r.write(Buffer.from(c)):Buffer.isBuffer(c)?r.write(c):typeof c==`object`&&r.write(JSON.stringify(c))),r.end()})}async function Ee(e,t,n){let{url:r,method:i,headers:a,body:o,signal:s}=I(e,t),c=new URL(r),l=c.origin;return new Promise(async(e,t)=>{let r,u,d=!1,f=()=>{d||(d=!0,V.releaseSession(l))},p=e=>{f(),t(e)},m=t=>{f(),e(t)};try{if(r=await V.getSession(l,n),s?.aborted){p(Error(`Request aborted`));return}if(u=r.request({":path":c.pathname+c.search,":method":i,...a}),n?.timeout&&u.setTimeout(n.timeout,()=>{u.close(),p(Error(`Request timed out`))}),s){let e=()=>{u.close(),p(Error(`Request aborted`))};s.addEventListener(`abort`,e);let t=()=>s.removeEventListener(`abort`,e);u.on(`close`,t),u.on(`error`,t)}let e=[];u.on(`data`,t=>e.push(Buffer.isBuffer(t)?t:Buffer.from(t))),u.on(`response`,t=>{let n=Number(t[`:status`])||200,r=new Headers;for(let[e,n]of Object.entries(t))e.startsWith(`:`)||(Array.isArray(n)?n.forEach(t=>r.append(e,t)):n!==void 0&&r.set(e,String(n)));u.on(`end`,()=>{let t=Buffer.concat(e);m(new Response(t,{status:n,statusText:`OK`,headers:r}))})}),u.on(`error`,e=>{p(e)}),o&&(typeof o==`string`||o instanceof Uint8Array||Buffer.isBuffer(o)?u.write(o):typeof o==`object`&&u.write(JSON.stringify(o))),u.end()}catch(e){p(e instanceof Error?e:Error(String(e)))}})}function De(){V.closeAll()}function Oe(){let e=V.getStats();return{sessionCount:e.sessionCount,origins:e.origins}}var L,R,z,B,V,H=t((()=>{B=class{sessions=new Map;cleanupInterval=null;maxIdleTime=3e4;maxRequestsPerSession=1e3;constructor(){this.startCleanup()}startCleanup(){this.cleanupInterval||=setInterval(()=>this.cleanup(),1e4)}cleanup(){let e=Date.now();for(let t of this.sessions.values())!t.closing&&e-t.lastUsed>this.maxIdleTime&&this.closeSession(t,`idle timeout`),!t.closing&&t.requestCount>=this.maxRequestsPerSession&&this.closeSession(t,`max requests exceeded`)}closeSession(e,t){e.closing=!0,e.session.close(),this.sessions.delete(e.origin)}async getSession(e,t){let n=this.sessions.get(e);if(n&&!n.session.closed&&!n.session.destroyed)return n.lastUsed=Date.now(),n.requestCount++,n.session;let r=(await Se()).connect(e,{settings:t?.http2Settings});return r.on(`error`,t=>{this.sessions.delete(e)}),r.on(`close`,()=>{this.sessions.delete(e)}),n={session:r,lastUsed:Date.now(),requestCount:1,origin:e,closing:!1},this.sessions.set(e,n),r}releaseSession(e){let t=this.sessions.get(e);t&&(t.lastUsed=Date.now())}getStats(){return{sessionCount:this.sessions.size,origins:Array.from(this.sessions.keys()),sessions:Array.from(this.sessions.values()).map(e=>({origin:e.origin,requestCount:e.requestCount,lastUsed:e.lastUsed,closing:e.closing,sessionAlive:!e.session.closed&&!e.session.destroyed}))}}closeAll(){for(let e of this.sessions.values())e.closing||e.session.close();this.sessions.clear(),this.cleanupInterval&&=(clearInterval(this.cleanupInterval),null)}},V=new B}));function ke(){return typeof window>`u`&&typeof process<`u`&&process.versions?.node!==void 0}function Ae(){let e=globalThis;return typeof window>`u`&&e.Deno!==void 0&&e.Deno.version?.deno!==void 0}function je(){let e=globalThis;return e.Bun!==void 0&&e.Bun.version!==void 0}function Me(){let e=globalThis;return e.caches!==void 0&&e.WebSocketPair!==void 0}function Ne(e,t){if(!e||e===`fetch`)return fetch;if(e===`node`||e===`http2`){if(!ke())throw Error(`Transport '${e}' is only available in Node.js environment`);return(n,r)=>e===`http2`?Promise.resolve().then(()=>(H(),F)).then(e=>e.nodeHttp2Adapter(n,r,t)):Promise.resolve().then(()=>(H(),F)).then(e=>e.nodeHttpAdapter(n,r,t))}switch(e){case`deno`:if(!Ae())throw Error(`Transport 'deno' is only available in Deno environment`);return fetch;case`bun`:if(!je())throw Error(`Transport 'bun' is only available in Bun environment`);return fetch;case`cloudflare`:if(!Me())throw Error(`Transport 'cloudflare' is only available in Cloudflare Workers environment`);return fetch;default:return fetch}}var Pe=class{store=new S;get(e){return this.store.get(e)}set(e,t,n=6e4){this.store.set(e,t,n)}has(e){return this.store.has(e)}clear(){this.store.clear()}},Fe=class{maxAttempts;baseDelayMs;constructor(e=3,t=100){this.maxAttempts=e,this.baseDelayMs=t}shouldRetry(e,t){let n=t.status!==void 0&&t.status>=500,r=t.code===`NETWORK_ERROR`;return e<this.maxAttempts&&(n||r||t.code===`TIMEOUT`)}delayMs(e){let t=this.baseDelayMs*2**(e-1),n=Math.random()*t*.1;return Math.min(t+n,3e4)}},Ie=class{maxAttempts;baseDelayMs;condition;constructor(e=3,t=100,n){this.maxAttempts=e,this.baseDelayMs=t,this.condition=n}shouldRetry(e,t){if(e>=this.maxAttempts)return!1;if(this.condition)return this.condition(t,e);let n=t.status!==void 0&&t.status>=500,r=t.code===`NETWORK_ERROR`;return n||r||t.code===`TIMEOUT`}delayMs(e){let t=this.baseDelayMs*2**(e-1),n=Math.random()*t*.1;return Math.min(t+n,3e4)}},Le=class{running=0;queue=[];maxConcurrent;constructor(e){this.maxConcurrent=e}async acquire(){if(this.running<this.maxConcurrent){this.running++;return}return new Promise(e=>{this.queue.push(()=>{this.running++,e()})})}release(){this.running--;let e=this.queue.shift();e&&e()}get pending(){return this.queue.length}get active(){return this.running}};function U(e){return e==null?!1:typeof Blob<`u`&&e instanceof Blob||typeof File<`u`&&e instanceof File?!0:Array.isArray(e)?e.some(e=>U(e)):typeof e==`object`?Object.values(e).some(e=>U(e)):!1}function W(e,t,n){let r=t||new FormData;for(let[t,i]of Object.entries(e)){let e=n?`${n}[${t}]`:t;i!=null&&(typeof Blob<`u`&&i instanceof Blob?r.append(e,i):Array.isArray(i)?i.some(e=>U(e))?i.forEach(t=>{U(t)?r.append(e,t):r.append(e,JSON.stringify(t))}):r.append(e,JSON.stringify(i)):typeof i==`object`&&!(i instanceof Blob)?W(i,r,e):r.append(e,String(i)))}return r}function Re(e,t){return!t||e==null||typeof FormData<`u`&&e instanceof FormData||typeof Blob<`u`&&e instanceof Blob||typeof URLSearchParams<`u`&&e instanceof URLSearchParams||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof ReadableStream<`u`&&e instanceof ReadableStream||typeof e==`string`?e:typeof e==`object`&&U(e)?W(e):e}function ze(e,t=!0){let n=Re(e,t);return n==null?{serialized:void 0,contentType:null}:typeof FormData<`u`&&n instanceof FormData?{serialized:n,contentType:null}:typeof URLSearchParams<`u`&&n instanceof URLSearchParams?{serialized:n,contentType:`application/x-www-form-urlencoded`}:typeof Blob<`u`&&n instanceof Blob?{serialized:n,contentType:n.type||`application/octet-stream`}:n instanceof ArrayBuffer||ArrayBuffer.isView(n)||typeof ReadableStream<`u`&&n instanceof ReadableStream?{serialized:n,contentType:`application/octet-stream`}:typeof n==`string`?{serialized:n,contentType:`text/plain`}:{serialized:JSON.stringify(n),contentType:`application/json`}}function G(e,t){return t?e.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,(e,n)=>{let r=t[n];if(r===void 0)throw Error(`Missing path parameter: :${n}`);return encodeURIComponent(String(r))}):e}function K(e,t){if(e!==void 0)return e;if(t!==void 0)return t?`include`:`same-origin`}function Be(e){return typeof e==`number`?{total:e}:typeof e==`object`&&e?{connection:e.connection,response:e.response,total:e.total}:{}}var q=class e{requestInterceptors=[];responseInterceptors=[];cache;config;requestQueue;pendingRequests=new Map;constructor(e={}){this.config={baseURL:e.baseURL??``,defaultHeaders:e.defaultHeaders??{"Content-Type":`application/json`},defaultTimeout:e.defaultTimeout??3e4,validateStatus:e.validateStatus??(e=>e>=200&&e<300),cacheStrategy:e.cacheStrategy??new Pe,maxConcurrent:e.maxConcurrent??0,defaultResponseType:e.defaultResponseType??`auto`,defaultHooks:e.defaultHooks??{},transformRequest:e.transformRequest,credentials:K(e.credentials,e.withCredentials),adapter:e.adapter,autoFormData:e.autoFormData??!0,debug:e.debug,logger:e.logger,transport:e.transport,nodeOptions:e.nodeOptions},this.cache=this.config.cacheStrategy,this.requestQueue=this.config.maxConcurrent>0?new Le(this.config.maxConcurrent):null}logDebug(e,t,n,r,i){let a=e??this.config.debug;if(!a||a===!0&&t===`verbose`)return;let o=`[Nexa HTTP] `+n,s=i??this.config.logger??console.log;r===void 0?s(o):s(o,r)}async request(e){let t={...this.config.defaultHooks,...e.hooks},n=e.debug??this.config.debug,a=e.logger??this.config.logger,o=this.getMaxAttempts(e.retry),s=this.getRetryStrategy(e.retry),c=Symbol(`request`);t.onStart?.(this.buildRequest(e)),this.requestQueue&&await this.requestQueue.acquire();try{for(let l=1;l<=o;l++){let u;try{if((e.method===`GET`||!e.method)&&e.cache?.enabled){let i=this.getCacheKey(e),o=this.cache.get(i);if(o){let i=o;return this.logDebug(n,`info`,`Cache hit for ${e.url}`,i,a),t.onSuccess?.(i),t.onFinally?.(),r(i)}}u=this.buildRequest(e),this.logDebug(n,`info`,`${u.method||`GET`} ${u.url}`,u,a);for(let e of this.requestInterceptors)u=await e.onRequest(u);this.logDebug(n,`verbose`,`Request after interceptors`,u,a),u=this.applyTransformRequestToRequest(u,e),this.logDebug(n,`verbose`,`Request after transformRequest`,u,a);let i=Be(e.timeout??this.config.defaultTimeout),s=new AbortController;this.pendingRequests.set(c,s),e.signal&&e.signal.addEventListener(`abort`,()=>s.abort(),{once:!0}),this.logDebug(n,`info`,`Fetching (attempt ${l}/${o})`,{url:u.url,method:u.method},a);let d=performance.now(),f=await this.fetchWithTimeout(u,i,s),p=performance.now()-d;this.logDebug(n,`info`,`Response ${f.status} ${f.statusText}`,{duration:p,status:f.status,attempt:l},a);let m=f;e.onDownloadProgress&&f.body&&(m=this.trackDownloadProgress(f,e.onDownloadProgress));let h=e.responseType??this.config.defaultResponseType,g=await this.parseResponse(m,u,p,h,i.response);if(!this.config.validateStatus(g.status))throw{message:`Request failed with status ${g.status}`,status:g.status,statusText:g.statusText,code:`HTTP_ERROR`,request:u,response:g,config:e};if(e.validate){let t=e.validate.validate(g.data);if(!t.ok)return t}e.transform&&(g.data=e.transform.transform(g.data));let _=g;for(let e of this.responseInterceptors)_=await e.onResponse(_);if((e.method===`GET`||!e.method)&&e.cache?.enabled){let t=this.getCacheKey(e);this.cache.set(t,_,e.cache.ttlMs)}return t.onSuccess?.(_),this.logDebug(n,`verbose`,`Response data`,_.data,a),this.pendingRequests.delete(c),r(_)}catch(r){let d=this.normalizeError(r,u,e);if(this.logDebug(n,`info`,`Error: ${d.message}`,{error:d,attempt:l},a),l<o&&s.shouldRetry(l,d)){t.onRetry?.(l,d);let e=s.delayMs(l);this.logDebug(n,`info`,`Retrying after ${e}ms (attempt ${l+1}/${o})`,{error:d},a),await this.delay(e);continue}let f=d;for(let e of this.responseInterceptors)e.onError&&(f=await e.onError(f));return t.onError?.(f),this.pendingRequests.delete(c),i(f)}}let l={message:`Max retries exceeded`,code:`MAX_RETRIES`};return this.logDebug(n,`info`,`Max retries exceeded`,l,a),t.onError?.(l),i(l)}finally{t.onFinally?.(),this.requestQueue&&this.requestQueue.release()}}get(e,t){return this.request({...t,url:e,method:`GET`})}post(e,t,n){return this.request({...n,url:e,method:`POST`,body:t})}put(e,t,n){return this.request({...n,url:e,method:`PUT`,body:t})}patch(e,t,n){return this.request({...n,url:e,method:`PATCH`,body:t})}delete(e,t){return this.request({...t,url:e,method:`DELETE`})}head(e,t){return this.request({...t,url:e,method:`HEAD`})}options(e,t){return this.request({...t,url:e,method:`OPTIONS`})}addRequestInterceptor(e){return this.requestInterceptors.push(e),()=>{let t=this.requestInterceptors.indexOf(e);t!==-1&&this.requestInterceptors.splice(t,1)}}addResponseInterceptor(e){return this.responseInterceptors.push(e),()=>{let t=this.responseInterceptors.indexOf(e);t!==-1&&this.responseInterceptors.splice(t,1)}}clearInterceptors(){this.requestInterceptors=[],this.responseInterceptors=[]}clearCache(){this.cache.clear()}cancelAll(){for(let e of this.pendingRequests.values())e.abort();this.pendingRequests.clear()}get activeRequests(){return this.pendingRequests.size}get queueStats(){return{active:this.requestQueue?.active??this.pendingRequests.size,pending:this.requestQueue?.pending??0}}extend(t={}){let n=new e({baseURL:t.baseURL??this.config.baseURL,defaultHeaders:{...this.config.defaultHeaders,...t.defaultHeaders},credentials:K(t.credentials,t.withCredentials)??this.config.credentials,defaultTimeout:t.defaultTimeout??this.config.defaultTimeout,validateStatus:t.validateStatus??this.config.validateStatus,cacheStrategy:t.cacheStrategy??this.cache,maxConcurrent:t.maxConcurrent??this.config.maxConcurrent,defaultResponseType:t.defaultResponseType??this.config.defaultResponseType,defaultHooks:{...this.config.defaultHooks,...t.defaultHooks},transformRequest:t.transformRequest??this.config.transformRequest,adapter:t.adapter??this.config.adapter,autoFormData:t.autoFormData??this.config.autoFormData});for(let e of this.requestInterceptors)n.addRequestInterceptor(e);for(let e of this.responseInterceptors)n.addResponseInterceptor(e);return n}async*paginate(e,t,n={}){let r={...n};for(;;){let n=await this.get(e,r);if(!n.ok)break;yield t.getItems(n.value.data);let i=t.getNextPage(n.value.data,r);if(!i)break;r=i}}async poll(e,t,n={}){let r=t.maxAttempts??0;for(let i=1;r===0||i<=r;i++){let a=await this.get(e,n);if(!a.ok||(t.onPoll?.(a.value.data,i),t.until(a.value.data)))return a;if(r>0&&i>=r)break;await this.delay(t.intervalMs)}return i({message:`Polling exhausted after ${r} attempts`,code:`POLL_EXHAUSTED`})}buildRequest(e){let t=G(e.url,e.params),n=this.buildUrl(t,e.query),r=K(e.credentials,e.withCredentials)??this.config.credentials,i=e.transport??this.config.transport,a=e.nodeOptions??this.config.nodeOptions;return{url:n,method:e.method??`GET`,headers:{...this.config.defaultHeaders,...e.headers},body:e.body,query:e.query,params:e.params,timeout:e.timeout,signal:e.signal,credentials:r,adapter:e.adapter,autoFormData:e.autoFormData??this.config.autoFormData,transport:i,nodeOptions:a}}buildUrl(e,t){let n=this.config.baseURL+e;if(t&&Object.keys(t).length>0){let e=new URLSearchParams;Object.entries(t).forEach(([t,n])=>{e.append(t,String(n))}),n+=`?${e.toString()}`}return n}applyTransformRequestToRequest(e,t){let n=this.config.transformRequest,r=t.transformRequest,i=[];if(n&&(Array.isArray(n)?i.push(...n):i.push(n)),r&&(Array.isArray(r)?i.push(...r):i.push(r)),i.length===0)return e;let a=e.body,o=e.headers??{};for(let e of i)a=e(a,o);return{...e,body:a,headers:o}}getCacheKey(e){let t=G(e.url,e.params),n=e.query?JSON.stringify(e.query):``;return`${e.method??`GET`}:${t}${n?`:`+n:``}`}fetchWithTimeout(e,t,n){let{serialized:r,contentType:i}=ze(e.body,e.autoFormData),a={...e.headers};i?a[`Content-Type`]=i:i===null&&r instanceof FormData&&delete a[`Content-Type`];let o=t.total??t.connection;return new Promise((t,i)=>{let s=null;o!==void 0&&(s=setTimeout(()=>{n.abort();let e=Error(`Request timed out`);e.name=`TimeoutError`,i(e)},o));let c={method:e.method,headers:a,body:r,signal:n.signal};e.credentials!==void 0&&(c.credentials=e.credentials);let l=e.transport??this.config.transport??`fetch`,u=e.nodeOptions??this.config.nodeOptions,d=e.adapter??this.config.adapter;d||=Ne(l,u),d(e.url,c).then(e=>{s&&clearTimeout(s),t(e)},e=>{s&&clearTimeout(s),i(e)})})}trackDownloadProgress(e,t){let n=parseInt(e.headers.get(`content-length`)||`0`,10),r=e.body?.getReader();if(!r)return e;let i=0,a=new ReadableStream({async pull(e){let{done:a,value:o}=await r.read();if(a){e.close();return}i+=o.byteLength,t({loaded:i,total:n,percent:n>0?Math.round(i/n*100):0}),e.enqueue(o)}});return new Response(a,{headers:e.headers,status:e.status,statusText:e.statusText})}withTimeout(e,t,n=`Operation timed out`){return t<=0?e:new Promise((r,i)=>{let a=setTimeout(()=>{let e=Error(n);e.name=`TimeoutError`,i(e)},t);e.then(e=>{clearTimeout(a),r(e)},e=>{clearTimeout(a),i(e)})})}async parseResponse(e,t,n,r,i){let a=await this.parseBody(e,r,i);return{status:e.status,statusText:e.statusText,headers:e.headers,data:a,request:t,duration:n}}async parseBody(e,t,n){let r=async e=>n!==void 0&&n>0?this.withTimeout(e,n,`Response timeout`):e;switch(t){case`json`:return await r(e.json());case`text`:return await r(e.text());case`blob`:return await r(e.blob());case`arrayBuffer`:return await r(e.arrayBuffer());case`formData`:return await r(e.formData());case`stream`:return e.body;default:{let t=e.headers.get(`content-type`)??``;if(t.includes(`application/json`))return await r(e.json());if(t.includes(`text/`))return await r(e.text());if(t.includes(`multipart/form-data`))return await r(e.formData());if(t.includes(`application/octet-stream`)||t.includes(`image/`)||t.includes(`audio/`)||t.includes(`video/`))return await r(e.blob());try{return await r(e.json())}catch{return await r(e.text())}}}}normalizeError(e,t,n){let r=(r,i)=>({message:i,code:r,originalError:e,request:t,config:n});return e instanceof Error&&e.name===`TimeoutError`?e.message.includes(`Response timeout`)?r(`RESPONSE_TIMEOUT`,e.message):r(`TIMEOUT`,`Request timed out`):e instanceof DOMException&&e.name===`AbortError`?r(`ABORTED`,`Request aborted`):e instanceof Error?e.name===`AbortError`||e.message.includes(`abort`)?r(`ABORTED`,`Request aborted`):{message:e.message,code:e.name===`TypeError`?`NETWORK_ERROR`:`UNKNOWN_ERROR`,originalError:e,request:t,config:n}:this.isHttpErrorDetails(e)?{...e,request:e.request??t,config:e.config??n}:{message:String(e),code:`UNKNOWN_ERROR`,originalError:e,request:t,config:n}}isHttpErrorDetails(e){return typeof e==`object`&&!!e&&`message`in e&&`code`in e}getMaxAttempts(e){return e?`shouldRetry`in e?100:e.maxAttempts??3:1}getRetryStrategy(e){if(!e)return{shouldRetry:()=>!1,delayMs:()=>0};if(`shouldRetry`in e)return e;let t=e;return t.on?new Ie(t.maxAttempts??3,t.backoffMs??100,t.on):new Fe(t.maxAttempts??3,t.backoffMs??100)}delay(e){return new Promise(t=>setTimeout(t,e))}},J=class extends Error{status;code;response;constructor(e,t,n,r){super(e),this.name=`HttpError`,this.status=t,this.code=n,this.response=r}};function Ve(e){return e instanceof J}function He(e){return new q(e)}function Y(){return typeof window>`u`&&typeof process<`u`&&process.versions?.node!==void 0}var Ue=class{url;options;pluginManager;status=`closed`;reconnectAttempt=0;reconnectTimer=null;heartbeatTimer=null;stats={messagesSent:0,messagesReceived:0,connectionTime:0,reconnectAttempts:0};connectionStartTime=0;listeners={open:new Set,close:new Set,error:new Set,message:new Set};constructor(e,t={}){this.url=e,this.options=t,this.pluginManager=new P}updateStatus(e){this.status=e,e===`open`?this.connectionStartTime=Date.now():e===`closed`&&this.connectionStartTime>0&&(this.stats.connectionTime+=Date.now()-this.connectionStartTime,this.connectionStartTime=0)}emitOpen(e){this.pluginManager.emit(`websocket:open`,this.url,e);for(let t of this.listeners.open)t(e)}emitClose(e){this.pluginManager.emit(`websocket:close`,this.url,e);for(let t of this.listeners.close)t(e)}emitError(e){let t;e instanceof Error?(t=new Event(`error`),t.error=e):t=e,this.pluginManager.emit(`websocket:error`,this.url,t);for(let e of this.listeners.error)e(t)}emitMessage(e){this.pluginManager.emit(`websocket:message`,this.url,e);for(let t of this.listeners.message)t(e)}onOpen(e){return this.listeners.open.add(e),()=>this.listeners.open.delete(e)}onClose(e){return this.listeners.close.add(e),()=>this.listeners.close.delete(e)}onError(e){return this.listeners.error.add(e),()=>this.listeners.error.delete(e)}onMessage(e){return this.listeners.message.add(e),()=>this.listeners.message.delete(e)}getStatus(){return this.status}getStats(){return{...this.stats,connectionTime:this.stats.connectionTime+(this.connectionStartTime>0?Date.now()-this.connectionStartTime:0)}}scheduleReconnect(){if(this.options.reconnect?.enabled===!1)return;let e=this.options.reconnect?.maxAttempts??1/0;if(this.reconnectAttempt>=e){this.pluginManager.emit(`websocket:reconnect:failed`,this.url,this.reconnectAttempt);return}let t=this.options.reconnect?.baseDelay??1e3,n=this.options.reconnect?.maxDelay??3e4,r=Math.min(n,t*2**this.reconnectAttempt);this.reconnectAttempt++,this.stats.reconnectAttempts=this.reconnectAttempt,this.options.reconnect?.onReconnecting?.(this.reconnectAttempt,r),this.pluginManager.emit(`websocket:reconnecting`,this.url,this.reconnectAttempt,r),this.reconnectTimer=setTimeout(()=>{this.connect().catch(e=>{this.emitError(e instanceof Error?e:Error(String(e)))})},r)}startHeartbeat(){if(!this.options.heartbeat)return;let e=this.options.heartbeat.interval??3e4,t=this.options.heartbeat.pingMessage??`ping`,n=this.options.heartbeat.pongMessage??`pong`,r=!0,i=()=>{if(!r){this.pluginManager.emit(`websocket:heartbeat:timeout`,this.url),this.disconnect();return}r=!1,this.send(t),this.heartbeatTimer=setTimeout(i,e)};this.onMessage(e=>{let t=e.raw;typeof t==`string`&&t===n&&(r=!0)}),this.heartbeatTimer=setTimeout(i,e)}stopHeartbeat(){this.heartbeatTimer&&=(clearTimeout(this.heartbeatTimer),null)}cleanup(){this.reconnectTimer&&=(clearTimeout(this.reconnectTimer),null),this.stopHeartbeat()}},X=class extends Ue{socket=null;messageTypeListeners=new Map;constructor(e,t={}){super(e,t)}async connect(){if(!(this.status===`connecting`||this.status===`open`))return this.updateStatus(`connecting`),this.pluginManager.emit(`websocket:connect:start`,this.url),new Promise((e,t)=>{let n=this.options.timeout??1e4,r=setTimeout(()=>{this.updateStatus(`closed`),this.socket?.close(),this.socket=null;let e=Error(`WebSocket connection timeout after ${n}ms`);this.emitError(e),t(e)},n);try{this.socket=new WebSocket(this.url,this.options.protocols),this.socket.onopen=t=>{clearTimeout(r),this.updateStatus(`open`),this.reconnectAttempt=0,this.emitOpen(t),this.options.onOpen?.(t),this.startHeartbeat(),this.pluginManager.emit(`websocket:connect:success`,this.url),e()},this.socket.onclose=e=>{clearTimeout(r),this.updateStatus(`closed`),this.emitClose(e),this.options.onClose?.(e),this.stopHeartbeat(),this.pluginManager.emit(`websocket:disconnected`,this.url,e.code,e.reason),e.code!==1e3&&!e.wasClean&&this.scheduleReconnect()},this.socket.onerror=e=>{clearTimeout(r),this.updateStatus(`closed`),this.emitError(e),this.options.onError?.(e),this.pluginManager.emit(`websocket:connect:error`,this.url,e),t(e)},this.socket.onmessage=e=>{this.stats.messagesReceived++;let t={data:this.tryParseData(e.data),raw:e.data,type:`message`,timestamp:Date.now()};this.emitMessage(t),this.pluginManager.emit(`websocket:message:received`,this.url,t)}}catch(e){clearTimeout(r),this.updateStatus(`closed`),this.pluginManager.emit(`websocket:connect:error`,this.url,e),t(e)}})}disconnect(){this.cleanup(),this.socket&&(this.updateStatus(`closing`),this.socket.close(1e3,`Client disconnected`),this.socket=null,this.updateStatus(`closed`))}send(e){if(!this.socket||this.socket.readyState!==WebSocket.OPEN)throw Error(`WebSocket is not connected`);this.socket.send(e),this.stats.messagesSent++,this.pluginManager.emit(`websocket:message:sent`,this.url,e)}sendJson(e){this.send(JSON.stringify(e))}onMessageType(e,t){return this.messageTypeListeners.has(e)||this.messageTypeListeners.set(e,new Set),this.messageTypeListeners.get(e).add(t),()=>{let n=this.messageTypeListeners.get(e);n&&(n.delete(t),n.size===0&&this.messageTypeListeners.delete(e))}}tryParseData(e){if(typeof e==`string`)try{return JSON.parse(e)}catch{return e}return e}},We=class extends X{async connect(){if(Y())try{let{default:e}=await import(`ws`);return super.connect()}catch{throw Error(`WebSocket client for Node.js requires the "ws" package. Please install it: npm install ws`)}return super.connect()}};function Ge(e,t={}){return Y()?new We(e,t):new X(e,t)}function Z(){return typeof window>`u`&&typeof process<`u`&&process.versions?.node!==void 0}var Ke=class{url;options;_source=null;pluginManager;status=`closed`;reconnectAttempt=0;reconnectTimer=null;stats={messagesSent:0,messagesReceived:0,connectionTime:0,reconnectAttempts:0};connectionStartTime=0;listeners={open:new Set,close:new Set,error:new Set,message:new Set,event:new Map};_lastEventId=null;constructor(e,t={}){this.url=e,this.options=t,this.pluginManager=new P}updateStatus(e){this.status=e,e===`open`?this.connectionStartTime=Date.now():e===`closed`&&this.connectionStartTime>0&&(this.stats.connectionTime+=Date.now()-this.connectionStartTime,this.connectionStartTime=0)}async connect(){if(!(this.status===`connecting`||this.status===`open`))return this.updateStatus(`connecting`),this.pluginManager.emit(`sse:connect:start`,this.url),new Promise((e,t)=>{let n=this.options.timeout??1e4,r=setTimeout(()=>{this.updateStatus(`closed`),this._source?.close(),this._source=null;let e=Error(`SSE connection timeout after ${n}ms`);this.emitError(e),t(e)},n);try{this._source=new EventSource(this.url),this._source.onopen=t=>{clearTimeout(r),this.updateStatus(`open`),this.reconnectAttempt=0,this.emitOpen(t),this.options.onOpen?.(t),this.pluginManager.emit(`sse:connect:success`,this.url),e()},this._source.onerror=e=>{clearTimeout(r),this.updateStatus(`closed`),this.emitError(e),this.options.onError?.(e),this.pluginManager.emit(`sse:connect:error`,this.url,e),this._source?.readyState===EventSource.CLOSED&&(this.emitClose(),this.options.onClose?.(),this.scheduleReconnect()),t(e)},this._source.onmessage=e=>{this.stats.messagesReceived++,this._lastEventId=e.lastEventId||this._lastEventId;let t={data:this.tryParseData(e.data),raw:e.data,type:e.type||`message`,timestamp:Date.now()};this.emitMessage(t),this.pluginManager.emit(`sse:message:received`,this.url,t);let n=e.type||`message`,r=this.listeners.event.get(n);if(r)for(let e of r)e(t.data)},this._source.addEventListener=this._source.addEventListener.bind(this._source)}catch(e){clearTimeout(r),this.updateStatus(`closed`),this.pluginManager.emit(`sse:connect:error`,this.url,e),t(e)}})}disconnect(){this.cleanup(),this._source&&(this.updateStatus(`closing`),this._source.close(),this._source=null,this.updateStatus(`closed`),this.emitClose(),this.options.onClose?.())}send(e){throw Error(`SSE is a receive-only protocol. Use HTTP requests to send data to server.`)}onMessage(e){return this.listeners.message.add(e),()=>this.listeners.message.delete(e)}onOpen(e){return this.listeners.open.add(e),()=>this.listeners.open.delete(e)}onClose(e){return this.listeners.close.add(e),()=>this.listeners.close.delete(e)}onError(e){return this.listeners.error.add(e),()=>this.listeners.error.delete(e)}onEvent(e,t){return this.listeners.event.has(e)||this.listeners.event.set(e,new Set),this.listeners.event.get(e).add(t),this._source&&!this._source[`on${e}`]&&this._source.addEventListener(e,n=>{t({data:this.tryParseData(n.data),raw:n.data,type:e,timestamp:Date.now()}.data)}),()=>{let n=this.listeners.event.get(e);n&&(n.delete(t),n.size===0&&this.listeners.event.delete(e))}}getStatus(){return this.status}getStats(){return{...this.stats,connectionTime:this.stats.connectionTime+(this.connectionStartTime>0?Date.now()-this.connectionStartTime:0)}}get lastEventId(){return this._lastEventId}get source(){return this._source}emitOpen(e){this.pluginManager.emit(`sse:open`,this.url,e);for(let t of this.listeners.open)t(e)}emitClose(){this.pluginManager.emit(`sse:close`,this.url);for(let e of this.listeners.close)e()}emitError(e){let t;e instanceof Error?(t=new Event(`error`),t.error=e):t=e,this.pluginManager.emit(`sse:error`,this.url,t);for(let e of this.listeners.error)e(t)}emitMessage(e){this.pluginManager.emit(`sse:message`,this.url,e);for(let t of this.listeners.message)t(e)}scheduleReconnect(){if(this.options.reconnect?.enabled===!1)return;let e=this.options.reconnect?.maxAttempts??1/0;if(this.reconnectAttempt>=e){this.pluginManager.emit(`sse:reconnect:failed`,this.url,this.reconnectAttempt);return}let t=this.options.reconnect?.baseDelay??1e3,n=this.options.reconnect?.maxDelay??3e4,r=Math.min(n,t*2**this.reconnectAttempt);this.reconnectAttempt++,this.stats.reconnectAttempts=this.reconnectAttempt,this.options.reconnect?.onReconnecting?.(this.reconnectAttempt,r),this.pluginManager.emit(`sse:reconnecting`,this.url,this.reconnectAttempt,r),this.reconnectTimer=setTimeout(()=>{this.connect().catch(e=>{this.emitError(e instanceof Error?e:Error(String(e)))})},r)}cleanup(){this.reconnectTimer&&=(clearTimeout(this.reconnectTimer),null)}tryParseData(e){try{return JSON.parse(e)}catch{return e}}},qe=class extends Ke{async connect(){if(Z())throw Error(`SSE client for Node.js requires a polyfill or custom implementation. Consider using a library like "eventsource" or implement using fetch with streaming.`);return super.connect()}};function Je(e,t={}){return Z()?new qe(e,t):new Ke(e,t)}var Ye=class{name=`realtime`;setup(e){e.on(`websocket:connect:start`,(...t)=>{let n=t[0];e.emit(`realtime:connect:start`,`websocket`,n)}),e.on(`websocket:connect:success`,(...t)=>{let n=t[0];e.emit(`realtime:connect:success`,`websocket`,n)}),e.on(`websocket:message:received`,(...t)=>{let n=t[0],r=t[1];e.emit(`realtime:message`,`websocket`,n,r)}),e.on(`sse:connect:start`,(...t)=>{let n=t[0];e.emit(`realtime:connect:start`,`sse`,n)}),e.on(`sse:connect:success`,(...t)=>{let n=t[0];e.emit(`realtime:connect:success`,`sse`,n)}),e.on(`sse:message:received`,(...t)=>{let n=t[0],r=t[1];e.emit(`realtime:message`,`sse`,n,r)})}};function Xe(){return new Ye}var Q=class{adapter;method;urlPattern;constructor(e,t,n){this.adapter=e,this.method=t,this.urlPattern=n}reply(e,t,n){let r;return r=typeof e==`number`?{status:e,data:t,headers:n}:e,this.adapter.addRoute(this.method,this.urlPattern,r),this.adapter}replyOnce(e,t,n){let r;return r=typeof e==`number`?{status:e,data:t,headers:n}:e,this.adapter.addRoute(this.method,this.urlPattern,r,{times:1}),this.adapter}networkError(e=`Network Error`){return this.adapter.addRoute(this.method,this.urlPattern,{networkError:!0,errorMessage:e}),this.adapter}timeout(){return this.adapter.addRoute(this.method,this.urlPattern,{status:408,statusText:`Request Timeout`}),this.adapter}},$=class{routes=[];originalAdapter;mockClient;options;defaultResponse={status:200,statusText:`OK`,headers:{"content-type":`application/json`}};constructor(e,t={}){this.options=t;let n=this.createAdapter();if(typeof e.extend==`function`)this.mockClient=e.extend({adapter:n});else throw Error(`MockAdapter requires an HttpClient instance with extend() method`)}get client(){return this.mockClient}createAdapter(){return async(e,t)=>{let n=typeof e==`string`?e:e.url,r=t?.method||`GET`,i={url:n,method:r,headers:t?.headers,body:t?.body,signal:t?.signal??void 0},a=this.findMatchingRoute(r,n);if(!a)return this.options.passthrough?(this.originalAdapter||fetch)(e,t):new Response(JSON.stringify({error:`No mock route matched`}),{status:404,statusText:`Not Found`,headers:{"content-type":`application/json`}});a.timesCalled++;let o;if(o=typeof a.response==`function`?await a.response(i):a.response,o.networkError)throw TypeError(o.errorMessage||`Network Error`);let s=Object.fromEntries(Object.entries(o).filter(([e,t])=>t!==void 0)),c={...this.defaultResponse,...s};if(o.headers&&`content-type`in o.headers||(c.data instanceof Uint8Array||ArrayBuffer.isView(c.data)?c.headers={...c.headers,"content-type":`application/octet-stream`}:c.data&&typeof c.data==`object`&&(c.headers={...c.headers,"content-type":`application/json`})),c.delay||this.options.delay){let e=c.delay??this.options.delay;if(e&&e>0){let n=t?.signal;n?(n.throwIfAborted(),await new Promise((t,r)=>{let i=setTimeout(t,e),a=()=>{clearTimeout(i),r(new DOMException(`Aborted`,`AbortError`))};n.addEventListener(`abort`,a,{once:!0}),setTimeout(()=>{n.removeEventListener(`abort`,a)},e)})):await new Promise(t=>setTimeout(t,e))}}let l=new Headers(c.headers),u=c.data;(c.status===204||c.status===205)&&l.delete(`content-type`);let d;if(u==null)d=``;else if(typeof u==`string`)d=u;else if(u instanceof Uint8Array||ArrayBuffer.isView(u)){let e;if(u.buffer instanceof ArrayBuffer)e=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);else{let t=new Uint8Array(u.byteLength);t.set(new Uint8Array(u.buffer,u.byteOffset,u.byteLength)),e=t.buffer}return new Response(e,{status:c.status,statusText:c.statusText,headers:l})}else d=JSON.stringify(u);let f=d;return(c.status===204||c.status===205||f===``)&&(f=null),f===null&&l.delete(`content-type`),new Response(f,{status:c.status,statusText:c.statusText,headers:l})}}onGet(e){return new Q(this,`GET`,e)}onPost(e){return new Q(this,`POST`,e)}onPut(e){return new Q(this,`PUT`,e)}onPatch(e){return new Q(this,`PATCH`,e)}onDelete(e){return new Q(this,`DELETE`,e)}onAny(e){return new Q(this,`ANY`,e)}addRoute(e,t,n,r){return this.routes.push({method:e.toUpperCase(),urlPattern:t,response:n,timesCalled:0,times:r?.times}),this}reset(){this.routes=[]}restore(){}static reply(e,t,n){return{status:e,data:t,headers:n}}static networkError(e=`Network Error`){return{networkError:!0,errorMessage:e}}findMatchingRoute(e,t){let n=t;if(this.options.baseURL&&t.startsWith(this.options.baseURL))n=t.slice(this.options.baseURL.length);else try{if(n.includes(`://`)){let e=new URL(n);n=e.pathname+e.search}}catch{}for(let t of this.routes){if(t.times&&t.timesCalled>=t.times||t.method!==`ANY`&&t.method!==e.toUpperCase())continue;let r=!1;if(typeof t.urlPattern==`string`?r=n===t.urlPattern||n.startsWith(t.urlPattern):t.urlPattern instanceof RegExp&&(r=t.urlPattern.test(n)),r)return t}return null}};function Ze(e,t={}){return new $(e,t)}exports.AggressiveRetry=m,exports.CachePlugin=_e,exports.CacheStore=S,exports.CircuitBreakerPlugin=be,exports.CircuitBreakerRetry=g,exports.ConservativeRetry=h,exports.DedupePlugin=ve,exports.Defer=fe,exports.Err=i,exports.HttpClient=q,exports.HttpError=J,exports.LoggerPlugin=he,exports.MetricsPlugin=ge,exports.MiddlewarePipeline=oe,exports.MockAdapter=$,exports.Ok=r,exports.PluginManager=P,exports.RateLimitPlugin=ye,exports.RequestDeduplicator=w,exports.TypedObservable=le,exports.cacheMiddleware=ne,exports.circuitBreakerMiddleware=ae,exports.createApiUrl=de,exports.createCacheMiddleware=C,exports.createCircuitBreakerMiddleware=D,exports.createDedupeMiddleware=T,exports.createHttpClient=He,exports.createMockClient=Ze,exports.createPipeline=O,exports.createProjectionTransformer=f,exports.createRateLimitMiddleware=E,exports.createRealtimePlugin=Xe,exports.createRequiredFieldsValidator=o,exports.createSSEClient=Je,exports.createSchemaValidator=a,exports.createStreamingMiddleware=N,exports.createTypeGuard=ue,exports.createTypedApiClient=ce,exports.createTypedRequest=k,exports.createTypedResponse=se,exports.createUrl=A,exports.createWebSocketClient=Ge,exports.createWrapperTransformer=p,exports.dedupeMiddleware=re,exports.handleStream=j,exports.isHttpError=Ve,exports.rateLimitMiddleware=ie,exports.retry=x,exports.streamToFile=pe,exports.streamingMiddleware=me,exports.transformCamelToSnake=u,exports.transformFlatten=d,exports.transformSnakeToCamel=l,exports.validatorIsArray=s,exports.validatorIsObject=c,exports.withTimeout=te;
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=e=>({ok:!0,value:e}),t=e=>({ok:!1,error:e});function n(n){return{validate(r){let i=r;for(let[e,r]of Object.entries(n))if(!r(i[e]))return t({message:`Validation failed: field "${e}" is invalid`,code:`VALIDATION_ERROR`});return e(r)}}}function r(n){return{validate(r){let i=r,a=n.filter(e=>!(e in i));return a.length>0?t({message:`Validation failed: missing fields: ${a.join(`, `)}`,code:`VALIDATION_ERROR`}):e(r)}}}var i={validate(n){return Array.isArray(n)?e(n):t({message:`Expected array response`,code:`VALIDATION_ERROR`})}},a={validate(n){return n&&typeof n==`object`&&!Array.isArray(n)?e(n):t({message:`Expected object response`,code:`VALIDATION_ERROR`})}},o={transform(e){return m(e,ee)}},s={transform(e){return m(e,te)}},c={transform(e){return h(e)}};function l(e){return{transform(t){return Array.isArray(t)?t.map(t=>g(t,e)):g(t,e)}}}function u(e){return{transform(t){return{[e]:t}}}}var d=class{maxAttempts;constructor(e=5){this.maxAttempts=e}shouldRetry(e){return e<this.maxAttempts}delayMs(e){return e*50}},f=class{retryableStatuses=[408,429,500,502,503,504];maxAttempts;constructor(e=3){this.maxAttempts=e}shouldRetry(e,t){return e>=this.maxAttempts?!1:this.retryableStatuses.includes(t.status??0)||t.code===`TIMEOUT`}delayMs(e){return Math.min(1e3*2**(e-1),1e4)}},p=class{failureCount=0;lastFailureTime=0;maxAttempts;failureThreshold;resetTimeMs;constructor(e=3,t=5,n=6e4){this.maxAttempts=e,this.failureThreshold=t,this.resetTimeMs=n}shouldRetry(e){return e>=this.maxAttempts||(Date.now()-this.lastFailureTime>this.resetTimeMs&&(this.failureCount=0),this.failureCount>=this.failureThreshold)?!1:(this.failureCount++,this.lastFailureTime=Date.now(),!0)}delayMs(e){return 100*2**(e-1)}reset(){this.failureCount=0,this.lastFailureTime=0}};function ee(e){return e.replace(/_([a-z])/g,(e,t)=>t.toUpperCase())}function te(e){return e.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function m(e,t){if(!e||typeof e!=`object`)return e;if(Array.isArray(e))return e.map(e=>m(e,t));let n={};for(let[r,i]of Object.entries(e))n[t(r)]=m(i,t);return n}function h(e,t=``){let n={};if(Array.isArray(e))e.forEach((e,r)=>{let i=t?`${t}[${r}]`:`[${r}]`;Object.assign(n,h(e,i))});else if(e&&typeof e==`object`)for(let[r,i]of Object.entries(e)){let e=t?`${t}.${r}`:r;i&&typeof i==`object`&&!Array.isArray(i)?Object.assign(n,h(i,e)):n[e]=i}return n}function g(e,t){if(!e||typeof e!=`object`)return{};let n=e,r={};for(let e of t)e in n&&(r[e]=n[e]);return r}function ne(e){let t=new AbortController,n=setTimeout(()=>t.abort(),e);return t.signal.addEventListener(`abort`,()=>clearTimeout(n),{once:!0}),t}async function _(e,t=3){try{return await e()}catch(n){if(t<=0)throw n;return _(e,t-1)}}var v=class{cache=new Map;get(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp>t.ttlMs?(this.cache.delete(e),null):t.data:null}set(e,t,n=6e4){this.cache.set(e,{data:t,timestamp:Date.now(),ttlMs:n})}clear(){this.cache.clear()}has(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp>t.ttlMs?(this.cache.delete(e),!1):!0:!1}delete(e){this.cache.delete(e)}};function y(e={}){let t=e.cache||new v,n=e.ttlMs||6e4,r=e.cacheableStatuses||[200,304];return async(e,i)=>{let a=(e.request.method||`GET`).toUpperCase(),o=a===`GET`,s=`${a}:${e.request.url}`;if(o&&t.has(s)){let n=t.get(s);if(n){e.response=n,e.state.cacheHit=!0;return}}await i(),o&&e.response&&r.includes(e.response.status)&&(t.set(s,e.response,n),e.state.cacheMiss=!0)}}var b=y(),x=class{pending=new Map;async execute(e,t){if(this.pending.has(e))return this.pending.get(e);let n=t().finally(()=>{this.pending.delete(e)});return this.pending.set(e,n),n}clear(){this.pending.clear()}};function S(e={}){let t=e.deduplicator||new x,n=e.includeBody??!1,r=e.methods||[`GET`];return async(e,i)=>{let a=(e.request.method||`GET`).toUpperCase();if(!r.includes(a)){await i();return}let o=`${a}:${e.request.url}`;n&&e.request.body&&(o+=`:${JSON.stringify(e.request.body)}`);try{e.response=await t.execute(o,async()=>(await i(),e.response)),e.state.deduped=!0}catch(t){throw e.error=t,t}}}var re=S();function C(e){return async t=>{let n=-1;async function r(i){if(i<=n)throw Error(`next() called multiple times`);n=i;let a=e[i];a&&await a(t,()=>r(i+1))}await r(0)}}var ie=class{middlewares=[];use(e){return this.middlewares.push(e),this}async execute(e){if(e&&typeof e==`object`&&`request`in e&&`response`in e){let t=e;return await C(this.middlewares.map(e=>typeof e==`function`&&e.length===2?e:async(t,n)=>{let r=e;t.response.body=await r(t.response.body),await n()}))(t),t.response.body}let t=e;for(let e of this.middlewares)t=await e(t);return t}clear(){this.middlewares=[]}};function w(e,t,n,r={}){return{ok:e>=200&&e<300,data:t,error:n,status:e,headers:r}}function T(e){return async(t,n)=>{let r=e.path,i;switch(e.method){case`GET`:i=await t.get(r);break;case`POST`:i=await t.post(r,n);break;case`PUT`:i=await t.put(r,n);break;case`PATCH`:i=await t.patch(r,n);break;case`DELETE`:i=await t.delete(r);break;default:throw Error(`Unsupported method: ${e.method}`)}return i}}function E(e){return{request:async(t,n,r)=>{let i=e[n];return await T(i)(t,r)}}}var D=class e{subscribers=[];errorSubscribers=[];completeSubscribers=[];subscribe(e,t,n){return e&&this.subscribers.push(e),t&&this.errorSubscribers.push(t),n&&this.completeSubscribers.push(n),{unsubscribe:()=>{this.subscribers=this.subscribers.filter(t=>t!==e),this.errorSubscribers=this.errorSubscribers.filter(e=>e!==t),this.completeSubscribers=this.completeSubscribers.filter(e=>e!==n)}}}next(e){this.subscribers.forEach(t=>t(e))}error(e){this.errorSubscribers.forEach(t=>t(e))}complete(){this.completeSubscribers.forEach(e=>e())}map(t){let n=new e;return this.subscribe(e=>n.next(t(e)),e=>n.error(e),()=>n.complete()),n}filter(t){let n=new e;return this.subscribe(e=>{t(e)&&n.next(e)},e=>n.error(e),()=>n.complete()),n}};function ae(e){return t=>{if(!e(t))throw TypeError(`Value does not match expected type`);return t}}function O(e){return e}function oe(e){return O(e)}var se=class{_promise;resolveFunc;rejectFunc;constructor(){this._promise=new Promise((e,t)=>{this.resolveFunc=e,this.rejectFunc=t})}resolve(e){this.resolveFunc(e)}reject(e){this.rejectFunc(e)}get promise(){return this._promise}promise_(){return this._promise}};async function k(e,t={}){let n=e.body?.getReader();if(!n)throw Error(`Response body is not readable`);let r=[],i=0,a=parseInt(e.headers.get(`content-length`)||`0`,10);for(;;){let{done:e,value:o}=await n.read();if(e)break;r.push(o),i+=o.length,t.onChunk&&await t.onChunk(o),t.onProgress&&a>0&&t.onProgress(i,a)}return A(r,i)}function A(e,t){let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.byteLength;return n}async function ce(e,t){let n=await k(e);if(typeof window>`u`)await(await import(`fs`).then(e=>e.promises)).writeFile(t,n);else{let e=new Blob([n.buffer],{type:`application/octet-stream`}),r=URL.createObjectURL(e),i=document.createElement(`a`);i.href=r,i.download=t,i.click(),URL.revokeObjectURL(r)}}function j(e={}){return async(t,n)=>{if(await n(),t.response&&t.response.body&&typeof t.response.body==`object`&&`getReader`in t.response.body){let n=t.response.body.getReader(),r=[],i=0,a=parseInt(t.response.headers?.[`content-length`]||`0`,10);try{for(;;){let{done:o,value:s}=await n.read();if(o)break;r.push(s),i+=s.length,e.onChunk&&await e.onChunk(s),e.onProgress&&a>0&&e.onProgress(i,a),t.state.streamedChunks=t.state.streamedChunks||[],t.state.streamedChunks.push(s)}let o=A(r,i);t.response.body=o,t.state.streaming=!0,t.state.streamedBytes=i}finally{n.releaseLock()}}}}var le=j({onProgress:(e,t)=>{if(t>0){let n=Math.round(e/t*100);console.warn(`Streaming: ${n}% (${e}/${t} bytes)`)}}}),M=class{plugins=[];cache=new v;deduplicator=new x;middlewares=[];listeners=new Map;register(e){return this.plugins.push(e),e.setup(this),this.emit(`plugin:registered`,e.name),this}addMiddleware(e){return this.middlewares.push(e),this}getCache(){return this.cache}getDeduplicator(){return this.deduplicator}getPipeline(){return C(this.middlewares)}async executePipeline(e){await this.getPipeline()(e)}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set);let n=this.listeners.get(e),r=t;return n&&n.add(r),this}emit(e,...t){let n=this.listeners.get(e);if(n)for(let e of n)e(...t)}off(e,t){return this.listeners.get(e)?.delete(t),this}getPlugins(){return[...this.plugins]}clear(){this.plugins=[],this.middlewares=[],this.listeners.clear(),this.cache.clear(),this.deduplicator.clear()}},ue={name:`logger`,setup(e){e.on(`request:start`,(...e)=>{let t=e[0];console.warn(`Request started: ${t}`)}),e.on(`request:success`,(...e)=>{let t=e[0],n=e[1];console.warn(`Request succeeded: ${t} (${n})`)}),e.on(`request:error`,(...e)=>{let t=e[0],n=e[1];console.error(`❌ Request failed: ${t}`,n)})}},N=class{name=`metrics`;metrics={requests:0,errors:0,totalTime:0,avgTime:0};setup(e){e.on(`request:complete`,(...e)=>{let t=e[0],n=e[1];this.metrics.requests++,this.metrics.totalTime+=t,this.metrics.avgTime=this.metrics.totalTime/this.metrics.requests,n||this.metrics.errors++})}getMetrics(){return{...this.metrics}}},P=class{name=`cache`;ttlMs;constructor(e=6e4){this.ttlMs=e}setup(e){e.addMiddleware(y({ttlMs:this.ttlMs}))}},F=class{name=`dedupe`;setup(e){e.addMiddleware(S())}},I=class{store=new v;get(e){return this.store.get(e)}set(e,t,n=6e4){this.store.set(e,t,n)}has(e){return this.store.has(e)}clear(){this.store.clear()}},L=class{maxAttempts;baseDelayMs;constructor(e=3,t=100){this.maxAttempts=e,this.baseDelayMs=t}shouldRetry(e,t){let n=t.status!==void 0&&t.status>=500,r=t.code===`NETWORK_ERROR`;return e<this.maxAttempts&&(n||r||t.code===`TIMEOUT`)}delayMs(e){let t=this.baseDelayMs*2**(e-1),n=Math.random()*t*.1;return Math.min(t+n,3e4)}},R=class{running=0;queue=[];maxConcurrent;constructor(e){this.maxConcurrent=e}async acquire(){if(this.running<this.maxConcurrent){this.running++;return}return new Promise(e=>{this.queue.push(()=>{this.running++,e()})})}release(){this.running--;let e=this.queue.shift();e&&e()}get pending(){return this.queue.length}get active(){return this.running}};function z(e){return e==null?{serialized:void 0,contentType:null}:typeof e==`string`?{serialized:e,contentType:`text/plain`}:typeof FormData<`u`&&e instanceof FormData?{serialized:e,contentType:null}:typeof URLSearchParams<`u`&&e instanceof URLSearchParams?{serialized:e,contentType:`application/x-www-form-urlencoded`}:typeof Blob<`u`&&e instanceof Blob?{serialized:e,contentType:e.type||`application/octet-stream`}:e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof ReadableStream<`u`&&e instanceof ReadableStream?{serialized:e,contentType:`application/octet-stream`}:{serialized:JSON.stringify(e),contentType:`application/json`}}function B(e,t){return t?e.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,(e,n)=>{let r=t[n];if(r===void 0)throw Error(`Missing path parameter: :${n}`);return encodeURIComponent(String(r))}):e}var V=class n{requestInterceptors=[];responseInterceptors=[];cache;devTracker;config;requestQueue;pendingRequests=new Set;constructor(e={}){this.config={baseURL:e.baseURL??``,defaultHeaders:e.defaultHeaders??{"Content-Type":`application/json`},defaultTimeout:e.defaultTimeout??3e4,validateStatus:e.validateStatus??(e=>e>=200&&e<300),cacheStrategy:e.cacheStrategy??new I,maxConcurrent:e.maxConcurrent??0,defaultResponseType:e.defaultResponseType??`auto`,defaultHooks:e.defaultHooks??{},adapter:e.adapter},this.cache=this.config.cacheStrategy,this.requestQueue=this.config.maxConcurrent>0?new R(this.config.maxConcurrent):null,this.devTracker=e.devTracker??null}async request(n){if(!this.requestInterceptors.length&&!this.responseInterceptors.length&&!n.cache?.enabled&&!n.hooks&&!Object.keys(this.config.defaultHooks).length&&!n.retry&&!n.validate&&!n.transform&&!this.requestQueue&&!n.onDownloadProgress&&!n.signal)return this.fastPath(n);let r=n.hooks?{...this.config.defaultHooks,...n.hooks}:this.config.defaultHooks,i=this.getMaxAttempts(n.retry),a=this.getRetryStrategy(n.retry),o=this.buildRequest(n);r.onStart?.(o),this.requestQueue&&await this.requestQueue.acquire();try{for(let s=1;s<=i;s++){let c;try{if((n.method===`GET`||!n.method)&&n.cache?.enabled){let t=this.getCacheKey(n),i=this.cache.get(t);if(i){let t=i;return this.trackDev({method:n.method??`GET`,url:o.url,status:t.status,duration:t.duration,cached:!0,ok:!0,headers:{...o.headers},body:n.body,retryCount:0}),r.onSuccess?.(t),r.onFinally?.(),e(t)}}let t=o;for(let e of this.requestInterceptors)t=await e.onRequest(t);c=new AbortController,this.pendingRequests.add(c),n.signal&&n.signal.addEventListener(`abort`,()=>c.abort(),{once:!0});let i=performance.now(),a=await this.fetchWithTimeout(t,this.resolveTimeoutMs(n.timeout??this.config.defaultTimeout),c),l=performance.now()-i,u=a;n.onDownloadProgress&&a.body&&(u=this.trackDownloadProgress(a,n.onDownloadProgress));let d=n.responseType??this.config.defaultResponseType,f=await this.parseResponse(u,t,l,d);if(!this.config.validateStatus(f.status))throw{message:`Request failed with status ${f.status}`,status:f.status,statusText:f.statusText,code:`HTTP_ERROR`};if(n.validate){let e=n.validate.validate(f.data);if(!e.ok)return e}n.transform&&(f.data=n.transform.transform(f.data));let p=f;for(let e of this.responseInterceptors)p=await e.onResponse(p);if((n.method===`GET`||!n.method)&&n.cache?.enabled){let e=this.getCacheKey(n);this.cache.set(e,p,n.cache.ttlMs)}return r.onSuccess?.(p),this.pendingRequests.delete(c),this.trackDev({method:n.method??`GET`,url:o.url,status:p.status,duration:p.duration,cached:!1,ok:!0,headers:{...o.headers},body:n.body,retryCount:s-1}),e(p)}catch(e){let l;if(l=e instanceof DOMException?e.name===`TimeoutError`?{message:`Request timed out`,code:`TIMEOUT`}:e.name===`AbortError`?{message:`Request aborted`,code:`ABORTED`}:{message:e.message,code:`UNKNOWN_ERROR`,originalError:e}:this.isHttpErrorDetails(e)?e:this.normalizeError(e),s<i&&a.shouldRetry(s,l)){r.onRetry?.(s,l);let e=a.delayMs(s);await this.delay(e);continue}let u=l;for(let e of this.responseInterceptors)e.onError&&(u=await e.onError(u));return r.onError?.(u),c&&this.pendingRequests.delete(c),this.trackDev({method:n.method??`GET`,url:o.url,status:u.status,duration:0,cached:!1,ok:!1,code:u.code,headers:{...o.headers},body:n.body,retryCount:s-1}),t(u)}}let s={message:`Max retries exceeded`,code:`MAX_RETRIES`};return r.onError?.(s),this.trackDev({method:n.method??`GET`,url:o.url,duration:0,cached:!1,ok:!1,code:`MAX_RETRIES`,headers:{...o.headers},body:n.body,retryCount:i}),t(s)}finally{r.onFinally?.(),this.requestQueue&&this.requestQueue.release()}}async fastPath(n){let r=B(n.url,n.params),i=this.buildUrl(r,n.query),{serialized:a,contentType:o}=z(n.body),s={...this.config.defaultHeaders,...n.headers};o?s[`Content-Type`]=o:a instanceof FormData&&delete s[`Content-Type`];let c=new AbortController,l=this.resolveTimeoutMs(n.timeout??this.config.defaultTimeout);this.pendingRequests.add(c);try{let r=performance.now(),a=await this.fetchWithTimeout({url:i,method:n.method??`GET`,headers:s,body:n.body,params:n.params},l,c),o=performance.now()-r,u=await this.parseBody(a,n.responseType??this.config.defaultResponseType);if(!this.config.validateStatus(a.status)){let e=t({message:`Request failed with status ${a.status}`,status:a.status,statusText:a.statusText,code:`HTTP_ERROR`});return this.trackDev({method:n.method??`GET`,url:i,status:a.status,duration:o,cached:!1,ok:!1,code:`HTTP_ERROR`,headers:s,body:n.body,retryCount:0}),this.pendingRequests.delete(c),e}return this.pendingRequests.delete(c),this.trackDev({method:n.method??`GET`,url:i,status:a.status,duration:o,cached:!1,ok:!0,headers:s,body:n.body,retryCount:0}),e({status:a.status,statusText:a.statusText,headers:a.headers,data:u,request:{url:i,method:n.method??`GET`,headers:s,body:n.body,params:n.params},duration:o})}catch(e){this.pendingRequests.delete(c);let r=`UNKNOWN_ERROR`;if(e instanceof DOMException?e.name===`TimeoutError`?r=`TIMEOUT`:e.name===`AbortError`&&(r=`ABORTED`):e instanceof Error&&(e.name===`TimeoutError`?r=`TIMEOUT`:e.name===`AbortError`||e.message.includes(`abort`)?r=`ABORTED`:e.name===`TypeError`&&(r=`NETWORK_ERROR`)),this.trackDev({method:n.method??`GET`,url:i,duration:performance.now()-(performance.now()-0),cached:!1,ok:!1,code:r,headers:s,body:n.body,retryCount:0}),e instanceof DOMException){if(e.name===`TimeoutError`)return t({message:`Request timed out`,code:`TIMEOUT`});if(e.name===`AbortError`)return t({message:`Request aborted`,code:`ABORTED`})}return e instanceof Error?e.name===`TimeoutError`?t({message:`Request timed out`,code:`TIMEOUT`}):e.name===`AbortError`||e.message.includes(`abort`)?t({message:`Request aborted`,code:`ABORTED`}):t({message:e.message,code:e.name===`TypeError`?`NETWORK_ERROR`:`UNKNOWN_ERROR`}):t({message:String(e),code:`UNKNOWN_ERROR`})}}get(e,t){return this.request({...t,url:e,method:`GET`})}post(e,t,n){return this.request({...n,url:e,method:`POST`,body:t})}put(e,t,n){return this.request({...n,url:e,method:`PUT`,body:t})}patch(e,t,n){return this.request({...n,url:e,method:`PATCH`,body:t})}delete(e,t){return this.request({...t,url:e,method:`DELETE`})}head(e,t){return this.request({...t,url:e,method:`HEAD`})}options(e,t){return this.request({...t,url:e,method:`OPTIONS`})}addRequestInterceptor(e){return this.requestInterceptors.push(e),()=>{let t=this.requestInterceptors.indexOf(e);t!==-1&&this.requestInterceptors.splice(t,1)}}addResponseInterceptor(e){return this.responseInterceptors.push(e),()=>{let t=this.responseInterceptors.indexOf(e);t!==-1&&this.responseInterceptors.splice(t,1)}}clearInterceptors(){this.requestInterceptors=[],this.responseInterceptors=[]}clearCache(){this.cache.clear()}cancelAll(){for(let e of this.pendingRequests)e.abort();this.pendingRequests.clear()}get activeRequests(){return this.pendingRequests.size}get queueStats(){return{active:this.requestQueue?.active??this.pendingRequests.size,pending:this.requestQueue?.pending??0}}extend(e={}){let t=new n({baseURL:e.baseURL??this.config.baseURL,defaultHeaders:{...this.config.defaultHeaders,...e.defaultHeaders},defaultTimeout:e.defaultTimeout??this.config.defaultTimeout,validateStatus:e.validateStatus??this.config.validateStatus,cacheStrategy:e.cacheStrategy??this.cache,maxConcurrent:e.maxConcurrent??this.config.maxConcurrent,defaultResponseType:e.defaultResponseType??this.config.defaultResponseType,defaultHooks:{...this.config.defaultHooks,...e.defaultHooks},adapter:e.adapter});for(let e of this.requestInterceptors)t.addRequestInterceptor(e);for(let e of this.responseInterceptors)t.addResponseInterceptor(e);return t}async*paginate(e,t,n={}){let r={...n};for(;;){let n=await this.get(e,r);if(!n.ok)break;yield t.getItems(n.value.data);let i=t.getNextPage(n.value.data,r);if(!i)break;r=i}}async poll(e,n,r={}){let i=n.maxAttempts??0;for(let t=1;i===0||t<=i;t++){let a=await this.get(e,r);if(!a.ok||(n.onPoll?.(a.value.data,t),n.until(a.value.data)))return a;if(i>0&&t>=i)break;await this.delay(n.intervalMs)}return t({message:`Polling exhausted after ${i} attempts`,code:`POLL_EXHAUSTED`})}buildRequest(e){let t=B(e.url,e.params);return{url:this.buildUrl(t,e.query),method:e.method??`GET`,headers:{...this.config.defaultHeaders,...e.headers},body:e.body,params:e.params}}buildUrl(e,t){let n=this.config.baseURL+e;if(t){let e=Object.keys(t);if(e.length>0){let r=new URLSearchParams;for(let n=0;n<e.length;n++)r.append(e[n],String(t[e[n]]));n+=`?${r.toString()}`}}return n}getCacheKey(e){let t=B(e.url,e.params),n=e.query?JSON.stringify(e.query):``;return`${e.method??`GET`}:${t}${n?`:`+n:``}`}fetchWithTimeout(e,t,n){let{serialized:r,contentType:i}=z(e.body),a={...e.headers};return i?a[`Content-Type`]=i:r instanceof FormData&&delete a[`Content-Type`],new Promise((i,o)=>{let s=setTimeout(()=>{n.abort(),o(new DOMException(`Request timed out`,`TimeoutError`))},t);(this.config.adapter??fetch)(e.url,{method:e.method,headers:a,body:r,signal:n.signal}).then(e=>{clearTimeout(s),i(e)},e=>{clearTimeout(s),o(e)})})}trackDownloadProgress(e,t){let n=parseInt(e.headers.get(`content-length`)||`0`,10),r=e.body?.getReader();if(!r)return e;let i=0,a=new ReadableStream({async pull(e){let{done:a,value:o}=await r.read();if(a){e.close();return}i+=o.byteLength,t({loaded:i,total:n,percent:n>0?Math.round(i/n*100):0}),e.enqueue(o)}});return new Response(a,{headers:e.headers,status:e.status,statusText:e.statusText})}async parseResponse(e,t,n,r){let i=await this.parseBody(e,r);return{status:e.status,statusText:e.statusText,headers:e.headers,data:i,request:t,duration:n}}async parseBody(e,t){switch(t){case`json`:return await e.json();case`text`:return await e.text();case`blob`:return await e.blob();case`arrayBuffer`:return await e.arrayBuffer();case`formData`:return await e.formData();case`stream`:return e.body;default:{let t=e.headers.get(`content-type`)??``;if(t.includes(`application/json`))return await e.json();if(t.includes(`text/`))return await e.text();if(t.includes(`multipart/form-data`))return await e.formData();if(t.includes(`application/octet-stream`)||t.includes(`image/`)||t.includes(`audio/`)||t.includes(`video/`))return await e.blob();try{return await e.json()}catch{return await e.text()}}}}normalizeError(e){if(e instanceof DOMException){if(e.name===`TimeoutError`)return{message:`Request timed out`,code:`TIMEOUT`};if(e.name===`AbortError`)return{message:`Request aborted`,code:`ABORTED`}}return e instanceof Error?e.name===`TimeoutError`?{message:`Request timed out`,code:`TIMEOUT`}:e.name===`AbortError`||e.message.includes(`abort`)?{message:`Request aborted`,code:`ABORTED`}:{message:e.message,code:e.name===`TypeError`?`NETWORK_ERROR`:`UNKNOWN_ERROR`,originalError:e}:{message:String(e),code:`UNKNOWN_ERROR`,originalError:e}}isHttpErrorDetails(e){return typeof e==`object`&&!!e&&`message`in e&&`code`in e}getMaxAttempts(e){return e?`maxAttempts`in e?e.maxAttempts??1:100:1}getRetryStrategy(e){return e?`shouldRetry`in e?e:new L(e.maxAttempts,e.backoffMs):{shouldRetry:()=>!1,delayMs:()=>0}}resolveTimeoutMs(e){return typeof e==`number`?e:e.total??e.response??e.connection??3e4}delay(e){return new Promise(t=>setTimeout(t,e))}trackDev(e){this.devTracker&&this.devTracker.track(e)}},H=class extends Error{status;code;response;constructor(e,t,n,r){super(e),this.name=`HttpError`,this.status=t,this.code=n,this.response=r}};function U(e){return e instanceof H}function de(e){return new V(e)}function W(){return typeof window>`u`&&typeof process<`u`&&process.versions?.node!==void 0}var fe=class{url;options;pluginManager;status=`closed`;reconnectAttempt=0;reconnectTimer=null;heartbeatTimer=null;stats={messagesSent:0,messagesReceived:0,connectionTime:0,reconnectAttempts:0};connectionStartTime=0;listeners={open:new Set,close:new Set,error:new Set,message:new Set};constructor(e,t={}){this.url=e,this.options=t,this.pluginManager=new M}updateStatus(e){this.status=e,e===`open`?this.connectionStartTime=Date.now():e===`closed`&&this.connectionStartTime>0&&(this.stats.connectionTime+=Date.now()-this.connectionStartTime,this.connectionStartTime=0)}emitOpen(e){this.pluginManager.emit(`websocket:open`,this.url,e);for(let t of this.listeners.open)t(e)}emitClose(e){this.pluginManager.emit(`websocket:close`,this.url,e);for(let t of this.listeners.close)t(e)}emitError(e){let t;e instanceof Error?(t=new Event(`error`),t.error=e):t=e,this.pluginManager.emit(`websocket:error`,this.url,t);for(let e of this.listeners.error)e(t)}emitMessage(e){this.pluginManager.emit(`websocket:message`,this.url,e);for(let t of this.listeners.message)t(e)}onOpen(e){return this.listeners.open.add(e),()=>this.listeners.open.delete(e)}onClose(e){return this.listeners.close.add(e),()=>this.listeners.close.delete(e)}onError(e){return this.listeners.error.add(e),()=>this.listeners.error.delete(e)}onMessage(e){return this.listeners.message.add(e),()=>this.listeners.message.delete(e)}getStatus(){return this.status}getStats(){return{...this.stats,connectionTime:this.stats.connectionTime+(this.connectionStartTime>0?Date.now()-this.connectionStartTime:0)}}scheduleReconnect(){if(this.options.reconnect?.enabled===!1)return;let e=this.options.reconnect?.maxAttempts??1/0;if(this.reconnectAttempt>=e){this.pluginManager.emit(`websocket:reconnect:failed`,this.url,this.reconnectAttempt);return}let t=this.options.reconnect?.baseDelay??1e3,n=this.options.reconnect?.maxDelay??3e4,r=Math.min(n,t*2**this.reconnectAttempt);this.reconnectAttempt++,this.stats.reconnectAttempts=this.reconnectAttempt,this.options.reconnect?.onReconnecting?.(this.reconnectAttempt,r),this.pluginManager.emit(`websocket:reconnecting`,this.url,this.reconnectAttempt,r),this.reconnectTimer=setTimeout(()=>{this.connect().catch(e=>{this.emitError(e instanceof Error?e:Error(String(e)))})},r)}startHeartbeat(){if(!this.options.heartbeat)return;let e=this.options.heartbeat.interval??3e4,t=this.options.heartbeat.pingMessage??`ping`,n=this.options.heartbeat.pongMessage??`pong`,r=!0,i=()=>{if(!r){this.pluginManager.emit(`websocket:heartbeat:timeout`,this.url),this.disconnect();return}r=!1,this.send(t),this.heartbeatTimer=setTimeout(i,e)};this.onMessage(e=>{let t=e.raw;typeof t==`string`&&t===n&&(r=!0)}),this.heartbeatTimer=setTimeout(i,e)}stopHeartbeat(){this.heartbeatTimer&&=(clearTimeout(this.heartbeatTimer),null)}cleanup(){this.reconnectTimer&&=(clearTimeout(this.reconnectTimer),null),this.stopHeartbeat()}},G=class extends fe{socket=null;messageTypeListeners=new Map;constructor(e,t={}){super(e,t)}async connect(){if(!(this.status===`connecting`||this.status===`open`))return this.updateStatus(`connecting`),this.pluginManager.emit(`websocket:connect:start`,this.url),new Promise((e,t)=>{let n=this.options.timeout??1e4,r=setTimeout(()=>{this.updateStatus(`closed`),this.socket?.close(),this.socket=null;let e=Error(`WebSocket connection timeout after ${n}ms`);this.emitError(e),t(e)},n);try{this.socket=new WebSocket(this.url,this.options.protocols),this.socket.onopen=t=>{clearTimeout(r),this.updateStatus(`open`),this.reconnectAttempt=0,this.emitOpen(t),this.options.onOpen?.(t),this.startHeartbeat(),this.pluginManager.emit(`websocket:connect:success`,this.url),e()},this.socket.onclose=e=>{clearTimeout(r),this.updateStatus(`closed`),this.emitClose(e),this.options.onClose?.(e),this.stopHeartbeat(),this.pluginManager.emit(`websocket:disconnected`,this.url,e.code,e.reason),e.code!==1e3&&!e.wasClean&&this.scheduleReconnect()},this.socket.onerror=e=>{clearTimeout(r),this.updateStatus(`closed`),this.emitError(e),this.options.onError?.(e),this.pluginManager.emit(`websocket:connect:error`,this.url,e),t(e)},this.socket.onmessage=e=>{this.stats.messagesReceived++;let t={data:this.tryParseData(e.data),raw:e.data,type:`message`,timestamp:Date.now()};this.emitMessage(t),this.pluginManager.emit(`websocket:message:received`,this.url,t)}}catch(e){clearTimeout(r),this.updateStatus(`closed`),this.pluginManager.emit(`websocket:connect:error`,this.url,e),t(e)}})}disconnect(){this.cleanup(),this.socket&&(this.updateStatus(`closing`),this.socket.close(1e3,`Client disconnected`),this.socket=null,this.updateStatus(`closed`))}send(e){if(!this.socket||this.socket.readyState!==WebSocket.OPEN)throw Error(`WebSocket is not connected`);this.socket.send(e),this.stats.messagesSent++,this.pluginManager.emit(`websocket:message:sent`,this.url,e)}sendJson(e){this.send(JSON.stringify(e))}onMessageType(e,t){return this.messageTypeListeners.has(e)||this.messageTypeListeners.set(e,new Set),this.messageTypeListeners.get(e).add(t),()=>{let n=this.messageTypeListeners.get(e);n&&(n.delete(t),n.size===0&&this.messageTypeListeners.delete(e))}}tryParseData(e){if(typeof e==`string`)try{return JSON.parse(e)}catch{return e}return e}},pe=class extends G{async connect(){if(W())try{let{default:e}=await import(`ws`);return super.connect()}catch{throw Error(`WebSocket client for Node.js requires the "ws" package. Please install it: npm install ws`)}return super.connect()}};function me(e,t={}){return W()?new pe(e,t):new G(e,t)}function K(){return typeof window>`u`&&typeof process<`u`&&process.versions?.node!==void 0}var q=class{url;options;_source=null;pluginManager;status=`closed`;reconnectAttempt=0;reconnectTimer=null;stats={messagesSent:0,messagesReceived:0,connectionTime:0,reconnectAttempts:0};connectionStartTime=0;listeners={open:new Set,close:new Set,error:new Set,message:new Set,event:new Map};_lastEventId=null;constructor(e,t={}){this.url=e,this.options=t,this.pluginManager=new M}updateStatus(e){this.status=e,e===`open`?this.connectionStartTime=Date.now():e===`closed`&&this.connectionStartTime>0&&(this.stats.connectionTime+=Date.now()-this.connectionStartTime,this.connectionStartTime=0)}async connect(){if(!(this.status===`connecting`||this.status===`open`))return this.updateStatus(`connecting`),this.pluginManager.emit(`sse:connect:start`,this.url),new Promise((e,t)=>{let n=this.options.timeout??1e4,r=setTimeout(()=>{this.updateStatus(`closed`),this._source?.close(),this._source=null;let e=Error(`SSE connection timeout after ${n}ms`);this.emitError(e),t(e)},n);try{this._source=new EventSource(this.url),this._source.onopen=t=>{clearTimeout(r),this.updateStatus(`open`),this.reconnectAttempt=0,this.emitOpen(t),this.options.onOpen?.(t),this.pluginManager.emit(`sse:connect:success`,this.url),e()},this._source.onerror=e=>{clearTimeout(r),this.updateStatus(`closed`),this.emitError(e),this.options.onError?.(e),this.pluginManager.emit(`sse:connect:error`,this.url,e),this._source?.readyState===EventSource.CLOSED&&(this.emitClose(),this.options.onClose?.(),this.scheduleReconnect()),t(e)},this._source.onmessage=e=>{this.stats.messagesReceived++,this._lastEventId=e.lastEventId||this._lastEventId;let t={data:this.tryParseData(e.data),raw:e.data,type:e.type||`message`,timestamp:Date.now()};this.emitMessage(t),this.pluginManager.emit(`sse:message:received`,this.url,t);let n=e.type||`message`,r=this.listeners.event.get(n);if(r)for(let e of r)e(t.data)},this._source.addEventListener=this._source.addEventListener.bind(this._source)}catch(e){clearTimeout(r),this.updateStatus(`closed`),this.pluginManager.emit(`sse:connect:error`,this.url,e),t(e)}})}disconnect(){this.cleanup(),this._source&&(this.updateStatus(`closing`),this._source.close(),this._source=null,this.updateStatus(`closed`),this.emitClose(),this.options.onClose?.())}send(e){throw Error(`SSE is a receive-only protocol. Use HTTP requests to send data to server.`)}onMessage(e){return this.listeners.message.add(e),()=>this.listeners.message.delete(e)}onOpen(e){return this.listeners.open.add(e),()=>this.listeners.open.delete(e)}onClose(e){return this.listeners.close.add(e),()=>this.listeners.close.delete(e)}onError(e){return this.listeners.error.add(e),()=>this.listeners.error.delete(e)}onEvent(e,t){return this.listeners.event.has(e)||this.listeners.event.set(e,new Set),this.listeners.event.get(e).add(t),this._source&&!this._source[`on${e}`]&&this._source.addEventListener(e,n=>{t({data:this.tryParseData(n.data),raw:n.data,type:e,timestamp:Date.now()}.data)}),()=>{let n=this.listeners.event.get(e);n&&(n.delete(t),n.size===0&&this.listeners.event.delete(e))}}getStatus(){return this.status}getStats(){return{...this.stats,connectionTime:this.stats.connectionTime+(this.connectionStartTime>0?Date.now()-this.connectionStartTime:0)}}get lastEventId(){return this._lastEventId}get source(){return this._source}emitOpen(e){this.pluginManager.emit(`sse:open`,this.url,e);for(let t of this.listeners.open)t(e)}emitClose(){this.pluginManager.emit(`sse:close`,this.url);for(let e of this.listeners.close)e()}emitError(e){let t;e instanceof Error?(t=new Event(`error`),t.error=e):t=e,this.pluginManager.emit(`sse:error`,this.url,t);for(let e of this.listeners.error)e(t)}emitMessage(e){this.pluginManager.emit(`sse:message`,this.url,e);for(let t of this.listeners.message)t(e)}scheduleReconnect(){if(this.options.reconnect?.enabled===!1)return;let e=this.options.reconnect?.maxAttempts??1/0;if(this.reconnectAttempt>=e){this.pluginManager.emit(`sse:reconnect:failed`,this.url,this.reconnectAttempt);return}let t=this.options.reconnect?.baseDelay??1e3,n=this.options.reconnect?.maxDelay??3e4,r=Math.min(n,t*2**this.reconnectAttempt);this.reconnectAttempt++,this.stats.reconnectAttempts=this.reconnectAttempt,this.options.reconnect?.onReconnecting?.(this.reconnectAttempt,r),this.pluginManager.emit(`sse:reconnecting`,this.url,this.reconnectAttempt,r),this.reconnectTimer=setTimeout(()=>{this.connect().catch(e=>{this.emitError(e instanceof Error?e:Error(String(e)))})},r)}cleanup(){this.reconnectTimer&&=(clearTimeout(this.reconnectTimer),null)}tryParseData(e){try{return JSON.parse(e)}catch{return e}}},he=class extends q{async connect(){if(K())throw Error(`SSE client for Node.js requires a polyfill or custom implementation. Consider using a library like "eventsource" or implement using fetch with streaming.`);return super.connect()}};function ge(e,t={}){return K()?new he(e,t):new q(e,t)}var _e=class{name=`realtime`;setup(e){e.on(`websocket:connect:start`,(...t)=>{let n=t[0];e.emit(`realtime:connect:start`,`websocket`,n)}),e.on(`websocket:connect:success`,(...t)=>{let n=t[0];e.emit(`realtime:connect:success`,`websocket`,n)}),e.on(`websocket:message:received`,(...t)=>{let n=t[0],r=t[1];e.emit(`realtime:message`,`websocket`,n,r)}),e.on(`sse:connect:start`,(...t)=>{let n=t[0];e.emit(`realtime:connect:start`,`sse`,n)}),e.on(`sse:connect:success`,(...t)=>{let n=t[0];e.emit(`realtime:connect:success`,`sse`,n)}),e.on(`sse:message:received`,(...t)=>{let n=t[0],r=t[1];e.emit(`realtime:message`,`sse`,n,r)})}};function ve(){return new _e}var J=class{history=[];maxHistory;listeners=new Set;startTime=Date.now();config;constructor(e={}){this.maxHistory=e.maxHistory??500,this.config={enabled:e.enabled??!0,maxHistory:this.maxHistory,keyboardShortcut:e.keyboardShortcut??`ctrl+shift+n`,position:e.position??`bottom-right`,theme:e.theme??`dark`}}track(e){let t={...e,id:this.generateId(),timestamp:Date.now()};this.history.unshift(t),this.history.length>this.maxHistory&&this.history.pop();for(let e of this.listeners)e(t);return t}getHistory(){return this.history}getMetrics(){let e=this.history.map(e=>e.duration),t=(Date.now()-this.startTime)/1e3;return{totalRequests:this.history.length,successfulRequests:this.history.filter(e=>e.ok).length,failedRequests:this.history.filter(e=>!e.ok).length,cachedRequests:this.history.filter(e=>e.cached).length,avgDuration:e.length?e.reduce((e,t)=>e+t,0)/e.length:0,maxDuration:e.length?Math.max(...e):0,minDuration:e.length?Math.min(...e):0,requestsPerSecond:t>0?this.history.length/t:0,slowestRequests:[...this.history].sort((e,t)=>t.duration-e.duration).slice(0,5)}}clear(){this.history=[],this.startTime=Date.now()}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}getConfig(){return this.config}generateId(){return`${Date.now()}-${Math.random().toString(36).slice(2,8)}`}},Y={close:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6L6 18M6 6l12 12"/></svg>`,chevron:`<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 18l6-6-6-6"/></svg>`,back:`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 12H5M12 19l-7-7 7-7"/></svg>`,retry:`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 4v6h6M23 20v-6h-6"/><path d="M20.49 9A9 9 0 005.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 013.51 15"/></svg>`,clear:`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2"/></svg>`,search:`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><path d="M21 21l-4.35-4.35"/></svg>`,clock:`<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg>`,zap:`<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>`},X={bg:`#09090b`,bgElevated:`#18181b`,border:`#27272a`,borderFocus:`#3f3f46`,text:`#fafafa`,textMuted:`#a1a1aa`,textDim:`#71717a`,accent:`#3b82f6`,accentHover:`#2563eb`,success:`#22c55e`,successBg:`rgba(34, 197, 94, 0.1)`,error:`#ef4444`,errorBg:`rgba(239, 68, 68, 0.1)`,warning:`#f59e0b`,get:`#22c55e`,post:`#3b82f6`,put:`#f59e0b`,patch:`#a855f7`,delete:`#ef4444`},Z=`
|
|
2
|
+
#nexa-dev-overlay * { margin: 0; padding: 0; box-sizing: border-box; }
|
|
3
|
+
#nexa-dev-overlay {
|
|
4
|
+
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
|
5
|
+
background: ${X.bg};
|
|
6
|
+
color: ${X.text};
|
|
7
|
+
border: 1px solid ${X.border};
|
|
8
|
+
border-radius: 16px;
|
|
9
|
+
box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5), 0 0 0 1px rgba(255,255,255,0.03);
|
|
10
|
+
overflow: hidden;
|
|
11
|
+
}
|
|
12
|
+
#nexa-dev-overlay .nexa-header {
|
|
13
|
+
display: flex;
|
|
14
|
+
align-items: center;
|
|
15
|
+
justify-content: space-between;
|
|
16
|
+
padding: 16px 20px;
|
|
17
|
+
border-bottom: 1px solid ${X.border};
|
|
18
|
+
background: ${X.bgElevated};
|
|
19
|
+
}
|
|
20
|
+
#nexa-dev-overlay .nexa-header-left {
|
|
21
|
+
display: flex;
|
|
22
|
+
align-items: center;
|
|
23
|
+
gap: 12px;
|
|
24
|
+
}
|
|
25
|
+
#nexa-dev-overlay .nexa-logo {
|
|
26
|
+
width: 32px;
|
|
27
|
+
height: 32px;
|
|
28
|
+
display: flex;
|
|
29
|
+
align-items: center;
|
|
30
|
+
justify-content: center;
|
|
31
|
+
background: ${X.bgElevated};
|
|
32
|
+
border-radius: 8px;
|
|
33
|
+
overflow: hidden;
|
|
34
|
+
}
|
|
35
|
+
#nexa-dev-overlay .nexa-title {
|
|
36
|
+
font-size: 15px;
|
|
37
|
+
font-weight: 600;
|
|
38
|
+
letter-spacing: -0.02em;
|
|
39
|
+
}
|
|
40
|
+
#nexa-dev-overlay .nexa-header-actions {
|
|
41
|
+
display: flex;
|
|
42
|
+
gap: 4px;
|
|
43
|
+
}
|
|
44
|
+
#nexa-dev-overlay .nexa-icon-btn {
|
|
45
|
+
width: 32px;
|
|
46
|
+
height: 32px;
|
|
47
|
+
display: flex;
|
|
48
|
+
align-items: center;
|
|
49
|
+
justify-content: center;
|
|
50
|
+
background: transparent;
|
|
51
|
+
border: none;
|
|
52
|
+
border-radius: 8px;
|
|
53
|
+
color: ${X.textMuted};
|
|
54
|
+
cursor: pointer;
|
|
55
|
+
transition: all 0.15s;
|
|
56
|
+
}
|
|
57
|
+
#nexa-dev-overlay .nexa-icon-btn:hover {
|
|
58
|
+
background: ${X.border};
|
|
59
|
+
color: ${X.text};
|
|
60
|
+
}
|
|
61
|
+
#nexa-dev-overlay .nexa-metrics-bar {
|
|
62
|
+
display: flex;
|
|
63
|
+
gap: 4px;
|
|
64
|
+
padding: 12px 16px;
|
|
65
|
+
background: ${X.bg};
|
|
66
|
+
border-bottom: 1px solid ${X.border};
|
|
67
|
+
}
|
|
68
|
+
#nexa-dev-overlay .nexa-metric {
|
|
69
|
+
flex: 1;
|
|
70
|
+
display: flex;
|
|
71
|
+
flex-direction: column;
|
|
72
|
+
align-items: center;
|
|
73
|
+
gap: 2px;
|
|
74
|
+
padding: 8px 12px;
|
|
75
|
+
background: ${X.bgElevated};
|
|
76
|
+
border-radius: 10px;
|
|
77
|
+
transition: all 0.2s;
|
|
78
|
+
}
|
|
79
|
+
#nexa-dev-overlay .nexa-metric:hover {
|
|
80
|
+
background: ${X.border};
|
|
81
|
+
}
|
|
82
|
+
#nexa-dev-overlay .nexa-metric-value {
|
|
83
|
+
font-size: 18px;
|
|
84
|
+
font-weight: 700;
|
|
85
|
+
letter-spacing: -0.03em;
|
|
86
|
+
color: ${X.text};
|
|
87
|
+
}
|
|
88
|
+
#nexa-dev-overlay .nexa-metric-ok .nexa-metric-value { color: ${X.success}; }
|
|
89
|
+
#nexa-dev-overlay .nexa-metric-err .nexa-metric-value { color: ${X.error}; }
|
|
90
|
+
#nexa-dev-overlay .nexa-metric-label {
|
|
91
|
+
font-size: 11px;
|
|
92
|
+
color: ${X.textDim};
|
|
93
|
+
text-transform: uppercase;
|
|
94
|
+
letter-spacing: 0.05em;
|
|
95
|
+
}
|
|
96
|
+
#nexa-dev-overlay .nexa-search {
|
|
97
|
+
padding: 12px 16px;
|
|
98
|
+
border-bottom: 1px solid ${X.border};
|
|
99
|
+
position: relative;
|
|
100
|
+
}
|
|
101
|
+
#nexa-dev-overlay .nexa-search-icon {
|
|
102
|
+
position: absolute;
|
|
103
|
+
left: 28px;
|
|
104
|
+
top: 50%;
|
|
105
|
+
transform: translateY(-50%);
|
|
106
|
+
color: ${X.textDim};
|
|
107
|
+
}
|
|
108
|
+
#nexa-dev-overlay .nexa-search-input {
|
|
109
|
+
width: 100%;
|
|
110
|
+
padding: 10px 12px 10px 38px;
|
|
111
|
+
background: ${X.bg};
|
|
112
|
+
border: 1px solid ${X.border};
|
|
113
|
+
border-radius: 10px;
|
|
114
|
+
color: ${X.text};
|
|
115
|
+
font-size: 13px;
|
|
116
|
+
outline: none;
|
|
117
|
+
transition: all 0.15s;
|
|
118
|
+
}
|
|
119
|
+
#nexa-dev-overlay .nexa-search-input:focus {
|
|
120
|
+
border-color: ${X.accent};
|
|
121
|
+
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.15);
|
|
122
|
+
}
|
|
123
|
+
#nexa-dev-overlay .nexa-search-input::placeholder { color: ${X.textDim}; }
|
|
124
|
+
#nexa-dev-overlay .nexa-tabs {
|
|
125
|
+
display: flex;
|
|
126
|
+
gap: 4px;
|
|
127
|
+
padding: 8px 16px;
|
|
128
|
+
border-bottom: 1px solid ${X.border};
|
|
129
|
+
}
|
|
130
|
+
#nexa-dev-overlay .nexa-tab {
|
|
131
|
+
display: flex;
|
|
132
|
+
align-items: center;
|
|
133
|
+
gap: 8px;
|
|
134
|
+
padding: 8px 14px;
|
|
135
|
+
background: transparent;
|
|
136
|
+
border: none;
|
|
137
|
+
border-radius: 8px;
|
|
138
|
+
color: ${X.textMuted};
|
|
139
|
+
font-size: 13px;
|
|
140
|
+
font-weight: 500;
|
|
141
|
+
cursor: pointer;
|
|
142
|
+
transition: all 0.15s;
|
|
143
|
+
}
|
|
144
|
+
#nexa-dev-overlay .nexa-tab:hover { color: ${X.text}; background: ${X.bgElevated}; }
|
|
145
|
+
#nexa-dev-overlay .nexa-tab-active { color: ${X.text}; background: ${X.accent} !important; }
|
|
146
|
+
#nexa-dev-overlay .nexa-tab-count {
|
|
147
|
+
font-size: 11px;
|
|
148
|
+
padding: 2px 6px;
|
|
149
|
+
background: rgba(255,255,255,0.1);
|
|
150
|
+
border-radius: 10px;
|
|
151
|
+
}
|
|
152
|
+
#nexa-dev-overlay .nexa-body { flex: 1; overflow: hidden; display: flex; }
|
|
153
|
+
#nexa-dev-overlay .nexa-panel { display: none; width: 100%; overflow-y: auto; }
|
|
154
|
+
#nexa-dev-overlay .nexa-panel-active { display: block; }
|
|
155
|
+
#nexa-dev-overlay .nexa-request-list {
|
|
156
|
+
padding: 8px;
|
|
157
|
+
display: flex;
|
|
158
|
+
flex-direction: column;
|
|
159
|
+
gap: 4px;
|
|
160
|
+
}
|
|
161
|
+
#nexa-dev-overlay .nexa-request-item {
|
|
162
|
+
display: flex;
|
|
163
|
+
align-items: center;
|
|
164
|
+
justify-content: space-between;
|
|
165
|
+
padding: 12px 14px;
|
|
166
|
+
background: ${X.bgElevated};
|
|
167
|
+
border: 1px solid transparent;
|
|
168
|
+
border-radius: 12px;
|
|
169
|
+
cursor: pointer;
|
|
170
|
+
transition: all 0.15s;
|
|
171
|
+
animation: nexaFadeIn 0.2s ease forwards;
|
|
172
|
+
opacity: 0;
|
|
173
|
+
}
|
|
174
|
+
@keyframes nexaFadeIn { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: translateY(0); } }
|
|
175
|
+
#nexa-dev-overlay .nexa-request-item:hover {
|
|
176
|
+
background: ${X.border};
|
|
177
|
+
border-color: ${X.borderFocus};
|
|
178
|
+
transform: translateX(2px);
|
|
179
|
+
}
|
|
180
|
+
#nexa-dev-overlay .nexa-req-left {
|
|
181
|
+
display: flex;
|
|
182
|
+
align-items: center;
|
|
183
|
+
gap: 10px;
|
|
184
|
+
}
|
|
185
|
+
#nexa-dev-overlay .nexa-method {
|
|
186
|
+
font-size: 11px;
|
|
187
|
+
font-weight: 700;
|
|
188
|
+
padding: 4px 8px;
|
|
189
|
+
border-radius: 6px;
|
|
190
|
+
text-transform: uppercase;
|
|
191
|
+
letter-spacing: 0.03em;
|
|
192
|
+
}
|
|
193
|
+
#nexa-dev-overlay .nexa-method-get { background: ${X.successBg}; color: ${X.get}; }
|
|
194
|
+
#nexa-dev-overlay .nexa-method-post { background: rgba(59, 130, 246, 0.15); color: ${X.post}; }
|
|
195
|
+
#nexa-dev-overlay .nexa-method-put { background: rgba(245, 158, 11, 0.15); color: ${X.put}; }
|
|
196
|
+
#nexa-dev-overlay .nexa-method-patch { background: rgba(168, 85, 247, 0.15); color: ${X.patch}; }
|
|
197
|
+
#nexa-dev-overlay .nexa-method-delete { background: ${X.errorBg}; color: ${X.delete}; }
|
|
198
|
+
#nexa-dev-overlay .nexa-status {
|
|
199
|
+
font-size: 12px;
|
|
200
|
+
font-weight: 600;
|
|
201
|
+
padding: 4px 8px;
|
|
202
|
+
border-radius: 6px;
|
|
203
|
+
min-width: 36px;
|
|
204
|
+
text-align: center;
|
|
205
|
+
}
|
|
206
|
+
#nexa-dev-overlay .nexa-ok { background: ${X.successBg}; color: ${X.success}; }
|
|
207
|
+
#nexa-dev-overlay .nexa-err { background: ${X.errorBg}; color: ${X.error}; }
|
|
208
|
+
#nexa-dev-overlay .nexa-url {
|
|
209
|
+
font-size: 13px;
|
|
210
|
+
color: ${X.textMuted};
|
|
211
|
+
max-width: 180px;
|
|
212
|
+
overflow: hidden;
|
|
213
|
+
text-overflow: ellipsis;
|
|
214
|
+
white-space: nowrap;
|
|
215
|
+
}
|
|
216
|
+
#nexa-dev-overlay .nexa-req-right {
|
|
217
|
+
display: flex;
|
|
218
|
+
align-items: center;
|
|
219
|
+
gap: 8px;
|
|
220
|
+
}
|
|
221
|
+
#nexa-dev-overlay .nexa-badge {
|
|
222
|
+
font-size: 10px;
|
|
223
|
+
font-weight: 600;
|
|
224
|
+
padding: 3px 6px;
|
|
225
|
+
border-radius: 6px;
|
|
226
|
+
text-transform: uppercase;
|
|
227
|
+
letter-spacing: 0.03em;
|
|
228
|
+
}
|
|
229
|
+
#nexa-dev-overlay .nexa-badge-cache { background: rgba(168, 85, 247, 0.15); color: #a855f7; }
|
|
230
|
+
#nexa-dev-overlay .nexa-badge-retry { background: rgba(245, 158, 11, 0.15); color: ${X.warning}; }
|
|
231
|
+
#nexa-dev-overlay .nexa-duration {
|
|
232
|
+
font-size: 12px;
|
|
233
|
+
font-weight: 600;
|
|
234
|
+
color: ${X.textDim};
|
|
235
|
+
font-variant-numeric: tabular-nums;
|
|
236
|
+
}
|
|
237
|
+
#nexa-dev-overlay .nexa-slow { color: ${X.warning}; }
|
|
238
|
+
#nexa-dev-overlay .nexa-empty {
|
|
239
|
+
display: flex;
|
|
240
|
+
flex-direction: column;
|
|
241
|
+
align-items: center;
|
|
242
|
+
justify-content: center;
|
|
243
|
+
padding: 48px 24px;
|
|
244
|
+
text-align: center;
|
|
245
|
+
color: ${X.textDim};
|
|
246
|
+
}
|
|
247
|
+
#nexa-dev-overlay .nexa-empty svg { margin-bottom: 16px; opacity: 0.4; }
|
|
248
|
+
#nexa-dev-overlay .nexa-empty p { font-size: 14px; color: ${X.textMuted}; margin-bottom: 4px; }
|
|
249
|
+
#nexa-dev-overlay .nexa-empty span { font-size: 12px; color: ${X.textDim}; }
|
|
250
|
+
#nexa-dev-overlay .nexa-detail {
|
|
251
|
+
flex-direction: column;
|
|
252
|
+
padding: 16px;
|
|
253
|
+
display: none;
|
|
254
|
+
overflow-y: auto;
|
|
255
|
+
max-height: 100%;
|
|
256
|
+
}
|
|
257
|
+
#nexa-dev-overlay .nexa-detail-active { display: flex; }
|
|
258
|
+
#nexa-dev-overlay .nexa-detail-header {
|
|
259
|
+
display: flex;
|
|
260
|
+
align-items: center;
|
|
261
|
+
justify-content: space-between;
|
|
262
|
+
margin-bottom: 16px;
|
|
263
|
+
}
|
|
264
|
+
#nexa-dev-overlay .nexa-btn {
|
|
265
|
+
display: flex;
|
|
266
|
+
align-items: center;
|
|
267
|
+
gap: 6px;
|
|
268
|
+
padding: 8px 14px;
|
|
269
|
+
background: ${X.bgElevated};
|
|
270
|
+
border: 1px solid ${X.border};
|
|
271
|
+
border-radius: 8px;
|
|
272
|
+
color: ${X.textMuted};
|
|
273
|
+
font-size: 13px;
|
|
274
|
+
font-weight: 500;
|
|
275
|
+
cursor: pointer;
|
|
276
|
+
transition: all 0.15s;
|
|
277
|
+
}
|
|
278
|
+
#nexa-dev-overlay .nexa-btn:hover { background: ${X.border}; color: ${X.text}; }
|
|
279
|
+
#nexa-dev-overlay .nexa-btn-retry { background: ${X.successBg}; border-color: transparent; color: ${X.success}; }
|
|
280
|
+
#nexa-dev-overlay .nexa-btn-retry:hover { background: ${X.success}; color: white; }
|
|
281
|
+
#nexa-dev-overlay .nexa-card {
|
|
282
|
+
background: ${X.bgElevated};
|
|
283
|
+
border: 1px solid ${X.border};
|
|
284
|
+
border-radius: 12px;
|
|
285
|
+
padding: 16px;
|
|
286
|
+
margin-bottom: 12px;
|
|
287
|
+
}
|
|
288
|
+
#nexa-dev-overlay .nexa-card h3 {
|
|
289
|
+
font-size: 12px;
|
|
290
|
+
font-weight: 600;
|
|
291
|
+
color: ${X.textDim};
|
|
292
|
+
text-transform: uppercase;
|
|
293
|
+
letter-spacing: 0.05em;
|
|
294
|
+
margin-bottom: 12px;
|
|
295
|
+
}
|
|
296
|
+
#nexa-dev-overlay .nexa-row {
|
|
297
|
+
display: flex;
|
|
298
|
+
justify-content: space-between;
|
|
299
|
+
align-items: center;
|
|
300
|
+
padding: 6px 0;
|
|
301
|
+
font-size: 13px;
|
|
302
|
+
border-bottom: 1px solid ${X.border};
|
|
303
|
+
}
|
|
304
|
+
#nexa-dev-overlay .nexa-row:last-child { border-bottom: none; }
|
|
305
|
+
#nexa-dev-overlay .nexa-row span { color: ${X.textMuted}; }
|
|
306
|
+
#nexa-dev-overlay .nexa-row strong { color: ${X.text}; font-weight: 500; font-variant-numeric: tabular-nums; }
|
|
307
|
+
#nexa-dev-overlay .nexa-row .nexa-ok { color: ${X.success}; }
|
|
308
|
+
#nexa-dev-overlay .nexa-row .nexa-err { color: ${X.error}; }
|
|
309
|
+
#nexa-dev-overlay .nexa-code {
|
|
310
|
+
background: ${X.bg};
|
|
311
|
+
border-radius: 8px;
|
|
312
|
+
padding: 12px;
|
|
313
|
+
font-size: 11px;
|
|
314
|
+
font-family: 'JetBrains Mono', 'Fira Code', monospace;
|
|
315
|
+
color: ${X.textMuted};
|
|
316
|
+
overflow-x: auto;
|
|
317
|
+
white-space: pre;
|
|
318
|
+
max-height: 200px;
|
|
319
|
+
line-height: 1.6;
|
|
320
|
+
}
|
|
321
|
+
#nexa-dev-overlay .nexa-url-full {
|
|
322
|
+
font-size: 12px;
|
|
323
|
+
word-break: break-all;
|
|
324
|
+
color: ${X.accent};
|
|
325
|
+
}
|
|
326
|
+
#nexa-dev-overlay .nexa-metrics-content {
|
|
327
|
+
padding: 16px;
|
|
328
|
+
display: flex;
|
|
329
|
+
flex-direction: column;
|
|
330
|
+
gap: 12px;
|
|
331
|
+
}
|
|
332
|
+
#nexa-dev-overlay .nexa-slow-req {
|
|
333
|
+
display: flex;
|
|
334
|
+
align-items: center;
|
|
335
|
+
gap: 8px;
|
|
336
|
+
}
|
|
337
|
+
`,ye=class{panel=null;tracker;visible=!1;selectedRequest=null;config;searchQuery=``;constructor(e){this.tracker=e,this.config=e.getConfig(),this.setupKeyboardShortcut(),this.createPanel()}show(){this.panel&&(this.panel.style.display=`flex`,this.panel.style.opacity=`0`,this.panel.style.transform=`scale(0.96) translateY(8px)`,requestAnimationFrame(()=>{this.panel.style.transition=`all 0.25s cubic-bezier(0.16, 1, 0.3, 1)`,this.panel.style.opacity=`1`,this.panel.style.transform=`scale(1) translateY(0)`}),this.visible=!0)}hide(){this.panel&&(this.panel.style.transition=`all 0.15s ease-out`,this.panel.style.opacity=`0`,this.panel.style.transform=`scale(0.96) translateY(8px)`,setTimeout(()=>{this.panel&&(this.panel.style.display=`none`)},150),this.visible=!1)}toggle(){this.visible?this.hide():this.show()}destroy(){this.panel?.remove(),this.panel=null}setupKeyboardShortcut(){let e=this.config.keyboardShortcut.split(`+`),t=new Set(e.map(e=>e.toLowerCase()));document.addEventListener(`keydown`,e=>{let n=new Set;e.ctrlKey&&n.add(`ctrl`),e.metaKey&&(n.add(`meta`),n.add(`cmd`),n.add(`ctrl`)),e.shiftKey&&n.add(`shift`),e.altKey&&n.add(`alt`),(e.key&&e.key.length===1||e.key.length>1)&&n.add(e.key.toLowerCase());let r=!0;for(let e of t)if(!n.has(e)){r=!1;break}r&&n.size===t.size&&(e.preventDefault(),this.toggle())})}createPanel(){this.panel=document.createElement(`div`),this.panel.id=`nexa-dev-overlay`;let e=this.config.position,t=e.includes(`bottom`),n=e.includes(`right`);this.panel.style.cssText=`
|
|
338
|
+
position: fixed;
|
|
339
|
+
${t?`bottom: 24px;`:`top: 24px;`}
|
|
340
|
+
${n?`right: 24px;`:`left: 24px;`}
|
|
341
|
+
width: 420px;
|
|
342
|
+
max-height: 70vh;
|
|
343
|
+
z-index: 2147483647;
|
|
344
|
+
display: flex;
|
|
345
|
+
flex-direction: column;
|
|
346
|
+
overflow: hidden;
|
|
347
|
+
`,this.panel.innerHTML=`<style>${Z}</style>
|
|
348
|
+
|
|
349
|
+
<div class="nexa-header">
|
|
350
|
+
<div class="nexa-header-left">
|
|
351
|
+
<div class="nexa-logo">
|
|
352
|
+
<img src="/src/assets/faviconNew.png" width="18" height="18" style="border-radius:4px;object-fit:contain;display:block;" alt="Nexa" onerror="this.style.display='none';this.nextElementSibling.style.display='flex';" />
|
|
353
|
+
<span style="display:none;align-items:center;justify-content:center;font-size:14px;font-weight:700;color:#fff;background:linear-gradient(135deg,#3b82f6,#238636);width:18px;height:18px;border-radius:4px;">N</span>
|
|
354
|
+
</div>
|
|
355
|
+
<span class="nexa-title">Nexa DevTools</span>
|
|
356
|
+
</div>
|
|
357
|
+
<div class="nexa-header-actions">
|
|
358
|
+
<button class="nexa-icon-btn nexa-btn-clear" title="Clear history">${Y.clear}</button>
|
|
359
|
+
<button class="nexa-icon-btn nexa-btn-close" title="Close (Esc)">${Y.close}</button>
|
|
360
|
+
</div>
|
|
361
|
+
</div>
|
|
362
|
+
|
|
363
|
+
<div class="nexa-metrics-bar">
|
|
364
|
+
<div class="nexa-metric"><span class="nexa-metric-value" data-metric="total">0</span><span class="nexa-metric-label">Requests</span></div>
|
|
365
|
+
<div class="nexa-metric"><span class="nexa-metric-value" data-metric="avg">0ms</span><span class="nexa-metric-label">Avg</span></div>
|
|
366
|
+
<div class="nexa-metric"><span class="nexa-metric-value" data-metric="rate">0/s</span><span class="nexa-metric-label">Throughput</span></div>
|
|
367
|
+
<div class="nexa-metric nexa-metric-ok"><span class="nexa-metric-value" data-metric="success">0</span><span class="nexa-metric-label">Success</span></div>
|
|
368
|
+
<div class="nexa-metric nexa-metric-err"><span class="nexa-metric-value" data-metric="fail">0</span><span class="nexa-metric-label">Failed</span></div>
|
|
369
|
+
</div>
|
|
370
|
+
|
|
371
|
+
<div class="nexa-search">
|
|
372
|
+
<span class="nexa-search-icon">${Y.search}</span>
|
|
373
|
+
<input type="text" class="nexa-search-input" placeholder="Filter by URL, method, or status..." />
|
|
374
|
+
</div>
|
|
375
|
+
|
|
376
|
+
<div class="nexa-tabs">
|
|
377
|
+
<button class="nexa-tab nexa-tab-active" data-tab="requests"><span>Requests</span><span class="nexa-tab-count" data-count="requests">0</span></button>
|
|
378
|
+
<button class="nexa-tab" data-tab="metrics"><span>Metrics</span></button>
|
|
379
|
+
</div>
|
|
380
|
+
|
|
381
|
+
<div class="nexa-body">
|
|
382
|
+
<div class="nexa-panel nexa-panel-active" data-panel="requests"><div class="nexa-request-list"></div></div>
|
|
383
|
+
<div class="nexa-panel" data-panel="metrics"><div class="nexa-metrics-content"></div></div>
|
|
384
|
+
</div>
|
|
385
|
+
|
|
386
|
+
<div class="nexa-detail" style="display:none">
|
|
387
|
+
<div class="nexa-detail-header">
|
|
388
|
+
<button class="nexa-btn nexa-btn-back">${Y.back} Back</button>
|
|
389
|
+
<button class="nexa-btn nexa-btn-retry">${Y.retry} Retry</button>
|
|
390
|
+
</div>
|
|
391
|
+
<div class="nexa-detail-body"></div>
|
|
392
|
+
</div>
|
|
393
|
+
`,document.body.appendChild(this.panel),this.bindEvents(),this.tracker.onChange(()=>this.render()),this.hide(),document.addEventListener(`keydown`,e=>{if(e.key===`Escape`&&this.visible){this.hide();return}if(this.visible&&(e.ctrlKey||e.metaKey)&&e.key.toLowerCase()===`f`){e.preventDefault();let t=this.panel?.querySelector(`.nexa-search-input`);t?.focus(),t?.select()}})}bindEvents(){this.panel&&(this.panel.querySelector(`.nexa-btn-close`)?.addEventListener(`click`,()=>this.hide()),this.panel.querySelector(`.nexa-btn-clear`)?.addEventListener(`click`,()=>{this.tracker.clear(),this.render()}),this.panel.querySelector(`.nexa-btn-back`)?.addEventListener(`click`,()=>this.showMainView()),this.panel.querySelector(`.nexa-btn-retry`)?.addEventListener(`click`,()=>this.retrySelected()),this.panel.querySelector(`.nexa-search-input`)?.addEventListener(`input`,e=>{this.searchQuery=e.target.value.toLowerCase(),this.renderRequestList()}),this.panel.querySelectorAll(`.nexa-tab`).forEach(e=>{e.addEventListener(`click`,()=>{this.panel.querySelectorAll(`.nexa-tab`).forEach(e=>e.classList.remove(`nexa-tab-active`)),this.panel.querySelectorAll(`.nexa-panel`).forEach(e=>e.classList.remove(`nexa-panel-active`)),e.classList.add(`nexa-tab-active`),this.panel.querySelector(`[data-panel="${e.dataset.tab}"]`)?.classList.add(`nexa-panel-active`),e.dataset.tab===`metrics`&&this.renderMetrics()})}))}render(){!this.panel||!this.visible||(this.renderMetricsBar(),this.renderRequestList())}renderMetricsBar(){let e=this.tracker.getMetrics(),t=this.panel;t&&(t.querySelector(`[data-metric="total"]`).textContent=String(e.totalRequests),t.querySelector(`[data-metric="avg"]`).textContent=`${e.avgDuration.toFixed(0)}ms`,t.querySelector(`[data-metric="rate"]`).textContent=`${e.requestsPerSecond.toFixed(1)}`,t.querySelector(`[data-metric="success"]`).textContent=String(e.successfulRequests),t.querySelector(`[data-metric="fail"]`).textContent=String(e.failedRequests),t.querySelector(`[data-count="requests"]`).textContent=String(e.totalRequests))}renderRequestList(){let e=this.panel?.querySelector(`.nexa-request-list`);if(!e)return;let t=this.tracker.getHistory();if(this.searchQuery&&(t=t.filter(e=>e.url.toLowerCase().includes(this.searchQuery)||e.method.toLowerCase().includes(this.searchQuery)||String(e.status).includes(this.searchQuery))),t.length===0){e.innerHTML=`
|
|
394
|
+
<div class="nexa-empty">
|
|
395
|
+
<svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
|
|
396
|
+
<circle cx="12" cy="12" r="10"/><path d="M8 12h8M12 8v8"/>
|
|
397
|
+
</svg>
|
|
398
|
+
<p>${this.searchQuery?`No matching requests`:`No requests yet`}</p>
|
|
399
|
+
<span>${this.searchQuery?`Try a different search term`:`Make a request to see it here`}</span>
|
|
400
|
+
</div>`;return}e.innerHTML=t.map((e,t)=>`
|
|
401
|
+
<div class="nexa-request-item" data-id="${e.id}" style="animation-delay: ${Math.min(t*20,300)}ms">
|
|
402
|
+
<div class="nexa-req-left">
|
|
403
|
+
<span class="nexa-method nexa-method-${e.method.toLowerCase()}">${e.method}</span>
|
|
404
|
+
<span class="nexa-status ${e.ok?`nexa-ok`:`nexa-err`}">${e.status||`ERR`}</span>
|
|
405
|
+
<span class="nexa-url" title="${e.url}">${this.truncateUrl(e.url)}</span>
|
|
406
|
+
</div>
|
|
407
|
+
<div class="nexa-req-right">
|
|
408
|
+
${e.cached?`<span class="nexa-badge nexa-badge-cache">Cache</span>`:``}
|
|
409
|
+
${e.retryCount>0?`<span class="nexa-badge nexa-badge-retry">${e.retryCount}R</span>`:``}
|
|
410
|
+
<span class="nexa-duration ${e.duration>500?`nexa-slow`:``}">${e.duration.toFixed(0)}ms</span>
|
|
411
|
+
${Y.chevron}
|
|
412
|
+
</div>
|
|
413
|
+
</div>
|
|
414
|
+
`).join(``),e.querySelectorAll(`.nexa-request-item`).forEach(e=>{e.addEventListener(`click`,()=>{let n=e.dataset.id,r=t.find(e=>e.id===n);r&&this.showDetail(r)})})}renderMetrics(){let e=this.tracker.getMetrics(),t=this.panel?.querySelector(`.nexa-metrics-content`);if(!t)return;let n=e.totalRequests>0?(e.successfulRequests/e.totalRequests*100).toFixed(1):`0`;t.innerHTML=`
|
|
415
|
+
<div class="nexa-card">
|
|
416
|
+
<h3>Overview</h3>
|
|
417
|
+
<div class="nexa-row"><span>Total Requests</span><strong>${e.totalRequests}</strong></div>
|
|
418
|
+
<div class="nexa-row"><span>Successful</span><strong class="nexa-ok">${e.successfulRequests}</strong></div>
|
|
419
|
+
<div class="nexa-row"><span>Failed</span><strong class="nexa-err">${e.failedRequests}</strong></div>
|
|
420
|
+
<div class="nexa-row"><span>Cached</span><strong>${e.cachedRequests}</strong></div>
|
|
421
|
+
<div class="nexa-row"><span>Success Rate</span><strong>${n}%</strong></div>
|
|
422
|
+
</div>
|
|
423
|
+
<div class="nexa-card">
|
|
424
|
+
<h3>Performance</h3>
|
|
425
|
+
<div class="nexa-row"><span>Average</span><strong>${e.avgDuration.toFixed(1)}ms</strong></div>
|
|
426
|
+
<div class="nexa-row"><span>Fastest</span><strong class="nexa-ok">${e.minDuration.toFixed(1)}ms</strong></div>
|
|
427
|
+
<div class="nexa-row"><span>Slowest</span><strong class="nexa-err">${e.maxDuration.toFixed(1)}ms</strong></div>
|
|
428
|
+
<div class="nexa-row"><span>Throughput</span><strong>${e.requestsPerSecond.toFixed(2)} req/s</strong></div>
|
|
429
|
+
</div>
|
|
430
|
+
${e.slowestRequests.length>0?`
|
|
431
|
+
<div class="nexa-card">
|
|
432
|
+
<h3>Slowest Requests</h3>
|
|
433
|
+
${e.slowestRequests.map(e=>`
|
|
434
|
+
<div class="nexa-row nexa-slow-req">
|
|
435
|
+
<span><span class="nexa-method nexa-method-${e.method.toLowerCase()}" style="font-size:10px;padding:2px 5px;">${e.method}</span> ${this.truncateUrl(e.url,25)}</span>
|
|
436
|
+
<strong class="nexa-err">${e.duration.toFixed(0)}ms</strong>
|
|
437
|
+
</div>
|
|
438
|
+
`).join(``)}
|
|
439
|
+
</div>
|
|
440
|
+
`:``}`}showDetail(e){this.selectedRequest=e;let t=this.panel?.querySelector(`.nexa-body`),n=this.panel?.querySelector(`.nexa-detail`),r=this.panel?.querySelector(`.nexa-detail-body`);!t||!n||!r||(t.style.display=`none`,n.style.display=`flex`,r.innerHTML=`
|
|
441
|
+
<div class="nexa-card">
|
|
442
|
+
<h3>Request</h3>
|
|
443
|
+
<div class="nexa-row"><span>Method</span><strong style="color:${e.method===`GET`?X.get:e.method===`POST`?X.post:e.method===`DELETE`?X.delete:X.warning}">${e.method}</strong></div>
|
|
444
|
+
<div class="nexa-row"><span>URL</span><span class="nexa-url-full">${e.url}</span></div>
|
|
445
|
+
<div class="nexa-row"><span>Status</span><strong class="${e.ok?`nexa-ok`:`nexa-err`}">${e.status||`N/A`}</strong></div>
|
|
446
|
+
<div class="nexa-row"><span>Duration</span><strong>${e.duration.toFixed(1)}ms</strong></div>
|
|
447
|
+
<div class="nexa-row"><span>Cached</span><strong>${e.cached?`Yes`:`No`}</strong></div>
|
|
448
|
+
<div class="nexa-row"><span>Retries</span><strong>${e.retryCount}</strong></div>
|
|
449
|
+
<div class="nexa-row"><span>Timestamp</span><strong>${new Date(e.timestamp).toLocaleTimeString()}</strong></div>
|
|
450
|
+
</div>
|
|
451
|
+
${e.body===void 0?``:`
|
|
452
|
+
<div class="nexa-card">
|
|
453
|
+
<h3>Request Body</h3>
|
|
454
|
+
<pre class="nexa-code">${this.formatJson(e.body)}</pre>
|
|
455
|
+
</div>
|
|
456
|
+
`}
|
|
457
|
+
${Object.keys(e.headers).length>0?`
|
|
458
|
+
<div class="nexa-card">
|
|
459
|
+
<h3>Headers</h3>
|
|
460
|
+
<pre class="nexa-code">${this.formatJson(e.headers)}</pre>
|
|
461
|
+
</div>
|
|
462
|
+
`:``}`)}showMainView(){let e=this.panel?.querySelector(`.nexa-body`),t=this.panel?.querySelector(`.nexa-detail`);e&&(e.style.display=`flex`),t&&(t.style.display=`none`),this.selectedRequest=null}retrySelected(){if(!this.selectedRequest)return;let{method:e,url:t,body:n,headers:r}=this.selectedRequest;fetch(t,{method:e,headers:r,body:n?JSON.stringify(n):void 0}).then(async e=>{this.selectedRequest&&(this.selectedRequest={...this.selectedRequest,status:e.status,ok:e.ok,duration:this.selectedRequest.duration,timestamp:Date.now()},this.showDetail(this.selectedRequest))}).catch(()=>{})}truncateUrl(e,t=35){try{let t=new URL(e);return t.pathname+(t.search||``)}catch{return e.length>t?e.slice(0,t)+`...`:e}}formatJson(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}},Q=null,$=null;function be(e={}){return Q?{tracker:$,ui:Q}:($=new J(e),Q=new ye($),Q.show(),{tracker:$,ui:Q})}function xe(){return{tracker:$,ui:Q}}function Se(){Q?.destroy(),Q=null,$=null}exports.AggressiveRetry=d,exports.CachePlugin=P,exports.CacheStore=v,exports.CircuitBreakerRetry=p,exports.ConservativeRetry=f,exports.DedupePlugin=F,exports.Defer=se,exports.Err=t,exports.HttpClient=V,exports.HttpError=H,exports.LoggerPlugin=ue,exports.MetricsPlugin=N,exports.MiddlewarePipeline=ie,exports.Ok=e,exports.PluginManager=M,exports.RequestDeduplicator=x,exports.RequestTracker=J,exports.TypedObservable=D,exports.cacheMiddleware=b,exports.createApiUrl=oe,exports.createCacheMiddleware=y,exports.createDedupeMiddleware=S,exports.createDevOverlay=be,exports.createHttpClient=de,exports.createPipeline=C,exports.createProjectionTransformer=l,exports.createRealtimePlugin=ve,exports.createRequiredFieldsValidator=r,exports.createSSEClient=ge,exports.createSchemaValidator=n,exports.createStreamingMiddleware=j,exports.createTypeGuard=ae,exports.createTypedApiClient=E,exports.createTypedRequest=T,exports.createTypedResponse=w,exports.createUrl=O,exports.createWebSocketClient=me,exports.createWrapperTransformer=u,exports.dedupeMiddleware=re,exports.destroyDevOverlay=Se,exports.getDevOverlay=xe,exports.handleStream=k,exports.isHttpError=U,exports.retry=_,exports.streamToFile=ce,exports.streamingMiddleware=le,exports.transformCamelToSnake=s,exports.transformFlatten=c,exports.transformSnakeToCamel=o,exports.validatorIsArray=i,exports.validatorIsObject=a,exports.withTimeout=ne;
|
|
2
463
|
//# sourceMappingURL=nexa.cjs.js.map
|