@univerjs/network 0.8.0 → 0.8.1-nightly.202506131607

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
- "use strict";var G=Object.defineProperty;var W=(e,n,r)=>n in e?G(e,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[n]=r;var y=(e,n,r)=>W(e,typeof n!="symbol"?n+"":n,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("@univerjs/core"),w=require("rxjs"),_=require("rxjs/operators"),A="application/json";function V(e){return Array.isArray(e)?e.some(n=>n.includes(A)):e.includes(A)}class E{constructor(n){y(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((r,t)=>n(t,r))}has(n){return!!this._headers.has(n.toLowerCase())}get(n){const r=n.toLowerCase();return this._headers.has(r)?this._headers.get(r):null}set(n,r){this._setHeader(n,r)}toHeadersInit(n){var t,s;const r={};return this._headers.forEach((o,i)=>{r[i]=o.join(",")}),(t=r.accept)!=null||(r.accept="application/json, text/plain, */*"),n instanceof FormData||(s=r["content-type"])!=null||(r["content-type"]="application/json;charset=UTF-8"),r}_setHeader(n,r){const t=n.toLowerCase();this._headers.has(t)?this._headers.get(t).push(r.toString()):this._headers.set(t,[r.toString()])}_handleHeadersString(n){n.split(`
2
- `).forEach(r=>{const[t,s]=r.split(":");t&&s&&this._setHeader(t,s)})}_handleHeadersConstructorProps(n){Object.entries(n).forEach(([r,t])=>this._setHeader(r,t))}_handleHeaders(n){n.forEach((r,t)=>this._setHeader(t,r))}}const U=p.createIdentifier("network.http-implementation");class M{constructor(n){this.params=n}toString(){return this.params?Object.keys(this.params).map(n=>{const r=this.params[n];return Array.isArray(r)?r.map(t=>`${n}=${t}`).join("&"):`${n}=${r}`}).join("&"):""}}let J=0;class O{constructor(n,r,t){y(this,"uid",J++);this.method=n,this.url=r,this.requestParams=t}get headers(){return this.requestParams.headers}get withCredentials(){return this.requestParams.withCredentials}get responseType(){return this.requestParams.responseType}getUrlWithParams(){var r,t;const n=(t=(r=this.requestParams)==null?void 0:r.params)==null?void 0:t.toString();return n?`${this.url}${this.url.includes("?")?"&":"?"}${n}`:this.url}getBody(){var t,s;const n=(t=this.headers.get("Content-Type"))!=null?t:A,r=(s=this.requestParams)==null?void 0:s.body;return r instanceof FormData?r:V(n)&&r&&typeof r=="object"?JSON.stringify(r):r?`${r}`:null}getHeadersInit(){var r;return this.headers.toHeadersInit((r=this.requestParams)==null?void 0:r.body)}}var z=Object.getOwnPropertyDescriptor,K=(e,n,r,t)=>{for(var s=t>1?void 0:t?z(n,r):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},Y=(e,n)=>(r,t)=>n(r,t,e);exports.HTTPService=class extends p.Disposable{constructor(r){super();y(this,"_interceptors",[]);y(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((t,s)=>{var o,i;return((o=t.priority)!=null?o:0)-((i=s.priority)!=null?i:0)}),this._pipe=null,p.toDisposable(()=>p.remove(this._interceptors,r))}get(r,t){return this._request("GET",r,t)}post(r,t){return this._request("POST",r,t)}put(r,t){return this._request("PUT",r,t)}delete(r,t){return this._request("DELETE",r,t)}patch(r,t){return this._request("PATCH",r,t)}getSSE(r,t,s){var d,u;const o=new E(s==null?void 0:s.headers),i=new M(s==null?void 0:s.params),c=new O(r,t,{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(_.concatMap(a=>this._runInterceptorsAndImplementation(a)))}async _request(r,t,s){var a,l;const o=new E(s==null?void 0:s.headers),i=new M(s==null?void 0:s.params),c=new O(r,t,{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(_.concatMap(h=>this._runInterceptorsAndImplementation(h)));return await w.firstValueFrom(d)}_runInterceptorsAndImplementation(r){return this._pipe||(this._pipe=this._interceptors.map(t=>t.interceptor).reduceRight((t,s)=>Q(t,s),(t,s)=>s(t))),this._pipe(r,t=>this._http.send(t))}};exports.HTTPService=K([Y(0,U)],exports.HTTPService);function Q(e,n){return(r,t)=>n(r,s=>e(s,t))}const Z=200,P=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:n,headers:r,status:t,statusText:s}){y(this,"type",1);y(this,"body");y(this,"headers");y(this,"status");y(this,"statusText");this.body=n,this.headers=r,this.status=t,this.statusText=s}}class j{constructor(n,r,t){y(this,"type",0);this.total=n,this.loaded=r,this.partialText=t}}class B{constructor(n,r,t){this.headers=n,this.status=r,this.statusText=t}}class b{constructor({request:n,headers:r,status:t,statusText:s,error:o}){y(this,"request");y(this,"headers");y(this,"status");y(this,"statusText");y(this,"error");this.request=n,this.headers=r,this.status=t,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.getOwnPropertyDescriptor,S=(e,n,r,t)=>{for(var s=t>1?void 0:t?H(n,r):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},C=(e,n)=>(r,t)=>n(r,t,e);exports.FetchHTTPImplementation=class{constructor(n){this._logService=n}send(n){return new w.Observable(r=>{const t=new AbortController;return this._send(n,r,t).catch(s=>{r.error(new b({error:s,request:n}))}),()=>t.abort()})}async _send(n,r,t){var a,l;let s;try{const h=X(n),f=n.getUrlWithParams(),m=fetch(f,{signal:t.signal,...h});this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${f} with params ${h}`),s=await m}catch(h){const f=new b({request:n,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",f),r.error(f);return}const o=new E(s.headers),i=s.status,c=s.statusText;let d=null;if(s.body&&(d=await this._readBody(n,s,r)),i>=x.Ok&&i<x.MultipleChoices)r.next(new L({body:d,headers:o,status:i,statusText:c}));else{const h=new b({request:n,error:d,status:i,statusText:c,headers:o});this._logService.error("[FetchHTTPImplementation]: network error",h),r.error(h)}r.complete()}async _readBody(n,r,t){var f,m;const s=[],o=r.body.getReader(),i=r.headers.get("content-length");let c=0;const d=(f=n.requestParams)==null?void 0:f.reportProgress,u=n.responseType;let a,l;for(;;){const{done:v,value:g}=await o.read();if(v)break;s.push(g),c+=g.length,d&&u==="text"&&(a=(a!=null?a:"")+(l!=null?l:l=new TextDecoder).decode(g,{stream:!0}),t.next(new j(i?Number.parseInt(i,10):void 0,c,a)))}const h=T(s,c);try{const v=(m=r.headers.get("content-type"))!=null?m:"";return re(n,h,v)}catch(v){const g=new b({request:n,error:v,status:r.status,statusText:r.statusText,headers:new E(r.headers)});return this._logService.error("[FetchHTTPImplementation]: network error",g),t.error(g),null}}};exports.FetchHTTPImplementation=S([C(0,p.ILogService)],exports.FetchHTTPImplementation);function T(e,n){const r=new Uint8Array(n);let t=0;for(const s of e)r.set(s,t),t+=s.length;return r}const ee=/^\)\]\}',?\n/;function re(e,n,r){switch(e.responseType){case"json":const t=new TextDecoder().decode(n).replace(ee,"");return t===""?null:JSON.parse(t);case"text":return new TextDecoder().decode(n);case"blob":return new Blob([n],{type:r});case"arraybuffer":return n.buffer;default:throw new Error(`[FetchHTTPImplementation]: unknown response type: ${e.responseType}.`)}}var te=Object.getOwnPropertyDescriptor,ne=(e,n,r,t)=>{for(var s=t>1?void 0:t?te(n,r):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},se=(e,n)=>(r,t)=>n(r,t,e);exports.XHRHTTPImplementation=class{constructor(n){this._logService=n}send(n){return new w.Observable(r=>{const t=new XMLHttpRequest,s=n.getUrlWithParams(),o=X(n);t.open(n.method,s),n.withCredentials&&(t.withCredentials=!0),o.headers&&Object.entries(o.headers).forEach(([a,l])=>t.setRequestHeader(a,l));const i=()=>{const a=t.statusText||"OK",l=new E(t.getAllResponseHeaders());return new B(l,t.status,a)},c=()=>{const{headers:a,statusText:l,status:h}=i(),{responseType:f}=n;let m=null,v=null;h!==x.NoContent&&(m=typeof t.response>"u"?t.responseText:t.response);let g=h>=Z&&h<P;if(f==="json"&&typeof m=="string"){const I=m;try{m=m?JSON.parse(m):null}catch(R){g=!1,m=I,v=R}}if(g)r.next(new L({body:m,headers:a,status:h,statusText:l}));else{const I=new b({request:n,error:v,headers:a,status:h,statusText:l});this._logService.error("[XHRHTTPImplementation]: network error",I),r.error(I)}},d=a=>{const l=new b({request:n,error:a,status:t.status||0,statusText:t.statusText||"Unknown Error",headers:i().headers});this._logService.error("[XHRHTTPImplementation]: network error",l),r.error(l)};t.addEventListener("load",c),t.addEventListener("error",d),t.addEventListener("abort",d),t.addEventListener("timeout",d);const u=n.getBody();return t.send(u),this._logService.debug("[XHRHTTPImplementation]",`sending request to url ${s} with params ${o}`),()=>{t.readyState!==t.DONE&&t.abort(),t.removeEventListener("load",c),t.removeEventListener("error",d),t.removeEventListener("abort",d),t.removeEventListener("timeout",d)}})}};exports.XHRHTTPImplementation=ne([se(0,p.ILogService)],exports.XHRHTTPImplementation);var oe=Object.getOwnPropertyDescriptor,ie=(e,n,r,t)=>{for(var s=t>1?void 0:t?oe(n,r):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},$=(e,n)=>(r,t)=>n(r,t,e),k;exports.UniverNetworkPlugin=(k=class extends p.Plugin{constructor(n=void 0,r,t){super(),this._config=n,this._logger=r,this._injector=t}onStarting(){var t,s,o;if(this._injector.get(exports.HTTPService,p.Quantity.OPTIONAL,p.LookUp.SKIP_SELF)&&!((t=this._config)!=null&&t.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))}},y(k,"pluginName","UNIVER_NETWORK_PLUGIN"),k);exports.UniverNetworkPlugin=ie([$(1,p.ILogService),$(2,p.Inject(p.Injector))],exports.UniverNetworkPlugin);const ce=p.createIdentifier("univer.network.socket.service");class ae extends p.Disposable{createSocket(n){try{const r=new WebSocket(n),t=new p.DisposableCollection;return{URL:n,close:(o,i)=>{r.close(o,i),t.dispose()},send:o=>{r.send(o)},open$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("open",i),t.add(p.toDisposable(()=>r.removeEventListener("open",i)))}).pipe(_.share()),close$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("close",i),t.add(p.toDisposable(()=>r.removeEventListener("close",i)))}).pipe(_.share()),error$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("error",i),t.add(p.toDisposable(()=>r.removeEventListener("error",i)))}).pipe(_.share()),message$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("message",i),t.add(p.toDisposable(()=>r.removeEventListener("message",i)))}).pipe(_.share())}}catch(r){return console.error(r),null}}}const le=3,he=1e3,pe=e=>{var t,s;const n=(t=e==null?void 0:e.maxRetryAttempts)!=null?t:le,r=(s=e==null?void 0:e.delayInterval)!=null?s:he;return(o,i)=>i(o).pipe(_.retry({delay:r,count:n}))},de=e=>{const n=[],r=new Set,t=()=>{var s;for(;r.size<((s=e==null?void 0:e.maxParallel)!=null?s:1)&&n.length>0;){const o=n.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(n,c),t()};return n.push(c),t(),d})},ue=e=>{const{errorStatusCodes:n,onAuthError:r}=e;return(s,o)=>o(s).pipe(w.catchError(i=>(i instanceof b&&n.some(c=>c===i.status)&&r(),w.throwError(()=>i))))},ge=(e=300)=>{let r=()=>{};return t=>new Promise(s=>{r();const o=setTimeout(()=>{s(!0)},e);r=()=>{clearTimeout(o),s(!1)}})},me=()=>(e,n)=>n.map(r=>({config:r,result:e})),ye=(e,n={})=>{const{isMatch:r,getParamsFromRequest:t,mergeParamsToRequest:s}=e,{fetchCheck:o=ge(300),distributeResult:i=me()}=n,c=[],d=u=>u.map(a=>a.config);return(u,a)=>r(u)?new w.Observable(l=>{const h=t(u);c.push({next:m=>l.next(m),error:m=>l.error(m),config:h});const f=d(c);o(u).then(m=>{if(m){const v=[];f.forEach(g=>{const I=c.findIndex(R=>R.config===g);if(I>=0){const[R]=c.splice(I,1);v.push(R)}}),a(s(f,u)).subscribe({next:g=>{if(g.type===D.Response){const I=g.body,R=i(I,f);v.forEach(F=>{const q=R.find(N=>N.config===F.config);if(q){const N=new L({body:q.result,headers:g.headers,status:g.status,statusText:g.statusText});F.next(N)}else F.error("batch error")})}},complete:()=>l.complete(),error:g=>l.error(g)})}})}):a(u)};exports.AuthInterceptorFactory=ue;exports.HTTPEventType=D;exports.HTTPHeaders=E;exports.HTTPProgress=j;exports.HTTPRequest=O;exports.HTTPResponse=L;exports.HTTPResponseError=b;exports.HTTPStatusCode=x;exports.IHTTPImplementation=U;exports.ISocketService=ce;exports.MergeInterceptorFactory=ye;exports.ResponseHeader=B;exports.RetryInterceptorFactory=pe;exports.ThresholdInterceptorFactory=de;exports.WebSocketService=ae;
1
+ "use strict";var G=Object.defineProperty;var W=(e,n,r)=>n in e?G(e,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[n]=r;var f=(e,n,r)=>W(e,typeof n!="symbol"?n+"":n,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("@univerjs/core"),w=require("rxjs"),E=require("rxjs/operators"),A="application/json";function V(e){return Array.isArray(e)?e.some(n=>n.includes(A)):e.includes(A)}class _{constructor(n){f(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((r,t)=>n(t,r))}has(n){return!!this._headers.has(n.toLowerCase())}get(n){const r=n.toLowerCase();return this._headers.has(r)?this._headers.get(r):null}set(n,r){this._setHeader(n,r)}toHeadersInit(n){var t,s;const r={};return this._headers.forEach((o,i)=>{r[i]=o.join(",")}),(t=r.accept)!=null||(r.accept="application/json, text/plain, */*"),n instanceof FormData||(s=r["content-type"])!=null||(r["content-type"]="application/json;charset=UTF-8"),r}_setHeader(n,r){const t=n.toLowerCase();this._headers.has(t)?this._headers.get(t).push(r.toString()):this._headers.set(t,[r.toString()])}_handleHeadersString(n){n.split(`
2
+ `).forEach(r=>{const[t,s]=r.split(":");t&&s&&this._setHeader(t,s)})}_handleHeadersConstructorProps(n){Object.entries(n).forEach(([r,t])=>this._setHeader(r,t))}_handleHeaders(n){n.forEach((r,t)=>this._setHeader(t,r))}}const U=p.createIdentifier("network.http-implementation");class M{constructor(n){this.params=n}toString(){return this.params?Object.keys(this.params).map(n=>{const r=this.params[n];return Array.isArray(r)?r.map(t=>`${n}=${t}`).join("&"):`${n}=${r}`}).join("&"):""}}let J=0;class O{constructor(n,r,t){f(this,"uid",J++);this.method=n,this.url=r,this.requestParams=t}get headers(){return this.requestParams.headers}get withCredentials(){return this.requestParams.withCredentials}get responseType(){return this.requestParams.responseType}getUrlWithParams(){var r,t;const n=(t=(r=this.requestParams)==null?void 0:r.params)==null?void 0:t.toString();return n?`${this.url}${this.url.includes("?")?"&":"?"}${n}`:this.url}getBody(){var t,s;const n=(t=this.headers.get("Content-Type"))!=null?t:A,r=(s=this.requestParams)==null?void 0:s.body;return r instanceof FormData?r:V(n)&&r&&typeof r=="object"?JSON.stringify(r):r?`${r}`:null}getHeadersInit(){var r;return this.headers.toHeadersInit((r=this.requestParams)==null?void 0:r.body)}}var z=Object.getOwnPropertyDescriptor,K=(e,n,r,t)=>{for(var s=t>1?void 0:t?z(n,r):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},Y=(e,n)=>(r,t)=>n(r,t,e);exports.HTTPService=class extends p.Disposable{constructor(r){super();f(this,"_interceptors",[]);f(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((t,s)=>{var o,i;return((o=t.priority)!=null?o:0)-((i=s.priority)!=null?i:0)}),this._pipe=null,p.toDisposable(()=>p.remove(this._interceptors,r))}get(r,t){return this.request("GET",r,t)}post(r,t){return this.request("POST",r,t)}put(r,t){return this.request("PUT",r,t)}delete(r,t){return this.request("DELETE",r,t)}patch(r,t){return this.request("PATCH",r,t)}async request(r,t,s){var u,h;const o=new _(s==null?void 0:s.headers),i=new M(s==null?void 0:s.params),c=new O(r,t,{headers:o,params:i,withCredentials:(u=s==null?void 0:s.withCredentials)!=null?u:!1,responseType:(h=s==null?void 0:s.responseType)!=null?h:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body}),y=w.of(c).pipe(E.concatMap(a=>this._runInterceptorsAndImplementation(a)));return await w.firstValueFrom(y)}stream(r,t,s){return this.getSSE(r,t,s)}getSSE(r,t,s){var y,l;const o=new _(s==null?void 0:s.headers),i=new M(s==null?void 0:s.params),c=new O(r,t,{headers:o,params:i,withCredentials:(y=s==null?void 0:s.withCredentials)!=null?y:!1,reportProgress:!0,responseType:(l=s==null?void 0:s.responseType)!=null?l:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body});return w.of(c).pipe(E.concatMap(u=>this._runInterceptorsAndImplementation(u)))}_runInterceptorsAndImplementation(r){return this._pipe||(this._pipe=this._interceptors.map(t=>t.interceptor).reduceRight((t,s)=>Q(t,s),(t,s)=>s(t))),this._pipe(r,t=>this._http.send(t))}};exports.HTTPService=K([Y(0,U)],exports.HTTPService);function Q(e,n){return(r,t)=>n(r,s=>e(s,t))}const Z=200,P=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:n,headers:r,status:t,statusText:s}){f(this,"type",1);f(this,"body");f(this,"headers");f(this,"status");f(this,"statusText");this.body=n,this.headers=r,this.status=t,this.statusText=s}}class j{constructor(n,r,t){f(this,"type",0);this.total=n,this.loaded=r,this.partialText=t}}class B{constructor(n,r,t){this.headers=n,this.status=r,this.statusText=t}}class I{constructor({request:n,headers:r,status:t,statusText:s,error:o}){f(this,"request");f(this,"headers");f(this,"status");f(this,"statusText");f(this,"error");this.request=n,this.headers=r,this.status=t,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.getOwnPropertyDescriptor,S=(e,n,r,t)=>{for(var s=t>1?void 0:t?H(n,r):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},C=(e,n)=>(r,t)=>n(r,t,e);exports.FetchHTTPImplementation=class{constructor(n){this._logService=n}send(n){return new w.Observable(r=>{const t=new AbortController;return this._send(n,r,t).catch(s=>{r.error(new I({error:s,request:n}))}),()=>t.abort()})}async _send(n,r,t){var u,h;let s;try{const a=X(n),m=n.getUrlWithParams(),g=fetch(m,{signal:t.signal,...a});this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${m} with params ${a}`),s=await g}catch(a){const m=new I({request:n,error:a,status:(u=a.status)!=null?u:0,statusText:(h=a.statusText)!=null?h:"Unknown Error",headers:a.headers});this._logService.error("[FetchHTTPImplementation]: network error",m),r.error(m);return}const o=new _(s.headers),i=s.status,c=s.statusText;let y=null;if(s.body&&(y=await this._readBody(n,s,r)),i>=x.Ok&&i<x.MultipleChoices)r.next(new L({body:y,headers:o,status:i,statusText:c}));else{const a=new I({request:n,error:y,status:i,statusText:c,headers:o});this._logService.error("[FetchHTTPImplementation]: network error",a),r.error(a)}r.complete()}async _readBody(n,r,t){var m,g;const s=[],o=r.body.getReader(),i=r.headers.get("content-length");let c=0;const y=(m=n.requestParams)==null?void 0:m.reportProgress,l=n.responseType;let u,h;for(;;){const{done:v,value:d}=await o.read();if(v)break;s.push(d),c+=d.length,y&&l==="text"&&(u=(u!=null?u:"")+(h!=null?h:h=new TextDecoder).decode(d,{stream:!0}),t.next(new j(i?Number.parseInt(i,10):void 0,c,u)))}const a=T(s,c);try{const v=(g=r.headers.get("content-type"))!=null?g:"";return re(n,a,v)}catch(v){const d=new I({request:n,error:v,status:r.status,statusText:r.statusText,headers:new _(r.headers)});return this._logService.error("[FetchHTTPImplementation]: network error",d),t.error(d),null}}};exports.FetchHTTPImplementation=S([C(0,p.ILogService)],exports.FetchHTTPImplementation);function T(e,n){const r=new Uint8Array(n);let t=0;for(const s of e)r.set(s,t),t+=s.length;return r}const ee=/^\)\]\}',?\n/;function re(e,n,r){switch(e.responseType){case"json":const t=new TextDecoder().decode(n).replace(ee,"");return t===""?null:JSON.parse(t);case"text":return new TextDecoder().decode(n);case"blob":return new Blob([n],{type:r});case"arraybuffer":return n.buffer;default:throw new Error(`[FetchHTTPImplementation]: unknown response type: ${e.responseType}.`)}}var te=Object.getOwnPropertyDescriptor,ne=(e,n,r,t)=>{for(var s=t>1?void 0:t?te(n,r):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},se=(e,n)=>(r,t)=>n(r,t,e);exports.XHRHTTPImplementation=class{constructor(n){this._logService=n}send(n){return new w.Observable(r=>{const t=new XMLHttpRequest,s=n.getUrlWithParams(),o=X(n),{responseType:i}=n;t.open(n.method,s),n.withCredentials&&(t.withCredentials=!0),o.headers&&Object.entries(o.headers).forEach(([h,a])=>t.setRequestHeader(h,a));const c=()=>{const h=t.statusText||"OK",a=new _(t.getAllResponseHeaders());return new B(a,t.status,h)},y=()=>{const{headers:h,statusText:a,status:m}=c();let g=null,v=null;m!==x.NoContent&&(g=typeof t.response>"u"?t.responseText:t.response);let d=m>=Z&&m<P;if(i==="json"&&typeof g=="string"){const b=g;try{g=g?JSON.parse(g):null}catch(R){d=!1,g=b,v=R}}if(i==="blob"&&!(g instanceof Blob)&&(d=!1,v=new Error("Response is not a Blob object")),d)r.next(new L({body:g,headers:h,status:m,statusText:a}));else{const b=new I({request:n,error:v,headers:h,status:m,statusText:a});this._logService.error("[XHRHTTPImplementation]: network error",b),r.error(b)}},l=h=>{const a=new I({request:n,error:h,status:t.status||0,statusText:t.statusText||"Unknown Error",headers:c().headers});this._logService.error("[XHRHTTPImplementation]: network error",a),r.error(a)};t.responseType=i||"",t.addEventListener("load",y),t.addEventListener("error",l),t.addEventListener("abort",l),t.addEventListener("timeout",l);const u=n.getBody();return t.send(u),this._logService.debug("[XHRHTTPImplementation]",`sending request to url ${s} with params ${o}`),()=>{t.readyState!==t.DONE&&t.abort(),t.removeEventListener("load",y),t.removeEventListener("error",l),t.removeEventListener("abort",l),t.removeEventListener("timeout",l)}})}};exports.XHRHTTPImplementation=ne([se(0,p.ILogService)],exports.XHRHTTPImplementation);var oe=Object.getOwnPropertyDescriptor,ie=(e,n,r,t)=>{for(var s=t>1?void 0:t?oe(n,r):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},$=(e,n)=>(r,t)=>n(r,t,e),k;exports.UniverNetworkPlugin=(k=class extends p.Plugin{constructor(n=void 0,r,t){super(),this._config=n,this._logger=r,this._injector=t}onStarting(){var t,s,o;if(this._injector.get(exports.HTTPService,p.Quantity.OPTIONAL,p.LookUp.SKIP_SELF)&&!((t=this._config)!=null&&t.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))}},f(k,"pluginName","UNIVER_NETWORK_PLUGIN"),k);exports.UniverNetworkPlugin=ie([$(1,p.ILogService),$(2,p.Inject(p.Injector))],exports.UniverNetworkPlugin);const ce=p.createIdentifier("univer.network.socket.service");class ae extends p.Disposable{createSocket(n){try{const r=new WebSocket(n),t=new p.DisposableCollection;return{URL:n,close:(o,i)=>{r.close(o,i),t.dispose()},send:o=>{r.send(o)},open$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("open",i),t.add(p.toDisposable(()=>r.removeEventListener("open",i)))}).pipe(E.share()),close$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("close",i),t.add(p.toDisposable(()=>r.removeEventListener("close",i)))}).pipe(E.share()),error$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("error",i),t.add(p.toDisposable(()=>r.removeEventListener("error",i)))}).pipe(E.share()),message$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("message",i),t.add(p.toDisposable(()=>r.removeEventListener("message",i)))}).pipe(E.share())}}catch(r){return console.error(r),null}}}const le=3,he=1e3,pe=e=>{var t,s;const n=(t=e==null?void 0:e.maxRetryAttempts)!=null?t:le,r=(s=e==null?void 0:e.delayInterval)!=null?s:he;return(o,i)=>i(o).pipe(E.retry({delay:r,count:n}))},de=e=>{const n=[],r=new Set,t=()=>{var s;for(;r.size<((s=e==null?void 0:e.maxParallel)!=null?s:1)&&n.length>0;){const o=n.shift();r.add(o),o()}};return(s,o)=>new w.Observable(i=>{const c=()=>o(s).subscribe({next:l=>i.next(l),error:l=>i.error(l),complete:()=>i.complete()}),y=()=>{r.delete(c),p.remove(n,c),t()};return n.push(c),t(),y})},ue=e=>{const{errorStatusCodes:n,onAuthError:r}=e;return(s,o)=>o(s).pipe(w.catchError(i=>(i instanceof I&&n.some(c=>c===i.status)&&r(),w.throwError(()=>i))))},ge=(e=300)=>{let r=()=>{};return t=>new Promise(s=>{r();const o=setTimeout(()=>{s(!0)},e);r=()=>{clearTimeout(o),s(!1)}})},me=()=>(e,n)=>n.map(r=>({config:r,result:e})),ye=(e,n={})=>{const{isMatch:r,getParamsFromRequest:t,mergeParamsToRequest:s}=e,{fetchCheck:o=ge(300),distributeResult:i=me()}=n,c=[],y=l=>l.map(u=>u.config);return(l,u)=>r(l)?new w.Observable(h=>{const a=t(l);c.push({next:g=>h.next(g),error:g=>h.error(g),config:a});const m=y(c);o(l).then(g=>{if(g){const v=[];m.forEach(d=>{const b=c.findIndex(R=>R.config===d);if(b>=0){const[R]=c.splice(b,1);v.push(R)}}),u(s(m,l)).subscribe({next:d=>{if(d.type===D.Response){const b=d.body,R=i(b,m);v.forEach(F=>{const q=R.find(N=>N.config===F.config);if(q){const N=new L({body:q.result,headers:d.headers,status:d.status,statusText:d.statusText});F.next(N)}else F.error("batch error")})}},complete:()=>h.complete(),error:d=>h.error(d)})}})}):u(l)};exports.AuthInterceptorFactory=ue;exports.HTTPEventType=D;exports.HTTPHeaders=_;exports.HTTPProgress=j;exports.HTTPRequest=O;exports.HTTPResponse=L;exports.HTTPResponseError=I;exports.HTTPStatusCode=x;exports.IHTTPImplementation=U;exports.ISocketService=ce;exports.MergeInterceptorFactory=ye;exports.ResponseHeader=B;exports.RetryInterceptorFactory=pe;exports.ThresholdInterceptorFactory=de;exports.WebSocketService=ae;
package/lib/es/index.js CHANGED
@@ -1,16 +1,16 @@
1
1
  var Z = Object.defineProperty;
2
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 p = (e, t, r) => P(e, typeof t != "symbol" ? t + "" : t, r);
3
+ var u = (e, t, r) => P(e, typeof t != "symbol" ? t + "" : t, r);
4
4
  import { createIdentifier as V, Disposable as J, toDisposable as R, remove as z, 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
- import { of as M, firstValueFrom as se, Observable as m, catchError as oe, throwError as ie } from "rxjs";
6
- import { concatMap as j, share as b, retry as ce } from "rxjs/operators";
5
+ import { of as j, firstValueFrom as se, Observable as m, catchError as oe, throwError as ie } from "rxjs";
6
+ import { concatMap as M, share as b, retry as ce } from "rxjs/operators";
7
7
  const U = "application/json";
8
8
  function ae(e) {
9
9
  return Array.isArray(e) ? e.some((t) => t.includes(U)) : e.includes(U);
10
10
  }
11
11
  class I {
12
12
  constructor(t) {
13
- p(this, "_headers", /* @__PURE__ */ new Map());
13
+ u(this, "_headers", /* @__PURE__ */ new Map());
14
14
  typeof t == "string" ? this._handleHeadersString(t) : t instanceof Headers ? this._handleHeaders(t) : t && this._handleHeadersConstructorProps(t);
15
15
  }
16
16
  forEach(t) {
@@ -66,7 +66,7 @@ class B {
66
66
  let le = 0;
67
67
  class G {
68
68
  constructor(t, r, n) {
69
- p(this, "uid", le++);
69
+ u(this, "uid", le++);
70
70
  this.method = t, this.url = r, this.requestParams = n;
71
71
  }
72
72
  get headers() {
@@ -93,17 +93,17 @@ class G {
93
93
  return this.headers.toHeadersInit((r = this.requestParams) == null ? void 0 : r.body);
94
94
  }
95
95
  }
96
- var he = Object.getOwnPropertyDescriptor, de = (e, t, r, n) => {
96
+ var he = Object.getOwnPropertyDescriptor, pe = (e, t, r, n) => {
97
97
  for (var s = n > 1 ? void 0 : n ? he(t, r) : t, o = e.length - 1, i; o >= 0; o--)
98
98
  (i = e[o]) && (s = i(s) || s);
99
99
  return s;
100
- }, pe = (e, t) => (r, n) => t(r, n, e);
100
+ }, de = (e, t) => (r, n) => t(r, n, e);
101
101
  let x = class extends J {
102
102
  constructor(t) {
103
103
  super();
104
- p(this, "_interceptors", []);
104
+ u(this, "_interceptors", []);
105
105
  // eslint-disable-next-line ts/no-explicit-any
106
- p(this, "_pipe");
106
+ u(this, "_pipe");
107
107
  this._http = t;
108
108
  }
109
109
  /**
@@ -121,46 +121,74 @@ let x = class extends J {
121
121
  }), this._pipe = null, R(() => z(this._interceptors, t));
122
122
  }
123
123
  get(t, r) {
124
- return this._request("GET", t, r);
124
+ return this.request("GET", t, r);
125
125
  }
126
126
  post(t, r) {
127
- return this._request("POST", t, r);
127
+ return this.request("POST", t, r);
128
128
  }
129
129
  put(t, r) {
130
- return this._request("PUT", t, r);
130
+ return this.request("PUT", t, r);
131
131
  }
132
132
  delete(t, r) {
133
- return this._request("DELETE", t, r);
133
+ return this.request("DELETE", t, r);
134
134
  }
135
135
  patch(t, r) {
136
- return this._request("PATCH", t, r);
136
+ return this.request("PATCH", t, r);
137
137
  }
138
- getSSE(t, r, n) {
139
- var c, y;
138
+ /**
139
+ * The HTTP request implementations. Normally you should use the `get`, `post`, `put`, `delete`,
140
+ * `patch` methods instead.
141
+ * @param method HTTP request method, e.g. GET, POST, PUT, DELETE, etc.
142
+ * @param url The URL to send the request to.
143
+ * @param options Optional parameters for the request.
144
+ * @returns A promise that resolves to the HTTP response.
145
+ */
146
+ async request(t, r, n) {
147
+ var l, h;
140
148
  const s = new I(n == null ? void 0 : n.headers), o = new B(n == null ? void 0 : n.params), i = new G(t, r, {
141
149
  headers: s,
142
150
  params: o,
143
- withCredentials: (c = n == null ? void 0 : n.withCredentials) != null ? c : !1,
144
- reportProgress: !0,
145
- responseType: (y = n == null ? void 0 : n.responseType) != null ? y : "json",
151
+ withCredentials: (l = n == null ? void 0 : n.withCredentials) != null ? l : !1,
152
+ // default value for withCredentials is false by MDN
153
+ responseType: (h = n == null ? void 0 : n.responseType) != null ? h : "json",
146
154
  body: ["GET", "DELETE"].includes(t) || n == null ? void 0 : n.body
147
- });
148
- return M(i).pipe(j((a) => this._runInterceptorsAndImplementation(a)));
155
+ }), c = j(i).pipe(
156
+ M((a) => this._runInterceptorsAndImplementation(a))
157
+ );
158
+ return await se(c);
149
159
  }
150
- /** The HTTP request implementations */
151
- async _request(t, r, n) {
152
- var a, h;
160
+ /**
161
+ * Send an HTTP request. It returns an observable that emits HTTP events. For example, it can be used to
162
+ * send Server-Sent Events (SSE) requests.
163
+ * @deprecated Please use `stream` method instead.
164
+ * @param method HTTP request method, e.g. GET, POST, PUT, DELETE, etc.
165
+ * @param url The URL to send the request to.
166
+ * @param _params Optional parameters for the request.
167
+ * @returns An observable of the HTTP event.
168
+ */
169
+ stream(t, r, n) {
170
+ return this.getSSE(t, r, n);
171
+ }
172
+ /**
173
+ * Send a Server-Sent Events (SSE) request. It returns an observable that emits HTTP events. It is the observable
174
+ * pair of the `request` method.
175
+ * @deprecated Please use `stream` method instead.
176
+ * @param method HTTP request method, e.g. GET, POST, PUT, DELETE, etc.
177
+ * @param url The URL to send the request to.
178
+ * @param _params Optional parameters for the request.
179
+ * @returns An observable of the HTTP event.
180
+ */
181
+ getSSE(t, r, n) {
182
+ var c, d;
153
183
  const s = new I(n == null ? void 0 : n.headers), o = new B(n == null ? void 0 : n.params), i = new G(t, r, {
154
184
  headers: s,
155
185
  params: o,
156
- withCredentials: (a = n == null ? void 0 : n.withCredentials) != null ? a : !1,
157
- // default value for withCredentials is false by MDN
158
- responseType: (h = n == null ? void 0 : n.responseType) != null ? h : "json",
186
+ withCredentials: (c = n == null ? void 0 : n.withCredentials) != null ? c : !1,
187
+ reportProgress: !0,
188
+ responseType: (d = n == null ? void 0 : n.responseType) != null ? d : "json",
159
189
  body: ["GET", "DELETE"].includes(t) || n == null ? void 0 : n.body
160
- }), c = M(i).pipe(
161
- j((l) => this._runInterceptorsAndImplementation(l))
162
- );
163
- return await se(c);
190
+ });
191
+ return j(i).pipe(M((l) => this._runInterceptorsAndImplementation(l)));
164
192
  }
165
193
  // eslint-disable-next-line ts/no-explicit-any
166
194
  _runInterceptorsAndImplementation(t) {
@@ -174,8 +202,8 @@ let x = class extends J {
174
202
  );
175
203
  }
176
204
  };
177
- x = de([
178
- pe(0, K)
205
+ x = pe([
206
+ de(0, K)
179
207
  ], x);
180
208
  function ue(e, t) {
181
209
  return (r, n) => t(r, (s) => e(s, n));
@@ -189,17 +217,17 @@ class $ {
189
217
  status: n,
190
218
  statusText: s
191
219
  }) {
192
- p(this, "type", 1);
193
- p(this, "body");
194
- p(this, "headers");
195
- p(this, "status");
196
- p(this, "statusText");
220
+ u(this, "type", 1);
221
+ u(this, "body");
222
+ u(this, "headers");
223
+ u(this, "status");
224
+ u(this, "statusText");
197
225
  this.body = t, this.headers = r, this.status = n, this.statusText = s;
198
226
  }
199
227
  }
200
228
  class ye {
201
229
  constructor(t, r, n) {
202
- p(this, "type", 0);
230
+ u(this, "type", 0);
203
231
  this.total = t, this.loaded = r, this.partialText = n;
204
232
  }
205
233
  }
@@ -216,11 +244,11 @@ class v {
216
244
  statusText: s,
217
245
  error: o
218
246
  }) {
219
- p(this, "request");
220
- p(this, "headers");
221
- p(this, "status");
222
- p(this, "statusText");
223
- p(this, "error");
247
+ u(this, "request");
248
+ u(this, "headers");
249
+ u(this, "status");
250
+ u(this, "statusText");
251
+ u(this, "error");
224
252
  this.request = t, this.headers = r, this.status = n, this.statusText = s, this.error = o;
225
253
  }
226
254
  }
@@ -236,7 +264,7 @@ var me = Object.getOwnPropertyDescriptor, ve = (e, t, r, n) => {
236
264
  for (var s = n > 1 ? void 0 : n ? me(t, r) : t, o = e.length - 1, i; o >= 0; o--)
237
265
  (i = e[o]) && (s = i(s) || s);
238
266
  return s;
239
- }, _e = (e, t) => (r, n) => t(r, n, e);
267
+ }, Ee = (e, t) => (r, n) => t(r, n, e);
240
268
  let N = class {
241
269
  constructor(e) {
242
270
  this._logService = e;
@@ -253,23 +281,23 @@ let N = class {
253
281
  });
254
282
  }
255
283
  async _send(e, t, r) {
256
- var a, h;
284
+ var l, h;
257
285
  let n;
258
286
  try {
259
- const l = Q(e), w = e.getUrlWithParams(), d = fetch(w, {
287
+ const a = Q(e), g = e.getUrlWithParams(), p = fetch(g, {
260
288
  signal: r.signal,
261
- ...l
289
+ ...a
262
290
  });
263
- this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${w} with params ${l}`), n = await d;
264
- } catch (l) {
265
- const w = new v({
291
+ this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${g} with params ${a}`), n = await p;
292
+ } catch (a) {
293
+ const g = new v({
266
294
  request: e,
267
- error: l,
268
- status: (a = l.status) != null ? a : 0,
269
- statusText: (h = l.statusText) != null ? h : "Unknown Error",
270
- headers: l.headers
295
+ error: a,
296
+ status: (l = a.status) != null ? l : 0,
297
+ statusText: (h = a.statusText) != null ? h : "Unknown Error",
298
+ headers: a.headers
271
299
  });
272
- this._logService.error("[FetchHTTPImplementation]: network error", w), t.error(w);
300
+ this._logService.error("[FetchHTTPImplementation]: network error", g), t.error(g);
273
301
  return;
274
302
  }
275
303
  const s = new I(n.headers), o = n.status, i = n.statusText;
@@ -282,52 +310,52 @@ let N = class {
282
310
  statusText: i
283
311
  }));
284
312
  else {
285
- const l = new v({
313
+ const a = new v({
286
314
  request: e,
287
315
  error: c,
288
316
  status: o,
289
317
  statusText: i,
290
318
  headers: s
291
319
  });
292
- this._logService.error("[FetchHTTPImplementation]: network error", l), t.error(l);
320
+ this._logService.error("[FetchHTTPImplementation]: network error", a), t.error(a);
293
321
  }
294
322
  t.complete();
295
323
  }
296
324
  async _readBody(e, t, r) {
297
- var w, d;
325
+ var g, p;
298
326
  const n = [], s = t.body.getReader(), o = t.headers.get("content-length");
299
327
  let i = 0;
300
- const c = (w = e.requestParams) == null ? void 0 : w.reportProgress, y = e.responseType;
301
- let a, h;
328
+ const c = (g = e.requestParams) == null ? void 0 : g.reportProgress, d = e.responseType;
329
+ let l, h;
302
330
  for (; ; ) {
303
- const { done: u, value: f } = await s.read();
304
- if (u) break;
305
- n.push(f), i += f.length, c && y === "text" && (a = (a != null ? a : "") + (h != null ? h : h = new TextDecoder()).decode(f, { stream: !0 }), r.next(new ye(
331
+ const { done: f, value: y } = await s.read();
332
+ if (f) break;
333
+ n.push(y), i += y.length, c && d === "text" && (l = (l != null ? l : "") + (h != null ? h : h = new TextDecoder()).decode(y, { stream: !0 }), r.next(new ye(
306
334
  o ? Number.parseInt(o, 10) : void 0,
307
335
  i,
308
- a
336
+ l
309
337
  )));
310
338
  }
311
- const l = Ee(n, i);
339
+ const a = _e(n, i);
312
340
  try {
313
- const u = (d = t.headers.get("content-type")) != null ? d : "";
314
- return Ie(e, l, u);
315
- } catch (u) {
316
- const f = new v({
341
+ const f = (p = t.headers.get("content-type")) != null ? p : "";
342
+ return Ie(e, a, f);
343
+ } catch (f) {
344
+ const y = new v({
317
345
  request: e,
318
- error: u,
346
+ error: f,
319
347
  status: t.status,
320
348
  statusText: t.statusText,
321
349
  headers: new I(t.headers)
322
350
  });
323
- return this._logService.error("[FetchHTTPImplementation]: network error", f), r.error(f), null;
351
+ return this._logService.error("[FetchHTTPImplementation]: network error", y), r.error(y), null;
324
352
  }
325
353
  }
326
354
  };
327
355
  N = ve([
328
- _e(0, D)
356
+ Ee(0, D)
329
357
  ], N);
330
- function Ee(e, t) {
358
+ function _e(e, t) {
331
359
  const r = new Uint8Array(t);
332
360
  let n = 0;
333
361
  for (const s of e)
@@ -361,57 +389,57 @@ let O = class {
361
389
  }
362
390
  send(e) {
363
391
  return new m((t) => {
364
- const r = new XMLHttpRequest(), n = e.getUrlWithParams(), s = Q(e);
365
- r.open(e.method, n), e.withCredentials && (r.withCredentials = !0), s.headers && Object.entries(s.headers).forEach(([a, h]) => r.setRequestHeader(a, h));
366
- const o = () => {
367
- const a = r.statusText || "OK", h = new I(r.getAllResponseHeaders());
368
- return new we(h, r.status, a);
369
- }, i = () => {
370
- const { headers: a, statusText: h, status: l } = o(), { responseType: w } = e;
371
- let d = null, u = null;
372
- l !== L.NoContent && (d = typeof r.response > "u" ? r.responseText : r.response);
373
- let f = l >= ge && l < fe;
374
- if (w === "json" && typeof d == "string") {
375
- const g = d;
392
+ const r = new XMLHttpRequest(), n = e.getUrlWithParams(), s = Q(e), { responseType: o } = e;
393
+ r.open(e.method, n), e.withCredentials && (r.withCredentials = !0), s.headers && Object.entries(s.headers).forEach(([h, a]) => r.setRequestHeader(h, a));
394
+ const i = () => {
395
+ const h = r.statusText || "OK", a = new I(r.getAllResponseHeaders());
396
+ return new we(a, r.status, h);
397
+ }, c = () => {
398
+ const { headers: h, statusText: a, status: g } = i();
399
+ let p = null, f = null;
400
+ g !== L.NoContent && (p = typeof r.response > "u" ? r.responseText : r.response);
401
+ let y = g >= ge && g < fe;
402
+ if (o === "json" && typeof p == "string") {
403
+ const w = p;
376
404
  try {
377
- d = d ? JSON.parse(d) : null;
378
- } catch (_) {
379
- f = !1, d = g, u = _;
405
+ p = p ? JSON.parse(p) : null;
406
+ } catch (E) {
407
+ y = !1, p = w, f = E;
380
408
  }
381
409
  }
382
- if (f)
410
+ if (o === "blob" && !(p instanceof Blob) && (y = !1, f = new Error("Response is not a Blob object")), y)
383
411
  t.next(
384
412
  new $({
385
- body: d,
386
- headers: a,
387
- status: l,
388
- statusText: h
413
+ body: p,
414
+ headers: h,
415
+ status: g,
416
+ statusText: a
389
417
  })
390
418
  );
391
419
  else {
392
- const g = new v({
420
+ const w = new v({
393
421
  request: e,
394
- error: u,
395
- headers: a,
396
- status: l,
397
- statusText: h
422
+ error: f,
423
+ headers: h,
424
+ status: g,
425
+ statusText: a
398
426
  });
399
- this._logService.error("[XHRHTTPImplementation]: network error", g), t.error(g);
427
+ this._logService.error("[XHRHTTPImplementation]: network error", w), t.error(w);
400
428
  }
401
- }, c = (a) => {
402
- const h = new v({
429
+ }, d = (h) => {
430
+ const a = new v({
403
431
  request: e,
404
- error: a,
432
+ error: h,
405
433
  status: r.status || 0,
406
434
  statusText: r.statusText || "Unknown Error",
407
- headers: o().headers
435
+ headers: i().headers
408
436
  });
409
- this._logService.error("[XHRHTTPImplementation]: network error", h), t.error(h);
437
+ this._logService.error("[XHRHTTPImplementation]: network error", a), t.error(a);
410
438
  };
411
- r.addEventListener("load", i), r.addEventListener("error", c), r.addEventListener("abort", c), r.addEventListener("timeout", c);
412
- const y = e.getBody();
413
- return r.send(y), this._logService.debug("[XHRHTTPImplementation]", `sending request to url ${n} with params ${s}`), () => {
414
- r.readyState !== r.DONE && r.abort(), r.removeEventListener("load", i), r.removeEventListener("error", c), r.removeEventListener("abort", c), r.removeEventListener("timeout", c);
439
+ r.responseType = o || "", r.addEventListener("load", c), r.addEventListener("error", d), r.addEventListener("abort", d), r.addEventListener("timeout", d);
440
+ const l = e.getBody();
441
+ return r.send(l), this._logService.debug("[XHRHTTPImplementation]", `sending request to url ${n} with params ${s}`), () => {
442
+ r.readyState !== r.DONE && r.abort(), r.removeEventListener("load", c), r.removeEventListener("error", d), r.removeEventListener("abort", d), r.removeEventListener("timeout", d);
415
443
  };
416
444
  });
417
445
  }
@@ -443,12 +471,12 @@ let X = (k = class extends C {
443
471
  [K, { useClass: t }]
444
472
  ], (s = this._config) == null ? void 0 : s.override));
445
473
  }
446
- }, p(k, "pluginName", "UNIVER_NETWORK_PLUGIN"), k);
474
+ }, u(k, "pluginName", "UNIVER_NETWORK_PLUGIN"), k);
447
475
  X = Ae([
448
476
  W(1, D),
449
477
  W(2, S(H))
450
478
  ], X);
451
- const je = V("univer.network.socket.service");
479
+ const Me = V("univer.network.socket.service");
452
480
  class Be extends J {
453
481
  createSocket(t) {
454
482
  try {
@@ -497,13 +525,13 @@ const Fe = 3, ke = 1e3, Ge = (e) => {
497
525
  };
498
526
  return (s, o) => new m((i) => {
499
527
  const c = () => o(s).subscribe({
500
- next: (a) => i.next(a),
501
- error: (a) => i.error(a),
528
+ next: (l) => i.next(l),
529
+ error: (l) => i.error(l),
502
530
  complete: () => i.complete()
503
- }), y = () => {
531
+ }), d = () => {
504
532
  r.delete(c), z(t, c), n();
505
533
  };
506
- return t.push(c), n(), y;
534
+ return t.push(c), n(), d;
507
535
  });
508
536
  }, Xe = (e) => {
509
537
  const { errorStatusCodes: t, onAuthError: r } = e;
@@ -523,36 +551,36 @@ const Fe = 3, ke = 1e3, Ge = (e) => {
523
551
  };
524
552
  });
525
553
  }, Oe = () => (e, t) => t.map((r) => ({ config: r, result: e })), Ve = (e, t = {}) => {
526
- const { isMatch: r, getParamsFromRequest: n, mergeParamsToRequest: s } = e, { fetchCheck: o = Ue(300), distributeResult: i = Oe() } = t, c = [], y = (a) => a.map((h) => h.config);
527
- return (a, h) => r(a) ? new m((l) => {
528
- const w = n(a);
554
+ const { isMatch: r, getParamsFromRequest: n, mergeParamsToRequest: s } = e, { fetchCheck: o = Ue(300), distributeResult: i = Oe() } = t, c = [], d = (l) => l.map((h) => h.config);
555
+ return (l, h) => r(l) ? new m((a) => {
556
+ const g = n(l);
529
557
  c.push({
530
- next: (u) => l.next(u),
531
- error: (u) => l.error(u),
532
- config: w
558
+ next: (f) => a.next(f),
559
+ error: (f) => a.error(f),
560
+ config: g
533
561
  });
534
- const d = y(c);
535
- o(a).then((u) => {
536
- if (u) {
537
- const f = [];
538
- d.forEach((g) => {
539
- const _ = c.findIndex((E) => E.config === g);
540
- if (_ >= 0) {
541
- const [E] = c.splice(_, 1);
542
- f.push(E);
562
+ const p = d(c);
563
+ o(l).then((f) => {
564
+ if (f) {
565
+ const y = [];
566
+ p.forEach((w) => {
567
+ const E = c.findIndex((_) => _.config === w);
568
+ if (E >= 0) {
569
+ const [_] = c.splice(E, 1);
570
+ y.push(_);
543
571
  }
544
- }), h(s(d, a)).subscribe({
545
- next: (g) => {
546
- if (g.type === Y.Response) {
547
- const _ = g.body, E = i(_, d);
548
- f.forEach((A) => {
549
- const q = E.find((F) => F.config === A.config);
572
+ }), h(s(p, l)).subscribe({
573
+ next: (w) => {
574
+ if (w.type === Y.Response) {
575
+ const E = w.body, _ = i(E, p);
576
+ y.forEach((A) => {
577
+ const q = _.find((F) => F.config === A.config);
550
578
  if (q) {
551
579
  const F = new $({
552
580
  body: q.result,
553
- headers: g.headers,
554
- status: g.status,
555
- statusText: g.statusText
581
+ headers: w.headers,
582
+ status: w.status,
583
+ statusText: w.statusText
556
584
  });
557
585
  A.next(F);
558
586
  } else
@@ -560,12 +588,12 @@ const Fe = 3, ke = 1e3, Ge = (e) => {
560
588
  });
561
589
  }
562
590
  },
563
- complete: () => l.complete(),
564
- error: (g) => l.error(g)
591
+ complete: () => a.complete(),
592
+ error: (w) => a.error(w)
565
593
  });
566
594
  }
567
595
  });
568
- }) : h(a);
596
+ }) : h(l);
569
597
  };
570
598
  export {
571
599
  Xe as AuthInterceptorFactory,
@@ -579,7 +607,7 @@ export {
579
607
  x as HTTPService,
580
608
  L as HTTPStatusCode,
581
609
  K as IHTTPImplementation,
582
- je as ISocketService,
610
+ Me as ISocketService,
583
611
  Ve as MergeInterceptorFactory,
584
612
  we as ResponseHeader,
585
613
  Ge as RetryInterceptorFactory,