@univerjs/network 0.5.5 → 0.6.0-alpha.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/lib/cjs/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  "use strict";var G=Object.defineProperty;var W=(e,t,r)=>t in e?G(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var m=(e,t,r)=>W(e,typeof t!="symbol"?t+"":t,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("@univerjs/core"),w=require("rxjs"),R=require("rxjs/operators"),j="application/json";class E{constructor(t){m(this,"_headers",new Map);typeof t=="string"?this._handleHeadersString(t):t instanceof Headers?this._handleHeaders(t):t&&this._handleHeadersConstructorProps(t)}forEach(t){this._headers.forEach((r,n)=>t(n,r))}has(t){return!!this._headers.has(t.toLowerCase())}get(t){const r=t.toLowerCase();return this._headers.has(r)?this._headers.get(r):null}set(t,r){this._setHeader(t,r)}toHeadersInit(){var r,n;const t={};return this._headers.forEach((s,o)=>{t[o]=s.join(",")}),(r=t.accept)!=null||(t.accept="application/json, text/plain, */*"),(n=t["content-type"])!=null||(t["content-type"]="application/json;charset=UTF-8"),t}_setHeader(t,r){const n=t.toLowerCase();this._headers.has(n)?this._headers.get(n).push(r.toString()):this._headers.set(n,[r.toString()])}_handleHeadersString(t){t.split(`
2
- `).forEach(r=>{const[n,s]=r.split(":");n&&s&&this._setHeader(n,s)})}_handleHeadersConstructorProps(t){Object.entries(t).forEach(([r,n])=>this._setHeader(r,n))}_handleHeaders(t){t.forEach((r,n)=>this._setHeader(n,r))}}const A=p.createIdentifier("network.http-implementation");class k{constructor(t){this.params=t}toString(){return this.params?Object.keys(this.params).map(t=>`${t}=${this.params[t]}`).join("&"):""}}let V=0;class U{constructor(t,r,n){m(this,"uid",V++);this.method=t,this.url=r,this.requestParams=n}get headers(){return this.requestParams.headers}get withCredentials(){return this.requestParams.withCredentials}get responseType(){return this.requestParams.responseType}getUrlWithParams(){var r,n;const t=(n=(r=this.requestParams)==null?void 0:r.params)==null?void 0:n.toString();return t?`${this.url}${this.url.includes("?")?"&":"?"}${t}`:this.url}getBody(){var n,s;const t=(n=this.headers.get("Content-Type"))!=null?n:j,r=(s=this.requestParams)==null?void 0:s.body;return t===j&&r&&typeof r=="object"?JSON.stringify(r):r?`${r}`:null}getHeadersInit(){return this.headers.toHeadersInit()}}var P=Object.defineProperty,z=Object.getOwnPropertyDescriptor,J=(e,t,r,n)=>{for(var s=n>1?void 0:n?z(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(n?i(t,r,s):i(s))||s);return n&&s&&P(t,r,s),s},K=(e,t)=>(r,n)=>t(r,n,e);exports.HTTPService=class extends p.Disposable{constructor(r){super();m(this,"_interceptors",[]);m(this,"_pipe");this._http=r}registerHTTPInterceptor(r){if(this._interceptors.indexOf(r)!==-1)throw new Error("[HTTPService]: The interceptor has already been registered!");return this._interceptors.push(r),this._interceptors=this._interceptors.sort((n,s)=>{var o,i;return((o=n.priority)!=null?o:0)-((i=s.priority)!=null?i:0)}),this._pipe=null,p.toDisposable(()=>p.remove(this._interceptors,r))}get(r,n){return this._request("GET",r,n)}post(r,n){return this._request("POST",r,n)}put(r,n){return this._request("PUT",r,n)}delete(r,n){return this._request("DELETE",r,n)}patch(r,n){return this._request("PATCH",r,n)}getSSE(r,n,s){var d,u;const o=new E(s==null?void 0:s.headers),i=new k(s==null?void 0:s.params),c=new U(r,n,{headers:o,params:i,withCredentials:(d=s==null?void 0:s.withCredentials)!=null?d:!1,reportProgress:!0,responseType:(u=s==null?void 0:s.responseType)!=null?u:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body});return w.of(c).pipe(R.concatMap(a=>this._runInterceptorsAndImplementation(a)))}async _request(r,n,s){var a,l;const o=new E(s==null?void 0:s.headers),i=new k(s==null?void 0:s.params),c=new U(r,n,{headers:o,params:i,withCredentials:(a=s==null?void 0:s.withCredentials)!=null?a:!1,responseType:(l=s==null?void 0:s.responseType)!=null?l:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body}),d=w.of(c).pipe(R.concatMap(h=>this._runInterceptorsAndImplementation(h)));return await w.firstValueFrom(d)}_runInterceptorsAndImplementation(r){return this._pipe||(this._pipe=this._interceptors.map(n=>n.interceptor).reduceRight((n,s)=>Y(n,s),(n,s)=>s(n))),this._pipe(r,n=>this._http.send(n))}};exports.HTTPService=J([K(0,A)],exports.HTTPService);function Y(e,t){return(r,n)=>t(r,s=>e(s,n))}const Q=200,Z=300;var x=(e=>(e[e.Continue=100]="Continue",e[e.SwitchingProtocols=101]="SwitchingProtocols",e[e.Processing=102]="Processing",e[e.EarlyHints=103]="EarlyHints",e[e.Ok=200]="Ok",e[e.Created=201]="Created",e[e.Accepted=202]="Accepted",e[e.NonAuthoritativeInformation=203]="NonAuthoritativeInformation",e[e.NoContent=204]="NoContent",e[e.ResetContent=205]="ResetContent",e[e.PartialContent=206]="PartialContent",e[e.MultiStatus=207]="MultiStatus",e[e.AlreadyReported=208]="AlreadyReported",e[e.ImUsed=226]="ImUsed",e[e.MultipleChoices=300]="MultipleChoices",e[e.MovedPermanently=301]="MovedPermanently",e[e.Found=302]="Found",e[e.SeeOther=303]="SeeOther",e[e.NotModified=304]="NotModified",e[e.UseProxy=305]="UseProxy",e[e.Unused=306]="Unused",e[e.TemporaryRedirect=307]="TemporaryRedirect",e[e.PermanentRedirect=308]="PermanentRedirect",e[e.BadRequest=400]="BadRequest",e[e.Unauthorized=401]="Unauthorized",e[e.PaymentRequired=402]="PaymentRequired",e[e.Forbidden=403]="Forbidden",e[e.NotFound=404]="NotFound",e[e.MethodNotAllowed=405]="MethodNotAllowed",e[e.NotAcceptable=406]="NotAcceptable",e[e.ProxyAuthenticationRequired=407]="ProxyAuthenticationRequired",e[e.RequestTimeout=408]="RequestTimeout",e[e.Conflict=409]="Conflict",e[e.Gone=410]="Gone",e[e.LengthRequired=411]="LengthRequired",e[e.PreconditionFailed=412]="PreconditionFailed",e[e.PayloadTooLarge=413]="PayloadTooLarge",e[e.UriTooLong=414]="UriTooLong",e[e.UnsupportedMediaType=415]="UnsupportedMediaType",e[e.RangeNotSatisfiable=416]="RangeNotSatisfiable",e[e.ExpectationFailed=417]="ExpectationFailed",e[e.ImATeapot=418]="ImATeapot",e[e.MisdirectedRequest=421]="MisdirectedRequest",e[e.UnprocessableEntity=422]="UnprocessableEntity",e[e.Locked=423]="Locked",e[e.FailedDependency=424]="FailedDependency",e[e.TooEarly=425]="TooEarly",e[e.UpgradeRequired=426]="UpgradeRequired",e[e.PreconditionRequired=428]="PreconditionRequired",e[e.TooManyRequests=429]="TooManyRequests",e[e.RequestHeaderFieldsTooLarge=431]="RequestHeaderFieldsTooLarge",e[e.UnavailableForLegalReasons=451]="UnavailableForLegalReasons",e[e.InternalServerError=500]="InternalServerError",e[e.NotImplemented=501]="NotImplemented",e[e.BadGateway=502]="BadGateway",e[e.ServiceUnavailable=503]="ServiceUnavailable",e[e.GatewayTimeout=504]="GatewayTimeout",e[e.HttpVersionNotSupported=505]="HttpVersionNotSupported",e[e.VariantAlsoNegotiates=506]="VariantAlsoNegotiates",e[e.InsufficientStorage=507]="InsufficientStorage",e[e.LoopDetected=508]="LoopDetected",e[e.NotExtended=510]="NotExtended",e[e.NetworkAuthenticationRequired=511]="NetworkAuthenticationRequired",e))(x||{}),D=(e=>(e[e.DownloadProgress=0]="DownloadProgress",e[e.Response=1]="Response",e))(D||{});class L{constructor({body:t,headers:r,status:n,statusText:s}){m(this,"type",1);m(this,"body");m(this,"headers");m(this,"status");m(this,"statusText");this.body=t,this.headers=r,this.status=n,this.statusText=s}}class M{constructor(t,r,n){m(this,"type",0);this.total=t,this.loaded=r,this.partialText=n}}class B{constructor(t,r,n){this.headers=t,this.status=r,this.statusText=n}}class I{constructor({request:t,headers:r,status:n,statusText:s,error:o}){m(this,"request");m(this,"headers");m(this,"status");m(this,"statusText");m(this,"error");this.request=t,this.headers=r,this.status=n,this.statusText=s,this.error=o}}function X(e){return{method:e.method,headers:e.getHeadersInit(),body:e.getBody(),credentials:e.withCredentials?"include":void 0}}var H=Object.defineProperty,S=Object.getOwnPropertyDescriptor,C=(e,t,r,n)=>{for(var s=n>1?void 0:n?S(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(n?i(t,r,s):i(s))||s);return n&&s&&H(t,r,s),s},T=(e,t)=>(r,n)=>t(r,n,e);exports.FetchHTTPImplementation=class{constructor(t){this._logService=t}send(t){return new w.Observable(r=>{const n=new AbortController;return this._send(t,r,n).catch(s=>{r.error(new I({error:s,request:t}))}),()=>n.abort()})}async _send(t,r,n){var a,l;let s;try{const h=X(t),y=t.getUrlWithParams(),g=fetch(y,{signal:n.signal,...h});this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${y} with params ${h}`),s=await g}catch(h){const y=new I({request:t,error:h,status:(a=h.status)!=null?a:0,statusText:(l=h.statusText)!=null?l:"Unknown Error",headers:h.headers});this._logService.error("[FetchHTTPImplementation]: network error",y),r.error(y);return}const o=new E(s.headers),i=s.status,c=s.statusText;let d=null;if(s.body&&(d=await this._readBody(t,s,r)),i>=x.Ok&&i<x.MultipleChoices)r.next(new L({body:d,headers:o,status:i,statusText:c}));else{const h=new I({request:t,error:d,status:i,statusText:c,headers:o});this._logService.error("[FetchHTTPImplementation]: network error",h),r.error(h)}r.complete()}async _readBody(t,r,n){var y,g;const s=[],o=r.body.getReader(),i=r.headers.get("content-length");let c=0;const d=(y=t.requestParams)==null?void 0:y.reportProgress,u=t.responseType;let a,l;for(;;){const{done:v,value:f}=await o.read();if(v)break;s.push(f),c+=f.length,d&&u==="text"&&(a=(a!=null?a:"")+(l!=null?l:l=new TextDecoder).decode(f,{stream:!0}),n.next(new M(i?Number.parseInt(i,10):void 0,c,a)))}const h=ee(s,c);try{const v=(g=r.headers.get("content-type"))!=null?g:"";return te(t,h,v)}catch(v){const f=new I({request:t,error:v,status:r.status,statusText:r.statusText,headers:new E(r.headers)});return this._logService.error("[FetchHTTPImplementation]: network error",f),n.error(f),null}}};exports.FetchHTTPImplementation=C([T(0,p.ILogService)],exports.FetchHTTPImplementation);function ee(e,t){const r=new Uint8Array(t);let n=0;for(const s of e)r.set(s,n),n+=s.length;return r}const re=/^\)\]\}',?\n/;function te(e,t,r){switch(e.responseType){case"json":const n=new TextDecoder().decode(t).replace(re,"");return n===""?null:JSON.parse(n);case"text":return new TextDecoder().decode(t);case"blob":return new Blob([t],{type:r});case"arraybuffer":return t.buffer;default:throw new Error(`[FetchHTTPImplementation]: unknown response type: ${e.responseType}.`)}}var ne=Object.defineProperty,se=Object.getOwnPropertyDescriptor,oe=(e,t,r,n)=>{for(var s=n>1?void 0:n?se(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(n?i(t,r,s):i(s))||s);return n&&s&&ne(t,r,s),s},ie=(e,t)=>(r,n)=>t(r,n,e);exports.XHRHTTPImplementation=class{constructor(t){this._logService=t}send(t){return new w.Observable(r=>{const n=new XMLHttpRequest,s=t.getUrlWithParams(),o=X(t);n.open(t.method,s),t.withCredentials&&(n.withCredentials=!0),o.headers&&Object.entries(o.headers).forEach(([a,l])=>n.setRequestHeader(a,l));const i=()=>{const a=n.statusText||"OK",l=new E(n.getAllResponseHeaders());return new B(l,n.status,a)},c=()=>{const{headers:a,statusText:l,status:h}=i(),{responseType:y}=t;let g=null,v=null;h!==x.NoContent&&(g=typeof n.response>"u"?n.responseText:n.response);let f=h>=Q&&h<Z;if(y==="json"&&typeof g=="string"){const b=g;try{g=g?JSON.parse(g):null}catch(_){f=!1,g=b,v=_}}if(f)r.next(new L({body:g,headers:a,status:h,statusText:l}));else{const b=new I({request:t,error:v,headers:a,status:h,statusText:l});this._logService.error("[XHRHTTPImplementation]: network error",b),r.error(b)}},d=a=>{const l=new I({request:t,error:a,status:n.status||0,statusText:n.statusText||"Unknown Error",headers:i().headers});this._logService.error("[XHRHTTPImplementation]: network error",l),r.error(l)};n.addEventListener("load",c),n.addEventListener("error",d),n.addEventListener("abort",d),n.addEventListener("timeout",d);const u=t.getBody();return n.send(u),this._logService.debug(`[XHRHTTPImplementation]: sending request to url ${s} with params ${o}`),()=>{n.readyState!==n.DONE&&n.abort(),n.removeEventListener("load",c),n.removeEventListener("error",d),n.removeEventListener("abort",d),n.removeEventListener("timeout",d)}})}};exports.XHRHTTPImplementation=oe([ie(0,p.ILogService)],exports.XHRHTTPImplementation);var ce=Object.defineProperty,ae=Object.getOwnPropertyDescriptor,le=(e,t,r,n)=>{for(var s=n>1?void 0:n?ae(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(n?i(t,r,s):i(s))||s);return n&&s&&ce(t,r,s),s},$=(e,t)=>(r,n)=>t(r,n,e),N;exports.UniverNetworkPlugin=(N=class extends p.Plugin{constructor(t=void 0,r,n){super(),this._config=t,this._logger=r,this._injector=n}onStarting(){var n,s,o;if(this._injector.get(exports.HTTPService,p.Quantity.OPTIONAL,p.LookUp.SKIP_SELF)&&!((n=this._config)!=null&&n.forceUseNewInstance)){this._logger.warn("[UniverNetworkPlugin]",'HTTPService is already registered in an ancestor interceptor. Skipping registration. If you want to force a new instance, set "forceUseNewInstance" to true in the plugin configuration.');return}const r=(s=this._config)!=null&&s.useFetchImpl?exports.FetchHTTPImplementation:typeof window<"u"?exports.XHRHTTPImplementation:exports.FetchHTTPImplementation;p.registerDependencies(this._injector,p.mergeOverrideWithDependencies([[exports.HTTPService],[A,{useClass:r}]],(o=this._config)==null?void 0:o.override))}},m(N,"pluginName","UNIVER_NETWORK_PLUGIN"),N);exports.UniverNetworkPlugin=le([$(1,p.ILogService),$(2,p.Inject(p.Injector))],exports.UniverNetworkPlugin);const he=p.createIdentifier("univer.network.socket.service");class pe extends p.Disposable{createSocket(t){try{const r=new WebSocket(t),n=new p.DisposableCollection;return{URL:t,close:(o,i)=>{r.close(o,i),n.dispose()},send:o=>{r.send(o)},open$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("open",i),n.add(p.toDisposable(()=>r.removeEventListener("open",i)))}).pipe(R.share()),close$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("close",i),n.add(p.toDisposable(()=>r.removeEventListener("close",i)))}).pipe(R.share()),error$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("error",i),n.add(p.toDisposable(()=>r.removeEventListener("error",i)))}).pipe(R.share()),message$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("message",i),n.add(p.toDisposable(()=>r.removeEventListener("message",i)))}).pipe(R.share())}}catch(r){return console.error(r),null}}}const de=3,ue=1e3,fe=e=>{var n,s;const t=(n=e==null?void 0:e.maxRetryAttempts)!=null?n:de,r=(s=e==null?void 0:e.delayInterval)!=null?s:ue;return(o,i)=>i(o).pipe(R.retry({delay:r,count:t}))},ge=e=>{const t=[],r=new Set,n=()=>{var s;for(;r.size<((s=e==null?void 0:e.maxParallel)!=null?s:1)&&t.length>0;){const o=t.shift();r.add(o),o()}};return(s,o)=>new w.Observable(i=>{const c=()=>o(s).subscribe({next:u=>i.next(u),error:u=>i.error(u),complete:()=>i.complete()}),d=()=>{r.delete(c),p.remove(t,c),n()};return t.push(c),n(),d})},me=e=>{const{errorStatusCodes:t,onAuthError:r}=e;return(s,o)=>o(s).pipe(w.catchError(i=>(i instanceof I&&t.some(c=>c===i.status)&&r(),w.throwError(()=>i))))},ye=(e=300)=>{let r=()=>{};return n=>new Promise(s=>{r();const o=setTimeout(()=>{s(!0)},e);r=()=>{clearTimeout(o),s(!1)}})},we=()=>(e,t)=>t.map(r=>({config:r,result:e})),ve=(e,t={})=>{const{isMatch:r,getParamsFromRequest:n,mergeParamsToRequest:s}=e,{fetchCheck:o=ye(300),distributeResult:i=we()}=t,c=[],d=u=>u.map(a=>a.config);return(u,a)=>r(u)?new w.Observable(l=>{const h=n(u);c.push({next:g=>l.next(g),error:g=>l.error(g),config:h});const y=d(c);o(u).then(g=>{if(g){const v=[];y.forEach(f=>{const b=c.findIndex(_=>_.config===f);if(b>=0){const[_]=c.splice(b,1);v.push(_)}}),a(s(y,u)).subscribe({next:f=>{if(f.type===D.Response){const b=f.body,_=i(b,y);v.forEach(F=>{const q=_.find(O=>O.config===F.config);if(q){const O=new L({body:q.result,headers:f.headers,status:f.status,statusText:f.statusText});F.next(O)}else F.error("batch error")})}},complete:()=>l.complete(),error:f=>l.error(f)})}})}):a(u)};exports.AuthInterceptorFactory=me;exports.HTTPEventType=D;exports.HTTPHeaders=E;exports.HTTPProgress=M;exports.HTTPRequest=U;exports.HTTPResponse=L;exports.HTTPResponseError=I;exports.HTTPStatusCode=x;exports.IHTTPImplementation=A;exports.ISocketService=he;exports.MergeInterceptorFactory=ve;exports.ResponseHeader=B;exports.RetryInterceptorFactory=fe;exports.ThresholdInterceptorFactory=ge;exports.WebSocketService=pe;
2
+ `).forEach(r=>{const[n,s]=r.split(":");n&&s&&this._setHeader(n,s)})}_handleHeadersConstructorProps(t){Object.entries(t).forEach(([r,n])=>this._setHeader(r,n))}_handleHeaders(t){t.forEach((r,n)=>this._setHeader(n,r))}}const U=p.createIdentifier("network.http-implementation");class q{constructor(t){this.params=t}toString(){return this.params?Object.keys(this.params).map(t=>{const r=this.params[t];return Array.isArray(r)?r.map(n=>`${t}=${n}`).join("&"):`${t}=${r}`}).join("&"):""}}let V=0;class A{constructor(t,r,n){m(this,"uid",V++);this.method=t,this.url=r,this.requestParams=n}get headers(){return this.requestParams.headers}get withCredentials(){return this.requestParams.withCredentials}get responseType(){return this.requestParams.responseType}getUrlWithParams(){var r,n;const t=(n=(r=this.requestParams)==null?void 0:r.params)==null?void 0:n.toString();return t?`${this.url}${this.url.includes("?")?"&":"?"}${t}`:this.url}getBody(){var n,s;const t=(n=this.headers.get("Content-Type"))!=null?n:j,r=(s=this.requestParams)==null?void 0:s.body;return t===j&&r&&typeof r=="object"?JSON.stringify(r):r?`${r}`:null}getHeadersInit(){return this.headers.toHeadersInit()}}var P=Object.defineProperty,z=Object.getOwnPropertyDescriptor,J=(e,t,r,n)=>{for(var s=n>1?void 0:n?z(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(n?i(t,r,s):i(s))||s);return n&&s&&P(t,r,s),s},K=(e,t)=>(r,n)=>t(r,n,e);exports.HTTPService=class extends p.Disposable{constructor(r){super();m(this,"_interceptors",[]);m(this,"_pipe");this._http=r}registerHTTPInterceptor(r){if(this._interceptors.indexOf(r)!==-1)throw new Error("[HTTPService]: The interceptor has already been registered!");return this._interceptors.push(r),this._interceptors=this._interceptors.sort((n,s)=>{var o,i;return((o=n.priority)!=null?o:0)-((i=s.priority)!=null?i:0)}),this._pipe=null,p.toDisposable(()=>p.remove(this._interceptors,r))}get(r,n){return this._request("GET",r,n)}post(r,n){return this._request("POST",r,n)}put(r,n){return this._request("PUT",r,n)}delete(r,n){return this._request("DELETE",r,n)}patch(r,n){return this._request("PATCH",r,n)}getSSE(r,n,s){var d,u;const o=new E(s==null?void 0:s.headers),i=new q(s==null?void 0:s.params),c=new A(r,n,{headers:o,params:i,withCredentials:(d=s==null?void 0:s.withCredentials)!=null?d:!1,reportProgress:!0,responseType:(u=s==null?void 0:s.responseType)!=null?u:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body});return w.of(c).pipe(R.concatMap(a=>this._runInterceptorsAndImplementation(a)))}async _request(r,n,s){var a,l;const o=new E(s==null?void 0:s.headers),i=new q(s==null?void 0:s.params),c=new A(r,n,{headers:o,params:i,withCredentials:(a=s==null?void 0:s.withCredentials)!=null?a:!1,responseType:(l=s==null?void 0:s.responseType)!=null?l:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body}),d=w.of(c).pipe(R.concatMap(h=>this._runInterceptorsAndImplementation(h)));return await w.firstValueFrom(d)}_runInterceptorsAndImplementation(r){return this._pipe||(this._pipe=this._interceptors.map(n=>n.interceptor).reduceRight((n,s)=>Y(n,s),(n,s)=>s(n))),this._pipe(r,n=>this._http.send(n))}};exports.HTTPService=J([K(0,U)],exports.HTTPService);function Y(e,t){return(r,n)=>t(r,s=>e(s,n))}const Q=200,Z=300;var x=(e=>(e[e.Continue=100]="Continue",e[e.SwitchingProtocols=101]="SwitchingProtocols",e[e.Processing=102]="Processing",e[e.EarlyHints=103]="EarlyHints",e[e.Ok=200]="Ok",e[e.Created=201]="Created",e[e.Accepted=202]="Accepted",e[e.NonAuthoritativeInformation=203]="NonAuthoritativeInformation",e[e.NoContent=204]="NoContent",e[e.ResetContent=205]="ResetContent",e[e.PartialContent=206]="PartialContent",e[e.MultiStatus=207]="MultiStatus",e[e.AlreadyReported=208]="AlreadyReported",e[e.ImUsed=226]="ImUsed",e[e.MultipleChoices=300]="MultipleChoices",e[e.MovedPermanently=301]="MovedPermanently",e[e.Found=302]="Found",e[e.SeeOther=303]="SeeOther",e[e.NotModified=304]="NotModified",e[e.UseProxy=305]="UseProxy",e[e.Unused=306]="Unused",e[e.TemporaryRedirect=307]="TemporaryRedirect",e[e.PermanentRedirect=308]="PermanentRedirect",e[e.BadRequest=400]="BadRequest",e[e.Unauthorized=401]="Unauthorized",e[e.PaymentRequired=402]="PaymentRequired",e[e.Forbidden=403]="Forbidden",e[e.NotFound=404]="NotFound",e[e.MethodNotAllowed=405]="MethodNotAllowed",e[e.NotAcceptable=406]="NotAcceptable",e[e.ProxyAuthenticationRequired=407]="ProxyAuthenticationRequired",e[e.RequestTimeout=408]="RequestTimeout",e[e.Conflict=409]="Conflict",e[e.Gone=410]="Gone",e[e.LengthRequired=411]="LengthRequired",e[e.PreconditionFailed=412]="PreconditionFailed",e[e.PayloadTooLarge=413]="PayloadTooLarge",e[e.UriTooLong=414]="UriTooLong",e[e.UnsupportedMediaType=415]="UnsupportedMediaType",e[e.RangeNotSatisfiable=416]="RangeNotSatisfiable",e[e.ExpectationFailed=417]="ExpectationFailed",e[e.ImATeapot=418]="ImATeapot",e[e.MisdirectedRequest=421]="MisdirectedRequest",e[e.UnprocessableEntity=422]="UnprocessableEntity",e[e.Locked=423]="Locked",e[e.FailedDependency=424]="FailedDependency",e[e.TooEarly=425]="TooEarly",e[e.UpgradeRequired=426]="UpgradeRequired",e[e.PreconditionRequired=428]="PreconditionRequired",e[e.TooManyRequests=429]="TooManyRequests",e[e.RequestHeaderFieldsTooLarge=431]="RequestHeaderFieldsTooLarge",e[e.UnavailableForLegalReasons=451]="UnavailableForLegalReasons",e[e.InternalServerError=500]="InternalServerError",e[e.NotImplemented=501]="NotImplemented",e[e.BadGateway=502]="BadGateway",e[e.ServiceUnavailable=503]="ServiceUnavailable",e[e.GatewayTimeout=504]="GatewayTimeout",e[e.HttpVersionNotSupported=505]="HttpVersionNotSupported",e[e.VariantAlsoNegotiates=506]="VariantAlsoNegotiates",e[e.InsufficientStorage=507]="InsufficientStorage",e[e.LoopDetected=508]="LoopDetected",e[e.NotExtended=510]="NotExtended",e[e.NetworkAuthenticationRequired=511]="NetworkAuthenticationRequired",e))(x||{}),D=(e=>(e[e.DownloadProgress=0]="DownloadProgress",e[e.Response=1]="Response",e))(D||{});class L{constructor({body:t,headers:r,status:n,statusText:s}){m(this,"type",1);m(this,"body");m(this,"headers");m(this,"status");m(this,"statusText");this.body=t,this.headers=r,this.status=n,this.statusText=s}}class M{constructor(t,r,n){m(this,"type",0);this.total=t,this.loaded=r,this.partialText=n}}class B{constructor(t,r,n){this.headers=t,this.status=r,this.statusText=n}}class I{constructor({request:t,headers:r,status:n,statusText:s,error:o}){m(this,"request");m(this,"headers");m(this,"status");m(this,"statusText");m(this,"error");this.request=t,this.headers=r,this.status=n,this.statusText=s,this.error=o}}function X(e){return{method:e.method,headers:e.getHeadersInit(),body:e.getBody(),credentials:e.withCredentials?"include":void 0}}var H=Object.defineProperty,S=Object.getOwnPropertyDescriptor,C=(e,t,r,n)=>{for(var s=n>1?void 0:n?S(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(n?i(t,r,s):i(s))||s);return n&&s&&H(t,r,s),s},T=(e,t)=>(r,n)=>t(r,n,e);exports.FetchHTTPImplementation=class{constructor(t){this._logService=t}send(t){return new w.Observable(r=>{const n=new AbortController;return this._send(t,r,n).catch(s=>{r.error(new I({error:s,request:t}))}),()=>n.abort()})}async _send(t,r,n){var a,l;let s;try{const h=X(t),y=t.getUrlWithParams(),g=fetch(y,{signal:n.signal,...h});this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${y} with params ${h}`),s=await g}catch(h){const y=new I({request:t,error:h,status:(a=h.status)!=null?a:0,statusText:(l=h.statusText)!=null?l:"Unknown Error",headers:h.headers});this._logService.error("[FetchHTTPImplementation]: network error",y),r.error(y);return}const o=new E(s.headers),i=s.status,c=s.statusText;let d=null;if(s.body&&(d=await this._readBody(t,s,r)),i>=x.Ok&&i<x.MultipleChoices)r.next(new L({body:d,headers:o,status:i,statusText:c}));else{const h=new I({request:t,error:d,status:i,statusText:c,headers:o});this._logService.error("[FetchHTTPImplementation]: network error",h),r.error(h)}r.complete()}async _readBody(t,r,n){var y,g;const s=[],o=r.body.getReader(),i=r.headers.get("content-length");let c=0;const d=(y=t.requestParams)==null?void 0:y.reportProgress,u=t.responseType;let a,l;for(;;){const{done:v,value:f}=await o.read();if(v)break;s.push(f),c+=f.length,d&&u==="text"&&(a=(a!=null?a:"")+(l!=null?l:l=new TextDecoder).decode(f,{stream:!0}),n.next(new M(i?Number.parseInt(i,10):void 0,c,a)))}const h=ee(s,c);try{const v=(g=r.headers.get("content-type"))!=null?g:"";return te(t,h,v)}catch(v){const f=new I({request:t,error:v,status:r.status,statusText:r.statusText,headers:new E(r.headers)});return this._logService.error("[FetchHTTPImplementation]: network error",f),n.error(f),null}}};exports.FetchHTTPImplementation=C([T(0,p.ILogService)],exports.FetchHTTPImplementation);function ee(e,t){const r=new Uint8Array(t);let n=0;for(const s of e)r.set(s,n),n+=s.length;return r}const re=/^\)\]\}',?\n/;function te(e,t,r){switch(e.responseType){case"json":const n=new TextDecoder().decode(t).replace(re,"");return n===""?null:JSON.parse(n);case"text":return new TextDecoder().decode(t);case"blob":return new Blob([t],{type:r});case"arraybuffer":return t.buffer;default:throw new Error(`[FetchHTTPImplementation]: unknown response type: ${e.responseType}.`)}}var ne=Object.defineProperty,se=Object.getOwnPropertyDescriptor,oe=(e,t,r,n)=>{for(var s=n>1?void 0:n?se(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(n?i(t,r,s):i(s))||s);return n&&s&&ne(t,r,s),s},ie=(e,t)=>(r,n)=>t(r,n,e);exports.XHRHTTPImplementation=class{constructor(t){this._logService=t}send(t){return new w.Observable(r=>{const n=new XMLHttpRequest,s=t.getUrlWithParams(),o=X(t);n.open(t.method,s),t.withCredentials&&(n.withCredentials=!0),o.headers&&Object.entries(o.headers).forEach(([a,l])=>n.setRequestHeader(a,l));const i=()=>{const a=n.statusText||"OK",l=new E(n.getAllResponseHeaders());return new B(l,n.status,a)},c=()=>{const{headers:a,statusText:l,status:h}=i(),{responseType:y}=t;let g=null,v=null;h!==x.NoContent&&(g=typeof n.response>"u"?n.responseText:n.response);let f=h>=Q&&h<Z;if(y==="json"&&typeof g=="string"){const b=g;try{g=g?JSON.parse(g):null}catch(_){f=!1,g=b,v=_}}if(f)r.next(new L({body:g,headers:a,status:h,statusText:l}));else{const b=new I({request:t,error:v,headers:a,status:h,statusText:l});this._logService.error("[XHRHTTPImplementation]: network error",b),r.error(b)}},d=a=>{const l=new I({request:t,error:a,status:n.status||0,statusText:n.statusText||"Unknown Error",headers:i().headers});this._logService.error("[XHRHTTPImplementation]: network error",l),r.error(l)};n.addEventListener("load",c),n.addEventListener("error",d),n.addEventListener("abort",d),n.addEventListener("timeout",d);const u=t.getBody();return n.send(u),this._logService.debug(`[XHRHTTPImplementation]: sending request to url ${s} with params ${o}`),()=>{n.readyState!==n.DONE&&n.abort(),n.removeEventListener("load",c),n.removeEventListener("error",d),n.removeEventListener("abort",d),n.removeEventListener("timeout",d)}})}};exports.XHRHTTPImplementation=oe([ie(0,p.ILogService)],exports.XHRHTTPImplementation);var ce=Object.defineProperty,ae=Object.getOwnPropertyDescriptor,le=(e,t,r,n)=>{for(var s=n>1?void 0:n?ae(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(n?i(t,r,s):i(s))||s);return n&&s&&ce(t,r,s),s},k=(e,t)=>(r,n)=>t(r,n,e),N;exports.UniverNetworkPlugin=(N=class extends p.Plugin{constructor(t=void 0,r,n){super(),this._config=t,this._logger=r,this._injector=n}onStarting(){var n,s,o;if(this._injector.get(exports.HTTPService,p.Quantity.OPTIONAL,p.LookUp.SKIP_SELF)&&!((n=this._config)!=null&&n.forceUseNewInstance)){this._logger.warn("[UniverNetworkPlugin]",'HTTPService is already registered in an ancestor interceptor. Skipping registration. If you want to force a new instance, set "forceUseNewInstance" to true in the plugin configuration.');return}const r=(s=this._config)!=null&&s.useFetchImpl?exports.FetchHTTPImplementation:typeof window<"u"?exports.XHRHTTPImplementation:exports.FetchHTTPImplementation;p.registerDependencies(this._injector,p.mergeOverrideWithDependencies([[exports.HTTPService],[U,{useClass:r}]],(o=this._config)==null?void 0:o.override))}},m(N,"pluginName","UNIVER_NETWORK_PLUGIN"),N);exports.UniverNetworkPlugin=le([k(1,p.ILogService),k(2,p.Inject(p.Injector))],exports.UniverNetworkPlugin);const he=p.createIdentifier("univer.network.socket.service");class pe extends p.Disposable{createSocket(t){try{const r=new WebSocket(t),n=new p.DisposableCollection;return{URL:t,close:(o,i)=>{r.close(o,i),n.dispose()},send:o=>{r.send(o)},open$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("open",i),n.add(p.toDisposable(()=>r.removeEventListener("open",i)))}).pipe(R.share()),close$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("close",i),n.add(p.toDisposable(()=>r.removeEventListener("close",i)))}).pipe(R.share()),error$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("error",i),n.add(p.toDisposable(()=>r.removeEventListener("error",i)))}).pipe(R.share()),message$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("message",i),n.add(p.toDisposable(()=>r.removeEventListener("message",i)))}).pipe(R.share())}}catch(r){return console.error(r),null}}}const de=3,ue=1e3,fe=e=>{var n,s;const t=(n=e==null?void 0:e.maxRetryAttempts)!=null?n:de,r=(s=e==null?void 0:e.delayInterval)!=null?s:ue;return(o,i)=>i(o).pipe(R.retry({delay:r,count:t}))},ge=e=>{const t=[],r=new Set,n=()=>{var s;for(;r.size<((s=e==null?void 0:e.maxParallel)!=null?s:1)&&t.length>0;){const o=t.shift();r.add(o),o()}};return(s,o)=>new w.Observable(i=>{const c=()=>o(s).subscribe({next:u=>i.next(u),error:u=>i.error(u),complete:()=>i.complete()}),d=()=>{r.delete(c),p.remove(t,c),n()};return t.push(c),n(),d})},me=e=>{const{errorStatusCodes:t,onAuthError:r}=e;return(s,o)=>o(s).pipe(w.catchError(i=>(i instanceof I&&t.some(c=>c===i.status)&&r(),w.throwError(()=>i))))},ye=(e=300)=>{let r=()=>{};return n=>new Promise(s=>{r();const o=setTimeout(()=>{s(!0)},e);r=()=>{clearTimeout(o),s(!1)}})},we=()=>(e,t)=>t.map(r=>({config:r,result:e})),ve=(e,t={})=>{const{isMatch:r,getParamsFromRequest:n,mergeParamsToRequest:s}=e,{fetchCheck:o=ye(300),distributeResult:i=we()}=t,c=[],d=u=>u.map(a=>a.config);return(u,a)=>r(u)?new w.Observable(l=>{const h=n(u);c.push({next:g=>l.next(g),error:g=>l.error(g),config:h});const y=d(c);o(u).then(g=>{if(g){const v=[];y.forEach(f=>{const b=c.findIndex(_=>_.config===f);if(b>=0){const[_]=c.splice(b,1);v.push(_)}}),a(s(y,u)).subscribe({next:f=>{if(f.type===D.Response){const b=f.body,_=i(b,y);v.forEach(F=>{const $=_.find(O=>O.config===F.config);if($){const O=new L({body:$.result,headers:f.headers,status:f.status,statusText:f.statusText});F.next(O)}else F.error("batch error")})}},complete:()=>l.complete(),error:f=>l.error(f)})}})}):a(u)};exports.AuthInterceptorFactory=me;exports.HTTPEventType=D;exports.HTTPHeaders=E;exports.HTTPProgress=M;exports.HTTPRequest=A;exports.HTTPResponse=L;exports.HTTPResponseError=I;exports.HTTPStatusCode=x;exports.IHTTPImplementation=U;exports.ISocketService=he;exports.MergeInterceptorFactory=ve;exports.ResponseHeader=B;exports.RetryInterceptorFactory=fe;exports.ThresholdInterceptorFactory=ge;exports.WebSocketService=pe;
package/lib/es/facade.js CHANGED
@@ -10,46 +10,46 @@ let p = class extends u {
10
10
  super(), this._injector = t, this._httpService = e;
11
11
  }
12
12
  /**
13
- * Send GET request to the server.
14
- * @param url The requested URL
15
- * @param params Query parameters
16
- * @returns Network response
13
+ * Send a GET request to the server.
14
+ * @param {string} url - The requested URL.
15
+ * @param {IRequestParams} [params] - Query parameters.
16
+ * @returns {Promise<HTTPResponse>} Network response.
17
17
  */
18
18
  get(t, e) {
19
19
  return this._httpService.get(t, e);
20
20
  }
21
21
  /**
22
- * Send POST request to the server.
23
- * @param url The requested URL
24
- * @param params Query parameters
25
- * @returns Network response
22
+ * Send a POST request to the server.
23
+ * @param {string} url - The requested URL.
24
+ * @param {IPostRequestParams} [params] - Query parameters.
25
+ * @returns {Promise<HTTPResponse>} Network response.
26
26
  */
27
27
  post(t, e) {
28
28
  return this._httpService.post(t, e);
29
29
  }
30
30
  /**
31
- * Send PUT request to the server.
32
- * @param url The requested URL
33
- * @param params Query parameters
34
- * @returns Network response
31
+ * Send a PUT request to the server.
32
+ * @param {string} url - The requested URL
33
+ * @param {IPostRequestParams} [params] - Query parameters
34
+ * @returns {Promise<HTTPResponse>} Network response
35
35
  */
36
36
  put(t, e) {
37
37
  return this._httpService.put(t, e);
38
38
  }
39
39
  /**
40
40
  * Send DELETE request to the server.
41
- * @param url The requested URL
42
- * @param params Query parameters
43
- * @returns Network response
41
+ * @param {string} url - The requested URL
42
+ * @param {IRequestParams} [params] - Query parameters
43
+ * @returns {Promise<HTTPResponse>} Network response
44
44
  */
45
45
  delete(t, e) {
46
46
  return this._httpService.delete(t, e);
47
47
  }
48
48
  /**
49
49
  * Send PATCH request to the server.
50
- * @param url The requested URL
51
- * @param params Query parameters
52
- * @returns Network response
50
+ * @param {string} url - The requested URL
51
+ * @param {IPostRequestParams} [params] - Query parameters
52
+ * @returns {Promise<HTTPResponse>} Network response
53
53
  */
54
54
  patch(t, e) {
55
55
  return this._httpService.patch(t, e);
@@ -57,10 +57,10 @@ let p = class extends u {
57
57
  /**
58
58
  * Request for a stream of server-sent events. Instead of a single response, the server sends a stream of responses,
59
59
  * Univer wraps the stream in an [`Observable`](https://rxjs.dev/guide/observable) which you can call `subscribe` on.
60
- * @param method HTTP request method
61
- * @param url The requested URL
62
- * @param params Query parameters
63
- * @returns An observable that emits the network response
60
+ * @param {HTTPRequestMethod} method - HTTP request method
61
+ * @param {string} url - The requested URL
62
+ * @param {IPostRequestParams} [params] - params Query parameters
63
+ * @returns {Observable<HTTPEvent>} An observable that emits the network response.
64
64
  */
65
65
  getSSE(t, e, r) {
66
66
  return this._httpService.getSSE(t, e, r);
package/lib/es/index.js CHANGED
@@ -1,67 +1,70 @@
1
1
  var Z = Object.defineProperty;
2
- var P = (e, r, t) => r in e ? Z(e, r, { enumerable: !0, configurable: !0, writable: !0, value: t }) : e[r] = t;
3
- var d = (e, r, t) => P(e, typeof r != "symbol" ? r + "" : r, t);
2
+ var P = (e, t, r) => t in e ? Z(e, t, { enumerable: !0, configurable: !0, writable: !0, value: r }) : e[t] = r;
3
+ var d = (e, t, r) => P(e, typeof t != "symbol" ? t + "" : t, r);
4
4
  import { createIdentifier as V, Disposable as z, toDisposable as R, remove as J, ILogService as D, Inject as S, Injector as H, Plugin as C, Quantity as T, LookUp as ee, registerDependencies as re, mergeOverrideWithDependencies as te, DisposableCollection as ne } from "@univerjs/core";
5
5
  import { of as q, firstValueFrom as se, Observable as m, catchError as oe, throwError as ie } from "rxjs";
6
6
  import { concatMap as M, share as b, retry as ce } from "rxjs/operators";
7
7
  const k = "application/json";
8
8
  class I {
9
- constructor(r) {
9
+ constructor(t) {
10
10
  d(this, "_headers", /* @__PURE__ */ new Map());
11
- typeof r == "string" ? this._handleHeadersString(r) : r instanceof Headers ? this._handleHeaders(r) : r && this._handleHeadersConstructorProps(r);
11
+ typeof t == "string" ? this._handleHeadersString(t) : t instanceof Headers ? this._handleHeaders(t) : t && this._handleHeadersConstructorProps(t);
12
12
  }
13
- forEach(r) {
14
- this._headers.forEach((t, n) => r(n, t));
13
+ forEach(t) {
14
+ this._headers.forEach((r, n) => t(n, r));
15
15
  }
16
- has(r) {
17
- return !!this._headers.has(r.toLowerCase());
16
+ has(t) {
17
+ return !!this._headers.has(t.toLowerCase());
18
18
  }
19
- get(r) {
20
- const t = r.toLowerCase();
21
- return this._headers.has(t) ? this._headers.get(t) : null;
19
+ get(t) {
20
+ const r = t.toLowerCase();
21
+ return this._headers.has(r) ? this._headers.get(r) : null;
22
22
  }
23
- set(r, t) {
24
- this._setHeader(r, t);
23
+ set(t, r) {
24
+ this._setHeader(t, r);
25
25
  }
26
26
  toHeadersInit() {
27
- var t, n;
28
- const r = {};
27
+ var r, n;
28
+ const t = {};
29
29
  return this._headers.forEach((s, o) => {
30
- r[o] = s.join(",");
31
- }), (t = r.accept) != null || (r.accept = "application/json, text/plain, */*"), (n = r["content-type"]) != null || (r["content-type"] = "application/json;charset=UTF-8"), r;
30
+ t[o] = s.join(",");
31
+ }), (r = t.accept) != null || (t.accept = "application/json, text/plain, */*"), (n = t["content-type"]) != null || (t["content-type"] = "application/json;charset=UTF-8"), t;
32
32
  }
33
- _setHeader(r, t) {
34
- const n = r.toLowerCase();
35
- this._headers.has(n) ? this._headers.get(n).push(t.toString()) : this._headers.set(n, [t.toString()]);
33
+ _setHeader(t, r) {
34
+ const n = t.toLowerCase();
35
+ this._headers.has(n) ? this._headers.get(n).push(r.toString()) : this._headers.set(n, [r.toString()]);
36
36
  }
37
- _handleHeadersString(r) {
38
- r.split(`
39
- `).forEach((t) => {
40
- const [n, s] = t.split(":");
37
+ _handleHeadersString(t) {
38
+ t.split(`
39
+ `).forEach((r) => {
40
+ const [n, s] = r.split(":");
41
41
  n && s && this._setHeader(n, s);
42
42
  });
43
43
  }
44
- _handleHeadersConstructorProps(r) {
45
- Object.entries(r).forEach(([t, n]) => this._setHeader(t, n));
44
+ _handleHeadersConstructorProps(t) {
45
+ Object.entries(t).forEach(([r, n]) => this._setHeader(r, n));
46
46
  }
47
- _handleHeaders(r) {
48
- r.forEach((t, n) => this._setHeader(n, t));
47
+ _handleHeaders(t) {
48
+ t.forEach((r, n) => this._setHeader(n, r));
49
49
  }
50
50
  }
51
51
  const K = V("network.http-implementation");
52
52
  class B {
53
- constructor(r) {
54
- this.params = r;
53
+ constructor(t) {
54
+ this.params = t;
55
55
  }
56
56
  toString() {
57
- return this.params ? Object.keys(this.params).map((r) => `${r}=${this.params[r]}`).join("&") : "";
57
+ return this.params ? Object.keys(this.params).map((t) => {
58
+ const r = this.params[t];
59
+ return Array.isArray(r) ? r.map((n) => `${t}=${n}`).join("&") : `${t}=${r}`;
60
+ }).join("&") : "";
58
61
  }
59
62
  }
60
63
  let ae = 0;
61
64
  class G {
62
- constructor(r, t, n) {
65
+ constructor(t, r, n) {
63
66
  d(this, "uid", ae++);
64
- this.method = r, this.url = t, this.requestParams = n;
67
+ this.method = t, this.url = r, this.requestParams = n;
65
68
  }
66
69
  get headers() {
67
70
  return this.requestParams.headers;
@@ -73,31 +76,31 @@ class G {
73
76
  return this.requestParams.responseType;
74
77
  }
75
78
  getUrlWithParams() {
76
- var t, n;
77
- const r = (n = (t = this.requestParams) == null ? void 0 : t.params) == null ? void 0 : n.toString();
78
- return r ? `${this.url}${this.url.includes("?") ? "&" : "?"}${r}` : this.url;
79
+ var r, n;
80
+ const t = (n = (r = this.requestParams) == null ? void 0 : r.params) == null ? void 0 : n.toString();
81
+ return t ? `${this.url}${this.url.includes("?") ? "&" : "?"}${t}` : this.url;
79
82
  }
80
83
  getBody() {
81
84
  var n, s;
82
- const r = (n = this.headers.get("Content-Type")) != null ? n : k, t = (s = this.requestParams) == null ? void 0 : s.body;
83
- return r === k && t && typeof t == "object" ? JSON.stringify(t) : t ? `${t}` : null;
85
+ const t = (n = this.headers.get("Content-Type")) != null ? n : k, r = (s = this.requestParams) == null ? void 0 : s.body;
86
+ return t === k && r && typeof r == "object" ? JSON.stringify(r) : r ? `${r}` : null;
84
87
  }
85
88
  getHeadersInit() {
86
89
  return this.headers.toHeadersInit();
87
90
  }
88
91
  }
89
- var le = Object.defineProperty, he = Object.getOwnPropertyDescriptor, pe = (e, r, t, n) => {
90
- for (var s = n > 1 ? void 0 : n ? he(r, t) : r, o = e.length - 1, i; o >= 0; o--)
91
- (i = e[o]) && (s = (n ? i(r, t, s) : i(s)) || s);
92
- return n && s && le(r, t, s), s;
93
- }, de = (e, r) => (t, n) => r(t, n, e);
92
+ var le = Object.defineProperty, he = Object.getOwnPropertyDescriptor, pe = (e, t, r, n) => {
93
+ for (var s = n > 1 ? void 0 : n ? he(t, r) : t, o = e.length - 1, i; o >= 0; o--)
94
+ (i = e[o]) && (s = (n ? i(t, r, s) : i(s)) || s);
95
+ return n && s && le(t, r, s), s;
96
+ }, de = (e, t) => (r, n) => t(r, n, e);
94
97
  let x = class extends z {
95
- constructor(r) {
98
+ constructor(t) {
96
99
  super();
97
100
  d(this, "_interceptors", []);
98
101
  // eslint-disable-next-line ts/no-explicit-any
99
102
  d(this, "_pipe");
100
- this._http = r;
103
+ this._http = t;
101
104
  }
102
105
  /**
103
106
  * Register an HTTP interceptor.
@@ -105,64 +108,64 @@ let x = class extends z {
105
108
  * @param interceptor the http interceptor
106
109
  * @returns a disposable handler to remove the interceptor
107
110
  */
108
- registerHTTPInterceptor(r) {
109
- if (this._interceptors.indexOf(r) !== -1)
111
+ registerHTTPInterceptor(t) {
112
+ if (this._interceptors.indexOf(t) !== -1)
110
113
  throw new Error("[HTTPService]: The interceptor has already been registered!");
111
- return this._interceptors.push(r), this._interceptors = this._interceptors.sort((t, n) => {
114
+ return this._interceptors.push(t), this._interceptors = this._interceptors.sort((r, n) => {
112
115
  var s, o;
113
- return ((s = t.priority) != null ? s : 0) - ((o = n.priority) != null ? o : 0);
114
- }), this._pipe = null, R(() => J(this._interceptors, r));
116
+ return ((s = r.priority) != null ? s : 0) - ((o = n.priority) != null ? o : 0);
117
+ }), this._pipe = null, R(() => J(this._interceptors, t));
115
118
  }
116
- get(r, t) {
117
- return this._request("GET", r, t);
119
+ get(t, r) {
120
+ return this._request("GET", t, r);
118
121
  }
119
- post(r, t) {
120
- return this._request("POST", r, t);
122
+ post(t, r) {
123
+ return this._request("POST", t, r);
121
124
  }
122
- put(r, t) {
123
- return this._request("PUT", r, t);
125
+ put(t, r) {
126
+ return this._request("PUT", t, r);
124
127
  }
125
- delete(r, t) {
126
- return this._request("DELETE", r, t);
128
+ delete(t, r) {
129
+ return this._request("DELETE", t, r);
127
130
  }
128
- patch(r, t) {
129
- return this._request("PATCH", r, t);
131
+ patch(t, r) {
132
+ return this._request("PATCH", t, r);
130
133
  }
131
- getSSE(r, t, n) {
134
+ getSSE(t, r, n) {
132
135
  var c, w;
133
- const s = new I(n == null ? void 0 : n.headers), o = new B(n == null ? void 0 : n.params), i = new G(r, t, {
136
+ const s = new I(n == null ? void 0 : n.headers), o = new B(n == null ? void 0 : n.params), i = new G(t, r, {
134
137
  headers: s,
135
138
  params: o,
136
139
  withCredentials: (c = n == null ? void 0 : n.withCredentials) != null ? c : !1,
137
140
  reportProgress: !0,
138
141
  responseType: (w = n == null ? void 0 : n.responseType) != null ? w : "json",
139
- body: ["GET", "DELETE"].includes(r) || n == null ? void 0 : n.body
142
+ body: ["GET", "DELETE"].includes(t) || n == null ? void 0 : n.body
140
143
  });
141
144
  return q(i).pipe(M((a) => this._runInterceptorsAndImplementation(a)));
142
145
  }
143
146
  /** The HTTP request implementations */
144
- async _request(r, t, n) {
147
+ async _request(t, r, n) {
145
148
  var a, h;
146
- const s = new I(n == null ? void 0 : n.headers), o = new B(n == null ? void 0 : n.params), i = new G(r, t, {
149
+ const s = new I(n == null ? void 0 : n.headers), o = new B(n == null ? void 0 : n.params), i = new G(t, r, {
147
150
  headers: s,
148
151
  params: o,
149
152
  withCredentials: (a = n == null ? void 0 : n.withCredentials) != null ? a : !1,
150
153
  // default value for withCredentials is false by MDN
151
154
  responseType: (h = n == null ? void 0 : n.responseType) != null ? h : "json",
152
- body: ["GET", "DELETE"].includes(r) || n == null ? void 0 : n.body
155
+ body: ["GET", "DELETE"].includes(t) || n == null ? void 0 : n.body
153
156
  }), c = q(i).pipe(
154
157
  M((l) => this._runInterceptorsAndImplementation(l))
155
158
  );
156
159
  return await se(c);
157
160
  }
158
161
  // eslint-disable-next-line ts/no-explicit-any
159
- _runInterceptorsAndImplementation(r) {
160
- return this._pipe || (this._pipe = this._interceptors.map((t) => t.interceptor).reduceRight(
161
- (t, n) => ue(t, n),
162
- (t, n) => n(t)
162
+ _runInterceptorsAndImplementation(t) {
163
+ return this._pipe || (this._pipe = this._interceptors.map((r) => r.interceptor).reduceRight(
164
+ (r, n) => ue(r, n),
165
+ (r, n) => n(r)
163
166
  )), this._pipe(
164
- r,
165
- (t) => this._http.send(t)
167
+ t,
168
+ (r) => this._http.send(r)
166
169
  /* final handler */
167
170
  );
168
171
  }
@@ -170,15 +173,15 @@ let x = class extends z {
170
173
  x = pe([
171
174
  de(0, K)
172
175
  ], x);
173
- function ue(e, r) {
174
- return (t, n) => r(t, (s) => e(s, n));
176
+ function ue(e, t) {
177
+ return (r, n) => t(r, (s) => e(s, n));
175
178
  }
176
179
  const fe = 200, ge = 300;
177
180
  var L = /* @__PURE__ */ ((e) => (e[e.Continue = 100] = "Continue", e[e.SwitchingProtocols = 101] = "SwitchingProtocols", e[e.Processing = 102] = "Processing", e[e.EarlyHints = 103] = "EarlyHints", e[e.Ok = 200] = "Ok", e[e.Created = 201] = "Created", e[e.Accepted = 202] = "Accepted", e[e.NonAuthoritativeInformation = 203] = "NonAuthoritativeInformation", e[e.NoContent = 204] = "NoContent", e[e.ResetContent = 205] = "ResetContent", e[e.PartialContent = 206] = "PartialContent", e[e.MultiStatus = 207] = "MultiStatus", e[e.AlreadyReported = 208] = "AlreadyReported", e[e.ImUsed = 226] = "ImUsed", e[e.MultipleChoices = 300] = "MultipleChoices", e[e.MovedPermanently = 301] = "MovedPermanently", e[e.Found = 302] = "Found", e[e.SeeOther = 303] = "SeeOther", e[e.NotModified = 304] = "NotModified", e[e.UseProxy = 305] = "UseProxy", e[e.Unused = 306] = "Unused", e[e.TemporaryRedirect = 307] = "TemporaryRedirect", e[e.PermanentRedirect = 308] = "PermanentRedirect", e[e.BadRequest = 400] = "BadRequest", e[e.Unauthorized = 401] = "Unauthorized", e[e.PaymentRequired = 402] = "PaymentRequired", e[e.Forbidden = 403] = "Forbidden", e[e.NotFound = 404] = "NotFound", e[e.MethodNotAllowed = 405] = "MethodNotAllowed", e[e.NotAcceptable = 406] = "NotAcceptable", e[e.ProxyAuthenticationRequired = 407] = "ProxyAuthenticationRequired", e[e.RequestTimeout = 408] = "RequestTimeout", e[e.Conflict = 409] = "Conflict", e[e.Gone = 410] = "Gone", e[e.LengthRequired = 411] = "LengthRequired", e[e.PreconditionFailed = 412] = "PreconditionFailed", e[e.PayloadTooLarge = 413] = "PayloadTooLarge", e[e.UriTooLong = 414] = "UriTooLong", e[e.UnsupportedMediaType = 415] = "UnsupportedMediaType", e[e.RangeNotSatisfiable = 416] = "RangeNotSatisfiable", e[e.ExpectationFailed = 417] = "ExpectationFailed", e[e.ImATeapot = 418] = "ImATeapot", e[e.MisdirectedRequest = 421] = "MisdirectedRequest", e[e.UnprocessableEntity = 422] = "UnprocessableEntity", e[e.Locked = 423] = "Locked", e[e.FailedDependency = 424] = "FailedDependency", e[e.TooEarly = 425] = "TooEarly", e[e.UpgradeRequired = 426] = "UpgradeRequired", e[e.PreconditionRequired = 428] = "PreconditionRequired", e[e.TooManyRequests = 429] = "TooManyRequests", e[e.RequestHeaderFieldsTooLarge = 431] = "RequestHeaderFieldsTooLarge", e[e.UnavailableForLegalReasons = 451] = "UnavailableForLegalReasons", e[e.InternalServerError = 500] = "InternalServerError", e[e.NotImplemented = 501] = "NotImplemented", e[e.BadGateway = 502] = "BadGateway", e[e.ServiceUnavailable = 503] = "ServiceUnavailable", e[e.GatewayTimeout = 504] = "GatewayTimeout", e[e.HttpVersionNotSupported = 505] = "HttpVersionNotSupported", e[e.VariantAlsoNegotiates = 506] = "VariantAlsoNegotiates", e[e.InsufficientStorage = 507] = "InsufficientStorage", e[e.LoopDetected = 508] = "LoopDetected", e[e.NotExtended = 510] = "NotExtended", e[e.NetworkAuthenticationRequired = 511] = "NetworkAuthenticationRequired", e))(L || {}), Y = /* @__PURE__ */ ((e) => (e[e.DownloadProgress = 0] = "DownloadProgress", e[e.Response = 1] = "Response", e))(Y || {});
178
181
  class $ {
179
182
  constructor({
180
- body: r,
181
- headers: t,
183
+ body: t,
184
+ headers: r,
182
185
  status: n,
183
186
  statusText: s
184
187
  }) {
@@ -187,24 +190,24 @@ class $ {
187
190
  d(this, "headers");
188
191
  d(this, "status");
189
192
  d(this, "statusText");
190
- this.body = r, this.headers = t, this.status = n, this.statusText = s;
193
+ this.body = t, this.headers = r, this.status = n, this.statusText = s;
191
194
  }
192
195
  }
193
196
  class we {
194
- constructor(r, t, n) {
197
+ constructor(t, r, n) {
195
198
  d(this, "type", 0);
196
- this.total = r, this.loaded = t, this.partialText = n;
199
+ this.total = t, this.loaded = r, this.partialText = n;
197
200
  }
198
201
  }
199
202
  class ye {
200
- constructor(r, t, n) {
201
- this.headers = r, this.status = t, this.statusText = n;
203
+ constructor(t, r, n) {
204
+ this.headers = t, this.status = r, this.statusText = n;
202
205
  }
203
206
  }
204
207
  class _ {
205
208
  constructor({
206
- request: r,
207
- headers: t,
209
+ request: t,
210
+ headers: r,
208
211
  status: n,
209
212
  statusText: s,
210
213
  error: o
@@ -214,7 +217,7 @@ class _ {
214
217
  d(this, "status");
215
218
  d(this, "statusText");
216
219
  d(this, "error");
217
- this.request = r, this.headers = t, this.status = n, this.statusText = s, this.error = o;
220
+ this.request = t, this.headers = r, this.status = n, this.statusText = s, this.error = o;
218
221
  }
219
222
  }
220
223
  function Q(e) {
@@ -225,32 +228,32 @@ function Q(e) {
225
228
  credentials: e.withCredentials ? "include" : void 0
226
229
  };
227
230
  }
228
- var me = Object.defineProperty, _e = Object.getOwnPropertyDescriptor, ve = (e, r, t, n) => {
229
- for (var s = n > 1 ? void 0 : n ? _e(r, t) : r, o = e.length - 1, i; o >= 0; o--)
230
- (i = e[o]) && (s = (n ? i(r, t, s) : i(s)) || s);
231
- return n && s && me(r, t, s), s;
232
- }, Ee = (e, r) => (t, n) => r(t, n, e);
231
+ var me = Object.defineProperty, _e = Object.getOwnPropertyDescriptor, ve = (e, t, r, n) => {
232
+ for (var s = n > 1 ? void 0 : n ? _e(t, r) : t, o = e.length - 1, i; o >= 0; o--)
233
+ (i = e[o]) && (s = (n ? i(t, r, s) : i(s)) || s);
234
+ return n && s && me(t, r, s), s;
235
+ }, Ee = (e, t) => (r, n) => t(r, n, e);
233
236
  let N = class {
234
237
  constructor(e) {
235
238
  this._logService = e;
236
239
  }
237
240
  send(e) {
238
- return new m((r) => {
239
- const t = new AbortController();
240
- return this._send(e, r, t).catch((n) => {
241
- r.error(new _({
241
+ return new m((t) => {
242
+ const r = new AbortController();
243
+ return this._send(e, t, r).catch((n) => {
244
+ t.error(new _({
242
245
  error: n,
243
246
  request: e
244
247
  }));
245
- }), () => t.abort();
248
+ }), () => r.abort();
246
249
  });
247
250
  }
248
- async _send(e, r, t) {
251
+ async _send(e, t, r) {
249
252
  var a, h;
250
253
  let n;
251
254
  try {
252
255
  const l = Q(e), y = e.getUrlWithParams(), p = fetch(y, {
253
- signal: t.signal,
256
+ signal: r.signal,
254
257
  ...l
255
258
  });
256
259
  this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${y} with params ${l}`), n = await p;
@@ -262,13 +265,13 @@ let N = class {
262
265
  statusText: (h = l.statusText) != null ? h : "Unknown Error",
263
266
  headers: l.headers
264
267
  });
265
- this._logService.error("[FetchHTTPImplementation]: network error", y), r.error(y);
268
+ this._logService.error("[FetchHTTPImplementation]: network error", y), t.error(y);
266
269
  return;
267
270
  }
268
271
  const s = new I(n.headers), o = n.status, i = n.statusText;
269
272
  let c = null;
270
- if (n.body && (c = await this._readBody(e, n, r)), o >= L.Ok && o < L.MultipleChoices)
271
- r.next(new $({
273
+ if (n.body && (c = await this._readBody(e, n, t)), o >= L.Ok && o < L.MultipleChoices)
274
+ t.next(new $({
272
275
  body: c,
273
276
  headers: s,
274
277
  status: o,
@@ -282,20 +285,20 @@ let N = class {
282
285
  statusText: i,
283
286
  headers: s
284
287
  });
285
- this._logService.error("[FetchHTTPImplementation]: network error", l), r.error(l);
288
+ this._logService.error("[FetchHTTPImplementation]: network error", l), t.error(l);
286
289
  }
287
- r.complete();
290
+ t.complete();
288
291
  }
289
- async _readBody(e, r, t) {
292
+ async _readBody(e, t, r) {
290
293
  var y, p;
291
- const n = [], s = r.body.getReader(), o = r.headers.get("content-length");
294
+ const n = [], s = t.body.getReader(), o = t.headers.get("content-length");
292
295
  let i = 0;
293
296
  const c = (y = e.requestParams) == null ? void 0 : y.reportProgress, w = e.responseType;
294
297
  let a, h;
295
298
  for (; ; ) {
296
299
  const { done: u, value: g } = await s.read();
297
300
  if (u) break;
298
- n.push(g), i += g.length, c && w === "text" && (a = (a != null ? a : "") + (h != null ? h : h = new TextDecoder()).decode(g, { stream: !0 }), t.next(new we(
301
+ n.push(g), i += g.length, c && w === "text" && (a = (a != null ? a : "") + (h != null ? h : h = new TextDecoder()).decode(g, { stream: !0 }), r.next(new we(
299
302
  o ? Number.parseInt(o, 10) : void 0,
300
303
  i,
301
304
  a
@@ -303,66 +306,66 @@ let N = class {
303
306
  }
304
307
  const l = Re(n, i);
305
308
  try {
306
- const u = (p = r.headers.get("content-type")) != null ? p : "";
309
+ const u = (p = t.headers.get("content-type")) != null ? p : "";
307
310
  return be(e, l, u);
308
311
  } catch (u) {
309
312
  const g = new _({
310
313
  request: e,
311
314
  error: u,
312
- status: r.status,
313
- statusText: r.statusText,
314
- headers: new I(r.headers)
315
+ status: t.status,
316
+ statusText: t.statusText,
317
+ headers: new I(t.headers)
315
318
  });
316
- return this._logService.error("[FetchHTTPImplementation]: network error", g), t.error(g), null;
319
+ return this._logService.error("[FetchHTTPImplementation]: network error", g), r.error(g), null;
317
320
  }
318
321
  }
319
322
  };
320
323
  N = ve([
321
324
  Ee(0, D)
322
325
  ], N);
323
- function Re(e, r) {
324
- const t = new Uint8Array(r);
326
+ function Re(e, t) {
327
+ const r = new Uint8Array(t);
325
328
  let n = 0;
326
329
  for (const s of e)
327
- t.set(s, n), n += s.length;
328
- return t;
330
+ r.set(s, n), n += s.length;
331
+ return r;
329
332
  }
330
333
  const Ie = /^\)\]\}',?\n/;
331
- function be(e, r, t) {
334
+ function be(e, t, r) {
332
335
  switch (e.responseType) {
333
336
  case "json":
334
- const n = new TextDecoder().decode(r).replace(Ie, "");
337
+ const n = new TextDecoder().decode(t).replace(Ie, "");
335
338
  return n === "" ? null : JSON.parse(n);
336
339
  case "text":
337
- return new TextDecoder().decode(r);
340
+ return new TextDecoder().decode(t);
338
341
  case "blob":
339
- return new Blob([r], { type: t });
342
+ return new Blob([t], { type: r });
340
343
  case "arraybuffer":
341
- return r.buffer;
344
+ return t.buffer;
342
345
  default:
343
346
  throw new Error(`[FetchHTTPImplementation]: unknown response type: ${e.responseType}.`);
344
347
  }
345
348
  }
346
- var xe = Object.defineProperty, Le = Object.getOwnPropertyDescriptor, Ne = (e, r, t, n) => {
347
- for (var s = n > 1 ? void 0 : n ? Le(r, t) : r, o = e.length - 1, i; o >= 0; o--)
348
- (i = e[o]) && (s = (n ? i(r, t, s) : i(s)) || s);
349
- return n && s && xe(r, t, s), s;
350
- }, Fe = (e, r) => (t, n) => r(t, n, e);
349
+ var xe = Object.defineProperty, Le = Object.getOwnPropertyDescriptor, Ne = (e, t, r, n) => {
350
+ for (var s = n > 1 ? void 0 : n ? Le(t, r) : t, o = e.length - 1, i; o >= 0; o--)
351
+ (i = e[o]) && (s = (n ? i(t, r, s) : i(s)) || s);
352
+ return n && s && xe(t, r, s), s;
353
+ }, Ae = (e, t) => (r, n) => t(r, n, e);
351
354
  let U = class {
352
355
  constructor(e) {
353
356
  this._logService = e;
354
357
  }
355
358
  send(e) {
356
- return new m((r) => {
357
- const t = new XMLHttpRequest(), n = e.getUrlWithParams(), s = Q(e);
358
- t.open(e.method, n), e.withCredentials && (t.withCredentials = !0), s.headers && Object.entries(s.headers).forEach(([a, h]) => t.setRequestHeader(a, h));
359
+ return new m((t) => {
360
+ const r = new XMLHttpRequest(), n = e.getUrlWithParams(), s = Q(e);
361
+ r.open(e.method, n), e.withCredentials && (r.withCredentials = !0), s.headers && Object.entries(s.headers).forEach(([a, h]) => r.setRequestHeader(a, h));
359
362
  const o = () => {
360
- const a = t.statusText || "OK", h = new I(t.getAllResponseHeaders());
361
- return new ye(h, t.status, a);
363
+ const a = r.statusText || "OK", h = new I(r.getAllResponseHeaders());
364
+ return new ye(h, r.status, a);
362
365
  }, i = () => {
363
366
  const { headers: a, statusText: h, status: l } = o(), { responseType: y } = e;
364
367
  let p = null, u = null;
365
- l !== L.NoContent && (p = typeof t.response > "u" ? t.responseText : t.response);
368
+ l !== L.NoContent && (p = typeof r.response > "u" ? r.responseText : r.response);
366
369
  let g = l >= fe && l < ge;
367
370
  if (y === "json" && typeof p == "string") {
368
371
  const f = p;
@@ -373,7 +376,7 @@ let U = class {
373
376
  }
374
377
  }
375
378
  if (g)
376
- r.next(
379
+ t.next(
377
380
  new $({
378
381
  body: p,
379
382
  headers: a,
@@ -389,103 +392,103 @@ let U = class {
389
392
  status: l,
390
393
  statusText: h
391
394
  });
392
- this._logService.error("[XHRHTTPImplementation]: network error", f), r.error(f);
395
+ this._logService.error("[XHRHTTPImplementation]: network error", f), t.error(f);
393
396
  }
394
397
  }, c = (a) => {
395
398
  const h = new _({
396
399
  request: e,
397
400
  error: a,
398
- status: t.status || 0,
399
- statusText: t.statusText || "Unknown Error",
401
+ status: r.status || 0,
402
+ statusText: r.statusText || "Unknown Error",
400
403
  headers: o().headers
401
404
  });
402
- this._logService.error("[XHRHTTPImplementation]: network error", h), r.error(h);
405
+ this._logService.error("[XHRHTTPImplementation]: network error", h), t.error(h);
403
406
  };
404
- t.addEventListener("load", i), t.addEventListener("error", c), t.addEventListener("abort", c), t.addEventListener("timeout", c);
407
+ r.addEventListener("load", i), r.addEventListener("error", c), r.addEventListener("abort", c), r.addEventListener("timeout", c);
405
408
  const w = e.getBody();
406
- return t.send(w), this._logService.debug(`[XHRHTTPImplementation]: sending request to url ${n} with params ${s}`), () => {
407
- t.readyState !== t.DONE && t.abort(), t.removeEventListener("load", i), t.removeEventListener("error", c), t.removeEventListener("abort", c), t.removeEventListener("timeout", c);
409
+ return r.send(w), this._logService.debug(`[XHRHTTPImplementation]: sending request to url ${n} with params ${s}`), () => {
410
+ r.readyState !== r.DONE && r.abort(), r.removeEventListener("load", i), r.removeEventListener("error", c), r.removeEventListener("abort", c), r.removeEventListener("timeout", c);
408
411
  };
409
412
  });
410
413
  }
411
414
  };
412
415
  U = Ne([
413
- Fe(0, D)
416
+ Ae(0, D)
414
417
  ], U);
415
- var Oe = Object.defineProperty, Ae = Object.getOwnPropertyDescriptor, Ue = (e, r, t, n) => {
416
- for (var s = n > 1 ? void 0 : n ? Ae(r, t) : r, o = e.length - 1, i; o >= 0; o--)
417
- (i = e[o]) && (s = (n ? i(r, t, s) : i(s)) || s);
418
- return n && s && Oe(r, t, s), s;
419
- }, W = (e, r) => (t, n) => r(t, n, e), A;
420
- let X = (A = class extends C {
421
- constructor(e = void 0, r, t) {
422
- super(), this._config = e, this._logger = r, this._injector = t;
418
+ var Fe = Object.defineProperty, Oe = Object.getOwnPropertyDescriptor, Ue = (e, t, r, n) => {
419
+ for (var s = n > 1 ? void 0 : n ? Oe(t, r) : t, o = e.length - 1, i; o >= 0; o--)
420
+ (i = e[o]) && (s = (n ? i(t, r, s) : i(s)) || s);
421
+ return n && s && Fe(t, r, s), s;
422
+ }, W = (e, t) => (r, n) => t(r, n, e), O;
423
+ let X = (O = class extends C {
424
+ constructor(e = void 0, t, r) {
425
+ super(), this._config = e, this._logger = t, this._injector = r;
423
426
  }
424
427
  onStarting() {
425
- var t, n, s;
426
- if (this._injector.get(x, T.OPTIONAL, ee.SKIP_SELF) && !((t = this._config) != null && t.forceUseNewInstance)) {
428
+ var r, n, s;
429
+ if (this._injector.get(x, T.OPTIONAL, ee.SKIP_SELF) && !((r = this._config) != null && r.forceUseNewInstance)) {
427
430
  this._logger.warn(
428
431
  "[UniverNetworkPlugin]",
429
432
  'HTTPService is already registered in an ancestor interceptor. Skipping registration. If you want to force a new instance, set "forceUseNewInstance" to true in the plugin configuration.'
430
433
  );
431
434
  return;
432
435
  }
433
- const r = (n = this._config) != null && n.useFetchImpl ? N : typeof window < "u" ? U : N;
436
+ const t = (n = this._config) != null && n.useFetchImpl ? N : typeof window < "u" ? U : N;
434
437
  re(this._injector, te([
435
438
  [x],
436
- [K, { useClass: r }]
439
+ [K, { useClass: t }]
437
440
  ], (s = this._config) == null ? void 0 : s.override));
438
441
  }
439
- }, d(A, "pluginName", "UNIVER_NETWORK_PLUGIN"), A);
442
+ }, d(O, "pluginName", "UNIVER_NETWORK_PLUGIN"), O);
440
443
  X = Ue([
441
444
  W(1, D),
442
445
  W(2, S(H))
443
446
  ], X);
444
447
  const We = V("univer.network.socket.service");
445
448
  class Xe extends z {
446
- createSocket(r) {
449
+ createSocket(t) {
447
450
  try {
448
- const t = new WebSocket(r), n = new ne();
451
+ const r = new WebSocket(t), n = new ne();
449
452
  return {
450
- URL: r,
453
+ URL: t,
451
454
  close: (o, i) => {
452
- t.close(o, i), n.dispose();
455
+ r.close(o, i), n.dispose();
453
456
  },
454
457
  send: (o) => {
455
- t.send(o);
458
+ r.send(o);
456
459
  },
457
460
  open$: new m((o) => {
458
461
  const i = (c) => o.next(c);
459
- t.addEventListener("open", i), n.add(R(() => t.removeEventListener("open", i)));
462
+ r.addEventListener("open", i), n.add(R(() => r.removeEventListener("open", i)));
460
463
  }).pipe(b()),
461
464
  close$: new m((o) => {
462
465
  const i = (c) => o.next(c);
463
- t.addEventListener("close", i), n.add(R(() => t.removeEventListener("close", i)));
466
+ r.addEventListener("close", i), n.add(R(() => r.removeEventListener("close", i)));
464
467
  }).pipe(b()),
465
468
  error$: new m((o) => {
466
469
  const i = (c) => o.next(c);
467
- t.addEventListener("error", i), n.add(R(() => t.removeEventListener("error", i)));
470
+ r.addEventListener("error", i), n.add(R(() => r.removeEventListener("error", i)));
468
471
  }).pipe(b()),
469
472
  message$: new m((o) => {
470
473
  const i = (c) => o.next(c);
471
- t.addEventListener("message", i), n.add(R(() => t.removeEventListener("message", i)));
474
+ r.addEventListener("message", i), n.add(R(() => r.removeEventListener("message", i)));
472
475
  }).pipe(b())
473
476
  };
474
- } catch (t) {
475
- return console.error(t), null;
477
+ } catch (r) {
478
+ return console.error(r), null;
476
479
  }
477
480
  }
478
481
  }
479
482
  const De = 3, $e = 1e3, Ve = (e) => {
480
483
  var n, s;
481
- const r = (n = e == null ? void 0 : e.maxRetryAttempts) != null ? n : De, t = (s = e == null ? void 0 : e.delayInterval) != null ? s : $e;
482
- return (o, i) => i(o).pipe(ce({ delay: t, count: r }));
484
+ const t = (n = e == null ? void 0 : e.maxRetryAttempts) != null ? n : De, r = (s = e == null ? void 0 : e.delayInterval) != null ? s : $e;
485
+ return (o, i) => i(o).pipe(ce({ delay: r, count: t }));
483
486
  }, ze = (e) => {
484
- const r = [], t = /* @__PURE__ */ new Set(), n = () => {
487
+ const t = [], r = /* @__PURE__ */ new Set(), n = () => {
485
488
  var s;
486
- for (; t.size < ((s = e == null ? void 0 : e.maxParallel) != null ? s : 1) && r.length > 0; ) {
487
- const o = r.shift();
488
- t.add(o), o();
489
+ for (; r.size < ((s = e == null ? void 0 : e.maxParallel) != null ? s : 1) && t.length > 0; ) {
490
+ const o = t.shift();
491
+ r.add(o), o();
489
492
  }
490
493
  };
491
494
  return (s, o) => new m((i) => {
@@ -494,30 +497,30 @@ const De = 3, $e = 1e3, Ve = (e) => {
494
497
  error: (a) => i.error(a),
495
498
  complete: () => i.complete()
496
499
  }), w = () => {
497
- t.delete(c), J(r, c), n();
500
+ r.delete(c), J(t, c), n();
498
501
  };
499
- return r.push(c), n(), w;
502
+ return t.push(c), n(), w;
500
503
  });
501
504
  }, Je = (e) => {
502
- const { errorStatusCodes: r, onAuthError: t } = e;
505
+ const { errorStatusCodes: t, onAuthError: r } = e;
503
506
  return (s, o) => o(s).pipe(
504
- oe((i) => (i instanceof _ && r.some((c) => c === i.status) && t(), ie(() => i)))
507
+ oe((i) => (i instanceof _ && t.some((c) => c === i.status) && r(), ie(() => i)))
505
508
  );
506
509
  }, je = (e = 300) => {
507
- let t = () => {
510
+ let r = () => {
508
511
  };
509
512
  return (n) => new Promise((s) => {
510
- t();
513
+ r();
511
514
  const o = setTimeout(() => {
512
515
  s(!0);
513
516
  }, e);
514
- t = () => {
517
+ r = () => {
515
518
  clearTimeout(o), s(!1);
516
519
  };
517
520
  });
518
- }, qe = () => (e, r) => r.map((t) => ({ config: t, result: e })), Ke = (e, r = {}) => {
519
- const { isMatch: t, getParamsFromRequest: n, mergeParamsToRequest: s } = e, { fetchCheck: o = je(300), distributeResult: i = qe() } = r, c = [], w = (a) => a.map((h) => h.config);
520
- return (a, h) => t(a) ? new m((l) => {
521
+ }, qe = () => (e, t) => t.map((r) => ({ config: r, result: e })), Ke = (e, t = {}) => {
522
+ const { isMatch: r, getParamsFromRequest: n, mergeParamsToRequest: s } = e, { fetchCheck: o = je(300), distributeResult: i = qe() } = t, c = [], w = (a) => a.map((h) => h.config);
523
+ return (a, h) => r(a) ? new m((l) => {
521
524
  const y = n(a);
522
525
  c.push({
523
526
  next: (u) => l.next(u),
@@ -538,18 +541,18 @@ const De = 3, $e = 1e3, Ve = (e) => {
538
541
  next: (f) => {
539
542
  if (f.type === Y.Response) {
540
543
  const v = f.body, E = i(v, p);
541
- g.forEach((F) => {
542
- const j = E.find((O) => O.config === F.config);
544
+ g.forEach((A) => {
545
+ const j = E.find((F) => F.config === A.config);
543
546
  if (j) {
544
- const O = new $({
547
+ const F = new $({
545
548
  body: j.result,
546
549
  headers: f.headers,
547
550
  status: f.status,
548
551
  statusText: f.statusText
549
552
  });
550
- F.next(O);
553
+ A.next(F);
551
554
  } else
552
- F.error("batch error");
555
+ A.error("batch error");
553
556
  });
554
557
  }
555
558
  },
@@ -1,52 +1,59 @@
1
1
  import { HTTPEvent, HTTPRequestMethod, HTTPResponse, IPostRequestParams, IRequestParams, HTTPService } from '@univerjs/network';
2
2
  import { Observable } from 'rxjs';
3
3
  import { FBase, Injector } from '@univerjs/core';
4
+ /**
5
+ * This Facade provides a set of methods to make HTTP requests. You should not
6
+ * create an instance of this class directly, instead, use `getNetwork` of
7
+ * {@link FUniver} instead.
8
+ *
9
+ * @hideconstructor
10
+ */
4
11
  export declare class FNetwork extends FBase {
5
12
  protected readonly _injector: Injector;
6
13
  protected readonly _httpService: HTTPService;
7
14
  constructor(_injector: Injector, _httpService: HTTPService);
8
15
  /**
9
- * Send GET request to the server.
10
- * @param url The requested URL
11
- * @param params Query parameters
12
- * @returns Network response
16
+ * Send a GET request to the server.
17
+ * @param {string} url - The requested URL.
18
+ * @param {IRequestParams} [params] - Query parameters.
19
+ * @returns {Promise<HTTPResponse>} Network response.
13
20
  */
14
21
  get<T>(url: string, params?: IRequestParams): Promise<HTTPResponse<T>>;
15
22
  /**
16
- * Send POST request to the server.
17
- * @param url The requested URL
18
- * @param params Query parameters
19
- * @returns Network response
23
+ * Send a POST request to the server.
24
+ * @param {string} url - The requested URL.
25
+ * @param {IPostRequestParams} [params] - Query parameters.
26
+ * @returns {Promise<HTTPResponse>} Network response.
20
27
  */
21
28
  post<T>(url: string, params?: IPostRequestParams): Promise<HTTPResponse<T>>;
22
29
  /**
23
- * Send PUT request to the server.
24
- * @param url The requested URL
25
- * @param params Query parameters
26
- * @returns Network response
30
+ * Send a PUT request to the server.
31
+ * @param {string} url - The requested URL
32
+ * @param {IPostRequestParams} [params] - Query parameters
33
+ * @returns {Promise<HTTPResponse>} Network response
27
34
  */
28
35
  put<T>(url: string, params?: IPostRequestParams): Promise<HTTPResponse<T>>;
29
36
  /**
30
37
  * Send DELETE request to the server.
31
- * @param url The requested URL
32
- * @param params Query parameters
33
- * @returns Network response
38
+ * @param {string} url - The requested URL
39
+ * @param {IRequestParams} [params] - Query parameters
40
+ * @returns {Promise<HTTPResponse>} Network response
34
41
  */
35
42
  delete<T>(url: string, params?: IRequestParams): Promise<HTTPResponse<T>>;
36
43
  /**
37
44
  * Send PATCH request to the server.
38
- * @param url The requested URL
39
- * @param params Query parameters
40
- * @returns Network response
45
+ * @param {string} url - The requested URL
46
+ * @param {IPostRequestParams} [params] - Query parameters
47
+ * @returns {Promise<HTTPResponse>} Network response
41
48
  */
42
49
  patch<T>(url: string, params?: IPostRequestParams): Promise<HTTPResponse<T>>;
43
50
  /**
44
51
  * Request for a stream of server-sent events. Instead of a single response, the server sends a stream of responses,
45
52
  * Univer wraps the stream in an [`Observable`](https://rxjs.dev/guide/observable) which you can call `subscribe` on.
46
- * @param method HTTP request method
47
- * @param url The requested URL
48
- * @param params Query parameters
49
- * @returns An observable that emits the network response
53
+ * @param {HTTPRequestMethod} method - HTTP request method
54
+ * @param {string} url - The requested URL
55
+ * @param {IPostRequestParams} [params] - params Query parameters
56
+ * @returns {Observable<HTTPEvent>} An observable that emits the network response.
50
57
  */
51
58
  getSSE<T>(method: HTTPRequestMethod, url: string, params?: IPostRequestParams): Observable<HTTPEvent<T>>;
52
59
  }
@@ -1,5 +1,8 @@
1
1
  import { FUniver } from '@univerjs/core';
2
2
  import { FNetwork } from './f-network';
3
+ /**
4
+ * @ignore
5
+ */
3
6
  interface IFUniverNetworkMixin {
4
7
  /**
5
8
  * Get the network API of Univer, with the help of which you can send HTTP requests.
@@ -13,12 +13,14 @@
13
13
  * See the License for the specific language governing permissions and
14
14
  * limitations under the License.
15
15
  */
16
+ type ValidParamType = string | number | boolean;
16
17
  export declare class HTTPParams {
17
18
  readonly params?: {
18
- [key: string]: string | number | boolean;
19
+ [key: string]: ValidParamType | ValidParamType[];
19
20
  } | undefined;
20
21
  constructor(params?: {
21
- [key: string]: string | number | boolean;
22
+ [key: string]: ValidParamType | ValidParamType[];
22
23
  } | undefined);
23
24
  toString(): string;
24
25
  }
26
+ export {};
package/lib/umd/index.js CHANGED
@@ -1,2 +1,2 @@
1
- (function(c,a){typeof exports=="object"&&typeof module<"u"?a(exports,require("@univerjs/core"),require("rxjs"),require("rxjs/operators")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","rxjs","rxjs/operators"],a):(c=typeof globalThis<"u"?globalThis:c||self,a(c.UniverNetwork={},c.UniverCore,c.rxjs,c.rxjs.operators))})(this,function(c,a,y,R){"use strict";var ve=Object.defineProperty;var Ie=(c,a,y)=>a in c?ve(c,a,{enumerable:!0,configurable:!0,writable:!0,value:y}):c[a]=y;var w=(c,a,y)=>Ie(c,typeof a!="symbol"?a+"":a,y);var D;const $="application/json";class L{constructor(n){w(this,"_headers",new Map);typeof n=="string"?this._handleHeadersString(n):n instanceof Headers?this._handleHeaders(n):n&&this._handleHeadersConstructorProps(n)}forEach(n){this._headers.forEach((t,r)=>n(r,t))}has(n){return!!this._headers.has(n.toLowerCase())}get(n){const t=n.toLowerCase();return this._headers.has(t)?this._headers.get(t):null}set(n,t){this._setHeader(n,t)}toHeadersInit(){var t,r;const n={};return this._headers.forEach((s,i)=>{n[i]=s.join(",")}),(t=n.accept)!=null||(n.accept="application/json, text/plain, */*"),(r=n["content-type"])!=null||(n["content-type"]="application/json;charset=UTF-8"),n}_setHeader(n,t){const r=n.toLowerCase();this._headers.has(r)?this._headers.get(r).push(t.toString()):this._headers.set(r,[t.toString()])}_handleHeadersString(n){n.split(`
2
- `).forEach(t=>{const[r,s]=t.split(":");r&&s&&this._setHeader(r,s)})}_handleHeadersConstructorProps(n){Object.entries(n).forEach(([t,r])=>this._setHeader(t,r))}_handleHeaders(n){n.forEach((t,r)=>this._setHeader(r,t))}}const O=a.createIdentifier("network.http-implementation");class M{constructor(n){this.params=n}toString(){return this.params?Object.keys(this.params).map(n=>`${n}=${this.params[n]}`).join("&"):""}}let W=0;class U{constructor(n,t,r){w(this,"uid",W++);this.method=n,this.url=t,this.requestParams=r}get headers(){return this.requestParams.headers}get withCredentials(){return this.requestParams.withCredentials}get responseType(){return this.requestParams.responseType}getUrlWithParams(){var t,r;const n=(r=(t=this.requestParams)==null?void 0:t.params)==null?void 0:r.toString();return n?`${this.url}${this.url.includes("?")?"&":"?"}${n}`:this.url}getBody(){var r,s;const n=(r=this.headers.get("Content-Type"))!=null?r:$,t=(s=this.requestParams)==null?void 0:s.body;return n===$&&t&&typeof t=="object"?JSON.stringify(t):t?`${t}`:null}getHeadersInit(){return this.headers.toHeadersInit()}}var V=Object.defineProperty,P=Object.getOwnPropertyDescriptor,z=(e,n,t,r)=>{for(var s=r>1?void 0:r?P(n,t):n,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=(r?o(n,t,s):o(s))||s);return r&&s&&V(n,t,s),s},J=(e,n)=>(t,r)=>n(t,r,e);c.HTTPService=class extends a.Disposable{constructor(t){super();w(this,"_interceptors",[]);w(this,"_pipe");this._http=t}registerHTTPInterceptor(t){if(this._interceptors.indexOf(t)!==-1)throw new Error("[HTTPService]: The interceptor has already been registered!");return this._interceptors.push(t),this._interceptors=this._interceptors.sort((r,s)=>{var i,o;return((i=r.priority)!=null?i:0)-((o=s.priority)!=null?o:0)}),this._pipe=null,a.toDisposable(()=>a.remove(this._interceptors,t))}get(t,r){return this._request("GET",t,r)}post(t,r){return this._request("POST",t,r)}put(t,r){return this._request("PUT",t,r)}delete(t,r){return this._request("DELETE",t,r)}patch(t,r){return this._request("PATCH",t,r)}getSSE(t,r,s){var u,f;const i=new L(s==null?void 0:s.headers),o=new M(s==null?void 0:s.params),l=new U(t,r,{headers:i,params:o,withCredentials:(u=s==null?void 0:s.withCredentials)!=null?u:!1,reportProgress:!0,responseType:(f=s==null?void 0:s.responseType)!=null?f:"json",body:["GET","DELETE"].includes(t)||s==null?void 0:s.body});return y.of(l).pipe(R.concatMap(h=>this._runInterceptorsAndImplementation(h)))}async _request(t,r,s){var h,d;const i=new L(s==null?void 0:s.headers),o=new M(s==null?void 0:s.params),l=new U(t,r,{headers:i,params:o,withCredentials:(h=s==null?void 0:s.withCredentials)!=null?h:!1,responseType:(d=s==null?void 0:s.responseType)!=null?d:"json",body:["GET","DELETE"].includes(t)||s==null?void 0:s.body}),u=y.of(l).pipe(R.concatMap(p=>this._runInterceptorsAndImplementation(p)));return await y.firstValueFrom(u)}_runInterceptorsAndImplementation(t){return this._pipe||(this._pipe=this._interceptors.map(r=>r.interceptor).reduceRight((r,s)=>K(r,s),(r,s)=>s(r))),this._pipe(t,r=>this._http.send(r))}},c.HTTPService=z([J(0,O)],c.HTTPService);function K(e,n){return(t,r)=>n(t,s=>e(s,r))}const Y=200,Q=300;var F=(e=>(e[e.Continue=100]="Continue",e[e.SwitchingProtocols=101]="SwitchingProtocols",e[e.Processing=102]="Processing",e[e.EarlyHints=103]="EarlyHints",e[e.Ok=200]="Ok",e[e.Created=201]="Created",e[e.Accepted=202]="Accepted",e[e.NonAuthoritativeInformation=203]="NonAuthoritativeInformation",e[e.NoContent=204]="NoContent",e[e.ResetContent=205]="ResetContent",e[e.PartialContent=206]="PartialContent",e[e.MultiStatus=207]="MultiStatus",e[e.AlreadyReported=208]="AlreadyReported",e[e.ImUsed=226]="ImUsed",e[e.MultipleChoices=300]="MultipleChoices",e[e.MovedPermanently=301]="MovedPermanently",e[e.Found=302]="Found",e[e.SeeOther=303]="SeeOther",e[e.NotModified=304]="NotModified",e[e.UseProxy=305]="UseProxy",e[e.Unused=306]="Unused",e[e.TemporaryRedirect=307]="TemporaryRedirect",e[e.PermanentRedirect=308]="PermanentRedirect",e[e.BadRequest=400]="BadRequest",e[e.Unauthorized=401]="Unauthorized",e[e.PaymentRequired=402]="PaymentRequired",e[e.Forbidden=403]="Forbidden",e[e.NotFound=404]="NotFound",e[e.MethodNotAllowed=405]="MethodNotAllowed",e[e.NotAcceptable=406]="NotAcceptable",e[e.ProxyAuthenticationRequired=407]="ProxyAuthenticationRequired",e[e.RequestTimeout=408]="RequestTimeout",e[e.Conflict=409]="Conflict",e[e.Gone=410]="Gone",e[e.LengthRequired=411]="LengthRequired",e[e.PreconditionFailed=412]="PreconditionFailed",e[e.PayloadTooLarge=413]="PayloadTooLarge",e[e.UriTooLong=414]="UriTooLong",e[e.UnsupportedMediaType=415]="UnsupportedMediaType",e[e.RangeNotSatisfiable=416]="RangeNotSatisfiable",e[e.ExpectationFailed=417]="ExpectationFailed",e[e.ImATeapot=418]="ImATeapot",e[e.MisdirectedRequest=421]="MisdirectedRequest",e[e.UnprocessableEntity=422]="UnprocessableEntity",e[e.Locked=423]="Locked",e[e.FailedDependency=424]="FailedDependency",e[e.TooEarly=425]="TooEarly",e[e.UpgradeRequired=426]="UpgradeRequired",e[e.PreconditionRequired=428]="PreconditionRequired",e[e.TooManyRequests=429]="TooManyRequests",e[e.RequestHeaderFieldsTooLarge=431]="RequestHeaderFieldsTooLarge",e[e.UnavailableForLegalReasons=451]="UnavailableForLegalReasons",e[e.InternalServerError=500]="InternalServerError",e[e.NotImplemented=501]="NotImplemented",e[e.BadGateway=502]="BadGateway",e[e.ServiceUnavailable=503]="ServiceUnavailable",e[e.GatewayTimeout=504]="GatewayTimeout",e[e.HttpVersionNotSupported=505]="HttpVersionNotSupported",e[e.VariantAlsoNegotiates=506]="VariantAlsoNegotiates",e[e.InsufficientStorage=507]="InsufficientStorage",e[e.LoopDetected=508]="LoopDetected",e[e.NotExtended=510]="NotExtended",e[e.NetworkAuthenticationRequired=511]="NetworkAuthenticationRequired",e))(F||{}),A=(e=>(e[e.DownloadProgress=0]="DownloadProgress",e[e.Response=1]="Response",e))(A||{});class N{constructor({body:n,headers:t,status:r,statusText:s}){w(this,"type",1);w(this,"body");w(this,"headers");w(this,"status");w(this,"statusText");this.body=n,this.headers=t,this.status=r,this.statusText=s}}class j{constructor(n,t,r){w(this,"type",0);this.total=n,this.loaded=t,this.partialText=r}}class x{constructor(n,t,r){this.headers=n,this.status=t,this.statusText=r}}class b{constructor({request:n,headers:t,status:r,statusText:s,error:i}){w(this,"request");w(this,"headers");w(this,"status");w(this,"statusText");w(this,"error");this.request=n,this.headers=t,this.status=r,this.statusText=s,this.error=i}}function B(e){return{method:e.method,headers:e.getHeadersInit(),body:e.getBody(),credentials:e.withCredentials?"include":void 0}}var Z=Object.defineProperty,H=Object.getOwnPropertyDescriptor,S=(e,n,t,r)=>{for(var s=r>1?void 0:r?H(n,t):n,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=(r?o(n,t,s):o(s))||s);return r&&s&&Z(n,t,s),s},C=(e,n)=>(t,r)=>n(t,r,e);c.FetchHTTPImplementation=class{constructor(n){this._logService=n}send(n){return new y.Observable(t=>{const r=new AbortController;return this._send(n,t,r).catch(s=>{t.error(new b({error:s,request:n}))}),()=>r.abort()})}async _send(n,t,r){var h,d;let s;try{const p=B(n),v=n.getUrlWithParams(),m=fetch(v,{signal:r.signal,...p});this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${v} with params ${p}`),s=await m}catch(p){const v=new b({request:n,error:p,status:(h=p.status)!=null?h:0,statusText:(d=p.statusText)!=null?d:"Unknown Error",headers:p.headers});this._logService.error("[FetchHTTPImplementation]: network error",v),t.error(v);return}const i=new L(s.headers),o=s.status,l=s.statusText;let u=null;if(s.body&&(u=await this._readBody(n,s,t)),o>=F.Ok&&o<F.MultipleChoices)t.next(new N({body:u,headers:i,status:o,statusText:l}));else{const p=new b({request:n,error:u,status:o,statusText:l,headers:i});this._logService.error("[FetchHTTPImplementation]: network error",p),t.error(p)}t.complete()}async _readBody(n,t,r){var v,m;const s=[],i=t.body.getReader(),o=t.headers.get("content-length");let l=0;const u=(v=n.requestParams)==null?void 0:v.reportProgress,f=n.responseType;let h,d;for(;;){const{done:I,value:g}=await i.read();if(I)break;s.push(g),l+=g.length,u&&f==="text"&&(h=(h!=null?h:"")+(d!=null?d:d=new TextDecoder).decode(g,{stream:!0}),r.next(new j(o?Number.parseInt(o,10):void 0,l,h)))}const p=T(s,l);try{const I=(m=t.headers.get("content-type"))!=null?m:"";return te(n,p,I)}catch(I){const g=new b({request:n,error:I,status:t.status,statusText:t.statusText,headers:new L(t.headers)});return this._logService.error("[FetchHTTPImplementation]: network error",g),r.error(g),null}}},c.FetchHTTPImplementation=S([C(0,a.ILogService)],c.FetchHTTPImplementation);function T(e,n){const t=new Uint8Array(n);let r=0;for(const s of e)t.set(s,r),r+=s.length;return t}const ee=/^\)\]\}',?\n/;function te(e,n,t){switch(e.responseType){case"json":const r=new TextDecoder().decode(n).replace(ee,"");return r===""?null:JSON.parse(r);case"text":return new TextDecoder().decode(n);case"blob":return new Blob([n],{type:t});case"arraybuffer":return n.buffer;default:throw new Error(`[FetchHTTPImplementation]: unknown response type: ${e.responseType}.`)}}var re=Object.defineProperty,ne=Object.getOwnPropertyDescriptor,se=(e,n,t,r)=>{for(var s=r>1?void 0:r?ne(n,t):n,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=(r?o(n,t,s):o(s))||s);return r&&s&&re(n,t,s),s},ie=(e,n)=>(t,r)=>n(t,r,e);c.XHRHTTPImplementation=class{constructor(n){this._logService=n}send(n){return new y.Observable(t=>{const r=new XMLHttpRequest,s=n.getUrlWithParams(),i=B(n);r.open(n.method,s),n.withCredentials&&(r.withCredentials=!0),i.headers&&Object.entries(i.headers).forEach(([h,d])=>r.setRequestHeader(h,d));const o=()=>{const h=r.statusText||"OK",d=new L(r.getAllResponseHeaders());return new x(d,r.status,h)},l=()=>{const{headers:h,statusText:d,status:p}=o(),{responseType:v}=n;let m=null,I=null;p!==F.NoContent&&(m=typeof r.response>"u"?r.responseText:r.response);let g=p>=Y&&p<Q;if(v==="json"&&typeof m=="string"){const _=m;try{m=m?JSON.parse(m):null}catch(E){g=!1,m=_,I=E}}if(g)t.next(new N({body:m,headers:h,status:p,statusText:d}));else{const _=new b({request:n,error:I,headers:h,status:p,statusText:d});this._logService.error("[XHRHTTPImplementation]: network error",_),t.error(_)}},u=h=>{const d=new b({request:n,error:h,status:r.status||0,statusText:r.statusText||"Unknown Error",headers:o().headers});this._logService.error("[XHRHTTPImplementation]: network error",d),t.error(d)};r.addEventListener("load",l),r.addEventListener("error",u),r.addEventListener("abort",u),r.addEventListener("timeout",u);const f=n.getBody();return r.send(f),this._logService.debug(`[XHRHTTPImplementation]: sending request to url ${s} with params ${i}`),()=>{r.readyState!==r.DONE&&r.abort(),r.removeEventListener("load",l),r.removeEventListener("error",u),r.removeEventListener("abort",u),r.removeEventListener("timeout",u)}})}},c.XHRHTTPImplementation=se([ie(0,a.ILogService)],c.XHRHTTPImplementation);var oe=Object.defineProperty,ce=Object.getOwnPropertyDescriptor,ae=(e,n,t,r)=>{for(var s=r>1?void 0:r?ce(n,t):n,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=(r?o(n,t,s):o(s))||s);return r&&s&&oe(n,t,s),s},X=(e,n)=>(t,r)=>n(t,r,e);c.UniverNetworkPlugin=(D=class extends a.Plugin{constructor(n=void 0,t,r){super(),this._config=n,this._logger=t,this._injector=r}onStarting(){var r,s,i;if(this._injector.get(c.HTTPService,a.Quantity.OPTIONAL,a.LookUp.SKIP_SELF)&&!((r=this._config)!=null&&r.forceUseNewInstance)){this._logger.warn("[UniverNetworkPlugin]",'HTTPService is already registered in an ancestor interceptor. Skipping registration. If you want to force a new instance, set "forceUseNewInstance" to true in the plugin configuration.');return}const t=(s=this._config)!=null&&s.useFetchImpl?c.FetchHTTPImplementation:typeof window<"u"?c.XHRHTTPImplementation:c.FetchHTTPImplementation;a.registerDependencies(this._injector,a.mergeOverrideWithDependencies([[c.HTTPService],[O,{useClass:t}]],(i=this._config)==null?void 0:i.override))}},w(D,"pluginName","UNIVER_NETWORK_PLUGIN"),D),c.UniverNetworkPlugin=ae([X(1,a.ILogService),X(2,a.Inject(a.Injector))],c.UniverNetworkPlugin);const le=a.createIdentifier("univer.network.socket.service");class he extends a.Disposable{createSocket(n){try{const t=new WebSocket(n),r=new a.DisposableCollection;return{URL:n,close:(i,o)=>{t.close(i,o),r.dispose()},send:i=>{t.send(i)},open$:new y.Observable(i=>{const o=l=>i.next(l);t.addEventListener("open",o),r.add(a.toDisposable(()=>t.removeEventListener("open",o)))}).pipe(R.share()),close$:new y.Observable(i=>{const o=l=>i.next(l);t.addEventListener("close",o),r.add(a.toDisposable(()=>t.removeEventListener("close",o)))}).pipe(R.share()),error$:new y.Observable(i=>{const o=l=>i.next(l);t.addEventListener("error",o),r.add(a.toDisposable(()=>t.removeEventListener("error",o)))}).pipe(R.share()),message$:new y.Observable(i=>{const o=l=>i.next(l);t.addEventListener("message",o),r.add(a.toDisposable(()=>t.removeEventListener("message",o)))}).pipe(R.share())}}catch(t){return console.error(t),null}}}const de=3,pe=1e3,ue=e=>{var r,s;const n=(r=e==null?void 0:e.maxRetryAttempts)!=null?r:de,t=(s=e==null?void 0:e.delayInterval)!=null?s:pe;return(i,o)=>o(i).pipe(R.retry({delay:t,count:n}))},fe=e=>{const n=[],t=new Set,r=()=>{var s;for(;t.size<((s=e==null?void 0:e.maxParallel)!=null?s:1)&&n.length>0;){const i=n.shift();t.add(i),i()}};return(s,i)=>new y.Observable(o=>{const l=()=>i(s).subscribe({next:f=>o.next(f),error:f=>o.error(f),complete:()=>o.complete()}),u=()=>{t.delete(l),a.remove(n,l),r()};return n.push(l),r(),u})},ge=e=>{const{errorStatusCodes:n,onAuthError:t}=e;return(s,i)=>i(s).pipe(y.catchError(o=>(o instanceof b&&n.some(l=>l===o.status)&&t(),y.throwError(()=>o))))},me=(e=300)=>{let t=()=>{};return r=>new Promise(s=>{t();const i=setTimeout(()=>{s(!0)},e);t=()=>{clearTimeout(i),s(!1)}})},ye=()=>(e,n)=>n.map(t=>({config:t,result:e})),we=(e,n={})=>{const{isMatch:t,getParamsFromRequest:r,mergeParamsToRequest:s}=e,{fetchCheck:i=me(300),distributeResult:o=ye()}=n,l=[],u=f=>f.map(h=>h.config);return(f,h)=>t(f)?new y.Observable(d=>{const p=r(f);l.push({next:m=>d.next(m),error:m=>d.error(m),config:p});const v=u(l);i(f).then(m=>{if(m){const I=[];v.forEach(g=>{const _=l.findIndex(E=>E.config===g);if(_>=0){const[E]=l.splice(_,1);I.push(E)}}),h(s(v,f)).subscribe({next:g=>{if(g.type===A.Response){const _=g.body,E=o(_,v);I.forEach(k=>{const G=E.find(q=>q.config===k.config);if(G){const q=new N({body:G.result,headers:g.headers,status:g.status,statusText:g.statusText});k.next(q)}else k.error("batch error")})}},complete:()=>d.complete(),error:g=>d.error(g)})}})}):h(f)};c.AuthInterceptorFactory=ge,c.HTTPEventType=A,c.HTTPHeaders=L,c.HTTPProgress=j,c.HTTPRequest=U,c.HTTPResponse=N,c.HTTPResponseError=b,c.HTTPStatusCode=F,c.IHTTPImplementation=O,c.ISocketService=le,c.MergeInterceptorFactory=we,c.ResponseHeader=x,c.RetryInterceptorFactory=ue,c.ThresholdInterceptorFactory=fe,c.WebSocketService=he,Object.defineProperty(c,Symbol.toStringTag,{value:"Module"})});
1
+ (function(c,a){typeof exports=="object"&&typeof module<"u"?a(exports,require("@univerjs/core"),require("rxjs"),require("rxjs/operators")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","rxjs","rxjs/operators"],a):(c=typeof globalThis<"u"?globalThis:c||self,a(c.UniverNetwork={},c.UniverCore,c.rxjs,c.rxjs.operators))})(this,function(c,a,y,R){"use strict";var ve=Object.defineProperty;var Ie=(c,a,y)=>a in c?ve(c,a,{enumerable:!0,configurable:!0,writable:!0,value:y}):c[a]=y;var w=(c,a,y)=>Ie(c,typeof a!="symbol"?a+"":a,y);var D;const k="application/json";class L{constructor(n){w(this,"_headers",new Map);typeof n=="string"?this._handleHeadersString(n):n instanceof Headers?this._handleHeaders(n):n&&this._handleHeadersConstructorProps(n)}forEach(n){this._headers.forEach((t,r)=>n(r,t))}has(n){return!!this._headers.has(n.toLowerCase())}get(n){const t=n.toLowerCase();return this._headers.has(t)?this._headers.get(t):null}set(n,t){this._setHeader(n,t)}toHeadersInit(){var t,r;const n={};return this._headers.forEach((s,i)=>{n[i]=s.join(",")}),(t=n.accept)!=null||(n.accept="application/json, text/plain, */*"),(r=n["content-type"])!=null||(n["content-type"]="application/json;charset=UTF-8"),n}_setHeader(n,t){const r=n.toLowerCase();this._headers.has(r)?this._headers.get(r).push(t.toString()):this._headers.set(r,[t.toString()])}_handleHeadersString(n){n.split(`
2
+ `).forEach(t=>{const[r,s]=t.split(":");r&&s&&this._setHeader(r,s)})}_handleHeadersConstructorProps(n){Object.entries(n).forEach(([t,r])=>this._setHeader(t,r))}_handleHeaders(n){n.forEach((t,r)=>this._setHeader(r,t))}}const O=a.createIdentifier("network.http-implementation");class M{constructor(n){this.params=n}toString(){return this.params?Object.keys(this.params).map(n=>{const t=this.params[n];return Array.isArray(t)?t.map(r=>`${n}=${r}`).join("&"):`${n}=${t}`}).join("&"):""}}let W=0;class U{constructor(n,t,r){w(this,"uid",W++);this.method=n,this.url=t,this.requestParams=r}get headers(){return this.requestParams.headers}get withCredentials(){return this.requestParams.withCredentials}get responseType(){return this.requestParams.responseType}getUrlWithParams(){var t,r;const n=(r=(t=this.requestParams)==null?void 0:t.params)==null?void 0:r.toString();return n?`${this.url}${this.url.includes("?")?"&":"?"}${n}`:this.url}getBody(){var r,s;const n=(r=this.headers.get("Content-Type"))!=null?r:k,t=(s=this.requestParams)==null?void 0:s.body;return n===k&&t&&typeof t=="object"?JSON.stringify(t):t?`${t}`:null}getHeadersInit(){return this.headers.toHeadersInit()}}var V=Object.defineProperty,P=Object.getOwnPropertyDescriptor,z=(e,n,t,r)=>{for(var s=r>1?void 0:r?P(n,t):n,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=(r?o(n,t,s):o(s))||s);return r&&s&&V(n,t,s),s},J=(e,n)=>(t,r)=>n(t,r,e);c.HTTPService=class extends a.Disposable{constructor(t){super();w(this,"_interceptors",[]);w(this,"_pipe");this._http=t}registerHTTPInterceptor(t){if(this._interceptors.indexOf(t)!==-1)throw new Error("[HTTPService]: The interceptor has already been registered!");return this._interceptors.push(t),this._interceptors=this._interceptors.sort((r,s)=>{var i,o;return((i=r.priority)!=null?i:0)-((o=s.priority)!=null?o:0)}),this._pipe=null,a.toDisposable(()=>a.remove(this._interceptors,t))}get(t,r){return this._request("GET",t,r)}post(t,r){return this._request("POST",t,r)}put(t,r){return this._request("PUT",t,r)}delete(t,r){return this._request("DELETE",t,r)}patch(t,r){return this._request("PATCH",t,r)}getSSE(t,r,s){var u,f;const i=new L(s==null?void 0:s.headers),o=new M(s==null?void 0:s.params),l=new U(t,r,{headers:i,params:o,withCredentials:(u=s==null?void 0:s.withCredentials)!=null?u:!1,reportProgress:!0,responseType:(f=s==null?void 0:s.responseType)!=null?f:"json",body:["GET","DELETE"].includes(t)||s==null?void 0:s.body});return y.of(l).pipe(R.concatMap(h=>this._runInterceptorsAndImplementation(h)))}async _request(t,r,s){var h,d;const i=new L(s==null?void 0:s.headers),o=new M(s==null?void 0:s.params),l=new U(t,r,{headers:i,params:o,withCredentials:(h=s==null?void 0:s.withCredentials)!=null?h:!1,responseType:(d=s==null?void 0:s.responseType)!=null?d:"json",body:["GET","DELETE"].includes(t)||s==null?void 0:s.body}),u=y.of(l).pipe(R.concatMap(p=>this._runInterceptorsAndImplementation(p)));return await y.firstValueFrom(u)}_runInterceptorsAndImplementation(t){return this._pipe||(this._pipe=this._interceptors.map(r=>r.interceptor).reduceRight((r,s)=>K(r,s),(r,s)=>s(r))),this._pipe(t,r=>this._http.send(r))}},c.HTTPService=z([J(0,O)],c.HTTPService);function K(e,n){return(t,r)=>n(t,s=>e(s,r))}const Y=200,Q=300;var F=(e=>(e[e.Continue=100]="Continue",e[e.SwitchingProtocols=101]="SwitchingProtocols",e[e.Processing=102]="Processing",e[e.EarlyHints=103]="EarlyHints",e[e.Ok=200]="Ok",e[e.Created=201]="Created",e[e.Accepted=202]="Accepted",e[e.NonAuthoritativeInformation=203]="NonAuthoritativeInformation",e[e.NoContent=204]="NoContent",e[e.ResetContent=205]="ResetContent",e[e.PartialContent=206]="PartialContent",e[e.MultiStatus=207]="MultiStatus",e[e.AlreadyReported=208]="AlreadyReported",e[e.ImUsed=226]="ImUsed",e[e.MultipleChoices=300]="MultipleChoices",e[e.MovedPermanently=301]="MovedPermanently",e[e.Found=302]="Found",e[e.SeeOther=303]="SeeOther",e[e.NotModified=304]="NotModified",e[e.UseProxy=305]="UseProxy",e[e.Unused=306]="Unused",e[e.TemporaryRedirect=307]="TemporaryRedirect",e[e.PermanentRedirect=308]="PermanentRedirect",e[e.BadRequest=400]="BadRequest",e[e.Unauthorized=401]="Unauthorized",e[e.PaymentRequired=402]="PaymentRequired",e[e.Forbidden=403]="Forbidden",e[e.NotFound=404]="NotFound",e[e.MethodNotAllowed=405]="MethodNotAllowed",e[e.NotAcceptable=406]="NotAcceptable",e[e.ProxyAuthenticationRequired=407]="ProxyAuthenticationRequired",e[e.RequestTimeout=408]="RequestTimeout",e[e.Conflict=409]="Conflict",e[e.Gone=410]="Gone",e[e.LengthRequired=411]="LengthRequired",e[e.PreconditionFailed=412]="PreconditionFailed",e[e.PayloadTooLarge=413]="PayloadTooLarge",e[e.UriTooLong=414]="UriTooLong",e[e.UnsupportedMediaType=415]="UnsupportedMediaType",e[e.RangeNotSatisfiable=416]="RangeNotSatisfiable",e[e.ExpectationFailed=417]="ExpectationFailed",e[e.ImATeapot=418]="ImATeapot",e[e.MisdirectedRequest=421]="MisdirectedRequest",e[e.UnprocessableEntity=422]="UnprocessableEntity",e[e.Locked=423]="Locked",e[e.FailedDependency=424]="FailedDependency",e[e.TooEarly=425]="TooEarly",e[e.UpgradeRequired=426]="UpgradeRequired",e[e.PreconditionRequired=428]="PreconditionRequired",e[e.TooManyRequests=429]="TooManyRequests",e[e.RequestHeaderFieldsTooLarge=431]="RequestHeaderFieldsTooLarge",e[e.UnavailableForLegalReasons=451]="UnavailableForLegalReasons",e[e.InternalServerError=500]="InternalServerError",e[e.NotImplemented=501]="NotImplemented",e[e.BadGateway=502]="BadGateway",e[e.ServiceUnavailable=503]="ServiceUnavailable",e[e.GatewayTimeout=504]="GatewayTimeout",e[e.HttpVersionNotSupported=505]="HttpVersionNotSupported",e[e.VariantAlsoNegotiates=506]="VariantAlsoNegotiates",e[e.InsufficientStorage=507]="InsufficientStorage",e[e.LoopDetected=508]="LoopDetected",e[e.NotExtended=510]="NotExtended",e[e.NetworkAuthenticationRequired=511]="NetworkAuthenticationRequired",e))(F||{}),A=(e=>(e[e.DownloadProgress=0]="DownloadProgress",e[e.Response=1]="Response",e))(A||{});class N{constructor({body:n,headers:t,status:r,statusText:s}){w(this,"type",1);w(this,"body");w(this,"headers");w(this,"status");w(this,"statusText");this.body=n,this.headers=t,this.status=r,this.statusText=s}}class j{constructor(n,t,r){w(this,"type",0);this.total=n,this.loaded=t,this.partialText=r}}class x{constructor(n,t,r){this.headers=n,this.status=t,this.statusText=r}}class b{constructor({request:n,headers:t,status:r,statusText:s,error:i}){w(this,"request");w(this,"headers");w(this,"status");w(this,"statusText");w(this,"error");this.request=n,this.headers=t,this.status=r,this.statusText=s,this.error=i}}function B(e){return{method:e.method,headers:e.getHeadersInit(),body:e.getBody(),credentials:e.withCredentials?"include":void 0}}var Z=Object.defineProperty,H=Object.getOwnPropertyDescriptor,S=(e,n,t,r)=>{for(var s=r>1?void 0:r?H(n,t):n,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=(r?o(n,t,s):o(s))||s);return r&&s&&Z(n,t,s),s},C=(e,n)=>(t,r)=>n(t,r,e);c.FetchHTTPImplementation=class{constructor(n){this._logService=n}send(n){return new y.Observable(t=>{const r=new AbortController;return this._send(n,t,r).catch(s=>{t.error(new b({error:s,request:n}))}),()=>r.abort()})}async _send(n,t,r){var h,d;let s;try{const p=B(n),v=n.getUrlWithParams(),m=fetch(v,{signal:r.signal,...p});this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${v} with params ${p}`),s=await m}catch(p){const v=new b({request:n,error:p,status:(h=p.status)!=null?h:0,statusText:(d=p.statusText)!=null?d:"Unknown Error",headers:p.headers});this._logService.error("[FetchHTTPImplementation]: network error",v),t.error(v);return}const i=new L(s.headers),o=s.status,l=s.statusText;let u=null;if(s.body&&(u=await this._readBody(n,s,t)),o>=F.Ok&&o<F.MultipleChoices)t.next(new N({body:u,headers:i,status:o,statusText:l}));else{const p=new b({request:n,error:u,status:o,statusText:l,headers:i});this._logService.error("[FetchHTTPImplementation]: network error",p),t.error(p)}t.complete()}async _readBody(n,t,r){var v,m;const s=[],i=t.body.getReader(),o=t.headers.get("content-length");let l=0;const u=(v=n.requestParams)==null?void 0:v.reportProgress,f=n.responseType;let h,d;for(;;){const{done:I,value:g}=await i.read();if(I)break;s.push(g),l+=g.length,u&&f==="text"&&(h=(h!=null?h:"")+(d!=null?d:d=new TextDecoder).decode(g,{stream:!0}),r.next(new j(o?Number.parseInt(o,10):void 0,l,h)))}const p=T(s,l);try{const I=(m=t.headers.get("content-type"))!=null?m:"";return te(n,p,I)}catch(I){const g=new b({request:n,error:I,status:t.status,statusText:t.statusText,headers:new L(t.headers)});return this._logService.error("[FetchHTTPImplementation]: network error",g),r.error(g),null}}},c.FetchHTTPImplementation=S([C(0,a.ILogService)],c.FetchHTTPImplementation);function T(e,n){const t=new Uint8Array(n);let r=0;for(const s of e)t.set(s,r),r+=s.length;return t}const ee=/^\)\]\}',?\n/;function te(e,n,t){switch(e.responseType){case"json":const r=new TextDecoder().decode(n).replace(ee,"");return r===""?null:JSON.parse(r);case"text":return new TextDecoder().decode(n);case"blob":return new Blob([n],{type:t});case"arraybuffer":return n.buffer;default:throw new Error(`[FetchHTTPImplementation]: unknown response type: ${e.responseType}.`)}}var re=Object.defineProperty,ne=Object.getOwnPropertyDescriptor,se=(e,n,t,r)=>{for(var s=r>1?void 0:r?ne(n,t):n,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=(r?o(n,t,s):o(s))||s);return r&&s&&re(n,t,s),s},ie=(e,n)=>(t,r)=>n(t,r,e);c.XHRHTTPImplementation=class{constructor(n){this._logService=n}send(n){return new y.Observable(t=>{const r=new XMLHttpRequest,s=n.getUrlWithParams(),i=B(n);r.open(n.method,s),n.withCredentials&&(r.withCredentials=!0),i.headers&&Object.entries(i.headers).forEach(([h,d])=>r.setRequestHeader(h,d));const o=()=>{const h=r.statusText||"OK",d=new L(r.getAllResponseHeaders());return new x(d,r.status,h)},l=()=>{const{headers:h,statusText:d,status:p}=o(),{responseType:v}=n;let m=null,I=null;p!==F.NoContent&&(m=typeof r.response>"u"?r.responseText:r.response);let g=p>=Y&&p<Q;if(v==="json"&&typeof m=="string"){const _=m;try{m=m?JSON.parse(m):null}catch(E){g=!1,m=_,I=E}}if(g)t.next(new N({body:m,headers:h,status:p,statusText:d}));else{const _=new b({request:n,error:I,headers:h,status:p,statusText:d});this._logService.error("[XHRHTTPImplementation]: network error",_),t.error(_)}},u=h=>{const d=new b({request:n,error:h,status:r.status||0,statusText:r.statusText||"Unknown Error",headers:o().headers});this._logService.error("[XHRHTTPImplementation]: network error",d),t.error(d)};r.addEventListener("load",l),r.addEventListener("error",u),r.addEventListener("abort",u),r.addEventListener("timeout",u);const f=n.getBody();return r.send(f),this._logService.debug(`[XHRHTTPImplementation]: sending request to url ${s} with params ${i}`),()=>{r.readyState!==r.DONE&&r.abort(),r.removeEventListener("load",l),r.removeEventListener("error",u),r.removeEventListener("abort",u),r.removeEventListener("timeout",u)}})}},c.XHRHTTPImplementation=se([ie(0,a.ILogService)],c.XHRHTTPImplementation);var oe=Object.defineProperty,ce=Object.getOwnPropertyDescriptor,ae=(e,n,t,r)=>{for(var s=r>1?void 0:r?ce(n,t):n,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=(r?o(n,t,s):o(s))||s);return r&&s&&oe(n,t,s),s},X=(e,n)=>(t,r)=>n(t,r,e);c.UniverNetworkPlugin=(D=class extends a.Plugin{constructor(n=void 0,t,r){super(),this._config=n,this._logger=t,this._injector=r}onStarting(){var r,s,i;if(this._injector.get(c.HTTPService,a.Quantity.OPTIONAL,a.LookUp.SKIP_SELF)&&!((r=this._config)!=null&&r.forceUseNewInstance)){this._logger.warn("[UniverNetworkPlugin]",'HTTPService is already registered in an ancestor interceptor. Skipping registration. If you want to force a new instance, set "forceUseNewInstance" to true in the plugin configuration.');return}const t=(s=this._config)!=null&&s.useFetchImpl?c.FetchHTTPImplementation:typeof window<"u"?c.XHRHTTPImplementation:c.FetchHTTPImplementation;a.registerDependencies(this._injector,a.mergeOverrideWithDependencies([[c.HTTPService],[O,{useClass:t}]],(i=this._config)==null?void 0:i.override))}},w(D,"pluginName","UNIVER_NETWORK_PLUGIN"),D),c.UniverNetworkPlugin=ae([X(1,a.ILogService),X(2,a.Inject(a.Injector))],c.UniverNetworkPlugin);const le=a.createIdentifier("univer.network.socket.service");class he extends a.Disposable{createSocket(n){try{const t=new WebSocket(n),r=new a.DisposableCollection;return{URL:n,close:(i,o)=>{t.close(i,o),r.dispose()},send:i=>{t.send(i)},open$:new y.Observable(i=>{const o=l=>i.next(l);t.addEventListener("open",o),r.add(a.toDisposable(()=>t.removeEventListener("open",o)))}).pipe(R.share()),close$:new y.Observable(i=>{const o=l=>i.next(l);t.addEventListener("close",o),r.add(a.toDisposable(()=>t.removeEventListener("close",o)))}).pipe(R.share()),error$:new y.Observable(i=>{const o=l=>i.next(l);t.addEventListener("error",o),r.add(a.toDisposable(()=>t.removeEventListener("error",o)))}).pipe(R.share()),message$:new y.Observable(i=>{const o=l=>i.next(l);t.addEventListener("message",o),r.add(a.toDisposable(()=>t.removeEventListener("message",o)))}).pipe(R.share())}}catch(t){return console.error(t),null}}}const de=3,pe=1e3,ue=e=>{var r,s;const n=(r=e==null?void 0:e.maxRetryAttempts)!=null?r:de,t=(s=e==null?void 0:e.delayInterval)!=null?s:pe;return(i,o)=>o(i).pipe(R.retry({delay:t,count:n}))},fe=e=>{const n=[],t=new Set,r=()=>{var s;for(;t.size<((s=e==null?void 0:e.maxParallel)!=null?s:1)&&n.length>0;){const i=n.shift();t.add(i),i()}};return(s,i)=>new y.Observable(o=>{const l=()=>i(s).subscribe({next:f=>o.next(f),error:f=>o.error(f),complete:()=>o.complete()}),u=()=>{t.delete(l),a.remove(n,l),r()};return n.push(l),r(),u})},ge=e=>{const{errorStatusCodes:n,onAuthError:t}=e;return(s,i)=>i(s).pipe(y.catchError(o=>(o instanceof b&&n.some(l=>l===o.status)&&t(),y.throwError(()=>o))))},me=(e=300)=>{let t=()=>{};return r=>new Promise(s=>{t();const i=setTimeout(()=>{s(!0)},e);t=()=>{clearTimeout(i),s(!1)}})},ye=()=>(e,n)=>n.map(t=>({config:t,result:e})),we=(e,n={})=>{const{isMatch:t,getParamsFromRequest:r,mergeParamsToRequest:s}=e,{fetchCheck:i=me(300),distributeResult:o=ye()}=n,l=[],u=f=>f.map(h=>h.config);return(f,h)=>t(f)?new y.Observable(d=>{const p=r(f);l.push({next:m=>d.next(m),error:m=>d.error(m),config:p});const v=u(l);i(f).then(m=>{if(m){const I=[];v.forEach(g=>{const _=l.findIndex(E=>E.config===g);if(_>=0){const[E]=l.splice(_,1);I.push(E)}}),h(s(v,f)).subscribe({next:g=>{if(g.type===A.Response){const _=g.body,E=o(_,v);I.forEach($=>{const G=E.find(q=>q.config===$.config);if(G){const q=new N({body:G.result,headers:g.headers,status:g.status,statusText:g.statusText});$.next(q)}else $.error("batch error")})}},complete:()=>d.complete(),error:g=>d.error(g)})}})}):h(f)};c.AuthInterceptorFactory=ge,c.HTTPEventType=A,c.HTTPHeaders=L,c.HTTPProgress=j,c.HTTPRequest=U,c.HTTPResponse=N,c.HTTPResponseError=b,c.HTTPStatusCode=F,c.IHTTPImplementation=O,c.ISocketService=le,c.MergeInterceptorFactory=we,c.ResponseHeader=x,c.RetryInterceptorFactory=ue,c.ThresholdInterceptorFactory=fe,c.WebSocketService=he,Object.defineProperty(c,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@univerjs/network",
3
- "version": "0.5.5",
3
+ "version": "0.6.0-alpha.0",
4
4
  "private": false,
5
5
  "author": "DreamNum <developer@univer.ai>",
6
6
  "license": "Apache-2.0",
@@ -52,14 +52,14 @@
52
52
  "rxjs": ">=7.0.0"
53
53
  },
54
54
  "dependencies": {
55
- "@univerjs/core": "0.5.5"
55
+ "@univerjs/core": "0.6.0-alpha.0"
56
56
  },
57
57
  "devDependencies": {
58
58
  "rxjs": "^7.8.1",
59
- "typescript": "^5.7.2",
59
+ "typescript": "^5.7.3",
60
60
  "vite": "^6.0.7",
61
61
  "vitest": "^2.1.8",
62
- "@univerjs-infra/shared": "0.5.5"
62
+ "@univerjs-infra/shared": "0.6.0-alpha.0"
63
63
  },
64
64
  "scripts": {
65
65
  "test": "vitest run",
@@ -1,16 +0,0 @@
1
- /**
2
- * Copyright 2023-present DreamNum Inc.
3
- *
4
- * Licensed under the Apache License, Version 2.0 (the "License");
5
- * you may not use this file except in compliance with the License.
6
- * You may obtain a copy of the License at
7
- *
8
- * http://www.apache.org/licenses/LICENSE-2.0
9
- *
10
- * Unless required by applicable law or agreed to in writing, software
11
- * distributed under the License is distributed on an "AS IS" BASIS,
12
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- * See the License for the specific language governing permissions and
14
- * limitations under the License.
15
- */
16
- export {};
@@ -1,16 +0,0 @@
1
- /**
2
- * Copyright 2023-present DreamNum Inc.
3
- *
4
- * Licensed under the Apache License, Version 2.0 (the "License");
5
- * you may not use this file except in compliance with the License.
6
- * You may obtain a copy of the License at
7
- *
8
- * http://www.apache.org/licenses/LICENSE-2.0
9
- *
10
- * Unless required by applicable law or agreed to in writing, software
11
- * distributed under the License is distributed on an "AS IS" BASIS,
12
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- * See the License for the specific language governing permissions and
14
- * limitations under the License.
15
- */
16
- export {};
@@ -1,16 +0,0 @@
1
- /**
2
- * Copyright 2023-present DreamNum Inc.
3
- *
4
- * Licensed under the Apache License, Version 2.0 (the "License");
5
- * you may not use this file except in compliance with the License.
6
- * You may obtain a copy of the License at
7
- *
8
- * http://www.apache.org/licenses/LICENSE-2.0
9
- *
10
- * Unless required by applicable law or agreed to in writing, software
11
- * distributed under the License is distributed on an "AS IS" BASIS,
12
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- * See the License for the specific language governing permissions and
14
- * limitations under the License.
15
- */
16
- export {};