@univerjs/network 0.5.5 → 0.6.0-experimental.20250125-1d060b9
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 +1 -1
- package/lib/es/facade.js +22 -22
- package/lib/es/index.js +186 -183
- package/lib/types/facade/f-network.d.ts +29 -22
- package/lib/types/facade/f-univer.d.ts +3 -0
- package/lib/types/services/http/params.d.ts +4 -2
- package/lib/umd/index.js +2 -2
- package/package.json +4 -4
- package/LICENSE +0 -176
- package/lib/types/services/http/interceptors/__tests__/merge-interceptor.spec.d.ts +0 -16
- package/lib/types/services/http/interceptors/__tests__/retry-interceptor.spec.d.ts +0 -16
- package/lib/types/services/http/interceptors/__tests__/threshold-interceptor.spec.d.ts +0 -16
- /package/lib/types/services/http/{interceptors/__tests__/auth-interceptor.spec.d.ts → __testing__/http-params.spec.d.ts} +0 -0
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);
|