@univerjs/network 0.2.4 → 0.2.6
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 +2 -2
- package/lib/es/index.js +413 -394
- package/lib/types/services/http/__testing__/http-testing-utils.d.ts +1 -2
- package/lib/types/services/http/http.service.d.ts +1 -2
- package/lib/types/services/http/implementations/implementation.d.ts +1 -1
- package/lib/types/services/web-socket/web-socket.service.d.ts +1 -1
- package/lib/umd/index.js +2 -2
- package/package.json +7 -9
package/lib/cjs/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
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 M=O.createIdentifier("network.http-implementation");class D{constructor(t){this.params=t}toString(){return this.params?Object.keys(this.params).map(t=>`${t}=${this.params[t]}`).join("&"):""}}let V=0;class q{constructor(t,r,n){y(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:U,r=(s=this.requestParams)==null?void 0:s.body;return t===U&&r&&typeof r=="object"?JSON.stringify(r):r?`${r}`:null}getHeadersInit(){return this.headers.toHeadersInit()}}var W=Object.defineProperty,X=Object.getOwnPropertyDescriptor,z=(e,t,r,n)=>{for(var s=n>1?void 0:n?X(t,r):t,c=e.length-1,o;c>=0;c--)(o=e[c])&&(s=(n?o(t,r,s):o(s))||s);return n&&s&&W(t,r,s),s},J=(e,t)=>(r,n)=>t(r,n,e);exports.HTTPService=class extends b.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((n,s)=>{var c,o;return((c=n.priority)!=null?c:0)-((o=s.priority)!=null?o:0)}),this._pipe=null,b.toDisposable(()=>b.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 h,a;const c=new E(s==null?void 0:s.headers),o=new D(s==null?void 0:s.params),i=new q(r,n,{headers:c,params:o,withCredentials:(h=s==null?void 0:s.withCredentials)!=null?h:!1,reportProgress:!0,responseType:(a=s==null?void 0:s.responseType)!=null?a:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body});return m.of(i).pipe(v.concatMap(l=>this._runInterceptorsAndImplementation(l)))}async _request(r,n,s){var l,p;const c=new E(s==null?void 0:s.headers),o=new D(s==null?void 0:s.params),i=new q(r,n,{headers:c,params:o,withCredentials:(l=s==null?void 0:s.withCredentials)!=null?l:!1,responseType:(p=s==null?void 0:s.responseType)!=null?p:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body}),h=m.of(i).pipe(v.concatMap(d=>this._runInterceptorsAndImplementation(d)));return await m.firstValueFrom(h)}_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=z([J(0,M)],exports.HTTPService);function Y(e,t){return(r,n)=>t(r,s=>e(s,n))}var N=(e=>(e[e.DownloadProgress=0]="DownloadProgress",e[e.Response=1]="Response",e))(N||{});class L{constructor({body:t,headers:r,status:n,statusText:s}){y(this,"type",1);y(this,"body");y(this,"headers");y(this,"status");y(this,"statusText");this.body=t,this.headers=r,this.status=n,this.statusText=s}}class j{constructor(t,r,n){y(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 R{constructor({headers:t,status:r,statusText:n,error:s}){y(this,"headers");y(this,"status");y(this,"statusText");y(this,"error");this.headers=t,this.status=r,this.statusText=n,this.error=s}}const K=200,Q=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||{});class Z{send(t){return new m.Observable(r=>{const n=new AbortController;return this._send(t,r,n).then(()=>{},s=>{r.error(new R({error:s}))}),()=>n.abort()})}async _send(t,r,n){var l,p;let s;try{const d=this._parseFetchParamsFromRequest(t);s=await fetch(t.getUrlWithParams(),{signal:n.signal,...d})}catch(d){r.error(new R({error:d,status:(l=d.status)!=null?l:0,statusText:(p=d.statusText)!=null?p:"Unknown Error",headers:d.headers}));return}const c=new E(s.headers),o=s.status,i=s.statusText;let h=null;s.body&&(h=await this._readBody(t,s,r)),o>=x.Ok&&o<x.MultipleChoices?r.next(new L({body:h,headers:c,status:o,statusText:i})):r.error(new R({error:h,status:o,statusText:i,headers:c})),r.complete()}async _readBody(t,r,n){var w,f;const s=[],c=r.body.getReader(),o=r.headers.get("content-length");let i=0;const h=(w=t.requestParams)==null?void 0:w.reportProgress,a=t.responseType;let l,p;for(;;){const{done:g,value:u}=await c.read();if(g)break;s.push(u),i+=u.length,h&&a==="text"&&(l=(l!=null?l:"")+(p!=null?p:p=new TextDecoder).decode(u,{stream:!0}),n.next(new j(o?Number.parseInt(o,10):void 0,i,l)))}const d=P(s,i);try{const g=(f=r.headers.get("content-type"))!=null?f:"";return S(t,d,g)}catch(g){return n.error(new R({error:g,status:r.status,statusText:r.statusText,headers:new E(r.headers)})),null}}_parseFetchParamsFromRequest(t){return{method:t.method,headers:t.getHeadersInit(),body:t.getBody(),credentials:t.withCredentials?"include":void 0}}}function P(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 H=/^\)\]\}',?\n/;function S(e,t,r){switch(e.responseType){case"json":const n=new TextDecoder().decode(t).replace(H,"");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}.`)}}class C{send(t){return new m.Observable(r=>{const n=new XMLHttpRequest;n.open(t.method,t.getUrlWithParams()),t.withCredentials&&(n.withCredentials=!0),t.headers.forEach((h,a)=>n.setRequestHeader(h,a.join(","))),t.headers.has("Accept")||n.setRequestHeader("Accept","application/json, text/plain, */*"),t.headers.has("Content-Type")||n.setRequestHeader("Content-Type","application/json;charset=UTF-8");const s=()=>{const h=n.statusText||"OK",a=new E(n.getAllResponseHeaders());return new B(a,n.status,h)},c=()=>{const{headers:h,statusText:a,status:l}=s(),{responseType:p}=t;let d=null,w=null;l!==x.NoContent&&(d=typeof n.response>"u"?n.responseText:n.response);let f=l>=K&&l<Q;if(p==="json"&&typeof d=="string"){const g=d;try{d=d?JSON.parse(d):null}catch(u){f=!1,d=g,w=u}}f?r.next(new L({body:d,headers:h,status:l,statusText:a})):r.error(new R({error:w,headers:h,status:l,statusText:a}))},o=h=>{const a=new R({error:h,status:n.status||0,statusText:n.statusText||"Unknown Error",headers:s().headers});r.error(a)};n.addEventListener("load",c),n.addEventListener("error",o),n.addEventListener("abort",o),n.addEventListener("timeout",o);const i=t.getBody();return n.send(i),()=>{n.readyState!==n.DONE&&n.abort(),n.removeEventListener("load",c),n.removeEventListener("error",o),n.removeEventListener("abort",o),n.removeEventListener("timeout",o)}})}}const T=O.createIdentifier("univer.socket");class ee extends b.Disposable{createSocket(t){try{const r=new WebSocket(t),n=new b.DisposableCollection;return{URL:t,close:(c,o)=>{r.close(c,o),n.dispose()},send:c=>{r.send(c)},open$:new m.Observable(c=>{const o=i=>c.next(i);r.addEventListener("open",o),n.add(b.toDisposable(()=>r.removeEventListener("open",o)))}).pipe(v.share()),close$:new m.Observable(c=>{const o=i=>c.next(i);r.addEventListener("close",o),n.add(b.toDisposable(()=>r.removeEventListener("close",o)))}).pipe(v.share()),error$:new m.Observable(c=>{const o=i=>c.next(i);r.addEventListener("error",o),n.add(b.toDisposable(()=>r.removeEventListener("error",o)))}).pipe(v.share()),message$:new m.Observable(c=>{const o=i=>c.next(i);r.addEventListener("message",o),n.add(b.toDisposable(()=>r.removeEventListener("message",o)))}).pipe(v.share())}}catch(r){return console.error(r),null}}}const re=3,te=1e3,ne=(e,t)=>{var s,c;const r=(s=t==null?void 0:t.maxRetryAttempts)!=null?s:re,n=(c=t==null?void 0:t.delayInterval)!=null?c:te;return(o,i)=>i(o).pipe(v.retry({delay:n,count:r}))},se=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 c=t.shift();r.add(c),c()}};return(s,c)=>new m.Observable(o=>{const i=()=>c(s).subscribe({next:a=>o.next(a),error:a=>o.next(a),complete:()=>o.complete()}),h=()=>{r.delete(i),b.remove(t,i),n()};return t.push(i),n(),h})},oe=e=>{const{errorStatusCodes:t,onAuthError:r}=e;return(s,c)=>c(s).pipe(m.catchError(o=>(o instanceof R&&t.some(i=>i===o.status)&&r(),m.throwError(()=>o))))},ce=(e=300)=>{let r=()=>{};return n=>new Promise(s=>{r();const c=setTimeout(()=>{s(!0)},e);r=()=>{clearTimeout(c),s(!1)}})},ie=()=>(e,t)=>t.map(r=>({config:r,result:e})),ae=(e,t={})=>{const{isMatch:r,getParamsFromRequest:n,mergeParamsToRequest:s}=e,{fetchCheck:c=ce(300),distributeResult:o=ie()}=t,i=[],h=a=>a.map(l=>l.config);return(a,l)=>r(a)?new m.Observable(p=>{const d=n(a);i.push({next:f=>p.next(f),error:f=>p.error(f),config:d});const w=h(i);c(a).then(f=>{if(f){const g=[];w.forEach(u=>{const I=i.findIndex(_=>_.config===u);if(I>=0){const[_]=i.splice(I,1);g.push(_)}}),l(s(w,a)).subscribe({next:u=>{if(u.type===N.Response){const I=u.body,_=o(I,w);g.forEach(F=>{const k=_.find(A=>A.config===F.config);if(k){const A=new L({body:k.result,headers:u.headers,status:u.status,statusText:u.statusText});F.next(A)}else F.error("batch error")})}},complete:()=>p.complete(),error:u=>p.error(u)})}})}):l(a)};exports.AuthInterceptorFactory=oe;exports.FetchHTTPImplementation=Z;exports.HTTPEventType=N;exports.HTTPHeaders=E;exports.HTTPProgress=j;exports.HTTPRequest=q;exports.HTTPResponse=L;exports.HTTPResponseError=R;exports.HTTPStatusCode=x;exports.IHTTPImplementation=M;exports.ISocketService=T;exports.MergeInterceptorFactory=ae;exports.ResponseHeader=B;exports.RetryInterceptorFactory=ne;exports.ThresholdInterceptorFactory=se;exports.WebSocketService=ee;exports.XHRHTTPImplementation=C;
|
|
1
|
+
"use strict";var __defProp=Object.defineProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!="symbol"?key+"":key,value);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const core=require("@univerjs/core"),rxjs=require("rxjs"),operators=require("rxjs/operators"),ApplicationJSONType="application/json",_HTTPHeaders=class _HTTPHeaders{constructor(headers){__publicField(this,"_headers",new Map);typeof headers=="string"?this._handleHeadersString(headers):headers instanceof Headers?this._handleHeaders(headers):headers&&this._handleHeadersConstructorProps(headers)}forEach(callback){this._headers.forEach((v,key)=>callback(key,v))}has(key){return!!this._headers.has(key.toLowerCase())}get(key){const k=key.toLowerCase();return this._headers.has(k)?this._headers.get(k):null}toHeadersInit(){var _a2,_b;const headers={};return this._headers.forEach((values,key)=>{headers[key]=values.join(",")}),(_a2=headers.accept)!=null||(headers.accept="application/json, text/plain, */*"),(_b=headers["content-type"])!=null||(headers["content-type"]="application/json;charset=UTF-8"),headers}_setHeader(name,value){const lowerCase=name.toLowerCase();this._headers.has(lowerCase)?this._headers.get(lowerCase).push(value.toString()):this._headers.set(lowerCase,[value.toString()])}_handleHeadersString(headers){headers.split(`
|
|
2
|
+
`).forEach(header=>{const[name,value]=header.split(":");name&&value&&this._setHeader(name,value)})}_handleHeadersConstructorProps(headers){Object.entries(headers).forEach(([name,value])=>this._setHeader(name,value))}_handleHeaders(headers){headers.forEach((value,name)=>this._setHeader(name,value))}};__name(_HTTPHeaders,"HTTPHeaders");let HTTPHeaders=_HTTPHeaders;const IHTTPImplementation=core.createIdentifier("network.http-implementation"),_HTTPParams=class _HTTPParams{constructor(params){this.params=params}toString(){return this.params?Object.keys(this.params).map(key=>`${key}=${this.params[key]}`).join("&"):""}};__name(_HTTPParams,"HTTPParams");let HTTPParams=_HTTPParams,HTTPRequestUID=0;const _HTTPRequest=class _HTTPRequest{constructor(method,url,requestParams){__publicField(this,"uid",HTTPRequestUID++);this.method=method,this.url=url,this.requestParams=requestParams}get headers(){return this.requestParams.headers}get withCredentials(){return this.requestParams.withCredentials}get responseType(){return this.requestParams.responseType}getUrlWithParams(){var _a2,_b;const params=(_b=(_a2=this.requestParams)==null?void 0:_a2.params)==null?void 0:_b.toString();return params?`${this.url}${this.url.includes("?")?"&":"?"}${params}`:this.url}getBody(){var _a2,_b;const contentType=(_a2=this.headers.get("Content-Type"))!=null?_a2:ApplicationJSONType,body=(_b=this.requestParams)==null?void 0:_b.body;return contentType===ApplicationJSONType&&body&&typeof body=="object"?JSON.stringify(body):body?`${body}`:null}getHeadersInit(){return this.headers.toHeadersInit()}};__name(_HTTPRequest,"HTTPRequest");let HTTPRequest=_HTTPRequest;var __defProp2=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__decorateClass=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp2(target,key,result),result},"__decorateClass"),__decorateParam=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam"),_a;exports.HTTPService=(_a=class extends core.Disposable{constructor(_http){super();__publicField(this,"_interceptors",[]);__publicField(this,"_pipe");this._http=_http}registerHTTPInterceptor(interceptor){if(this._interceptors.indexOf(interceptor)!==-1)throw new Error("[HTTPService]: The interceptor has already been registered!");return this._interceptors.push(interceptor),this._interceptors=this._interceptors.sort((a,b)=>{var _a2,_b;return((_a2=a.priority)!=null?_a2:0)-((_b=b.priority)!=null?_b:0)}),this._pipe=null,core.toDisposable(()=>core.remove(this._interceptors,interceptor))}get(url,params){return this._request("GET",url,params)}post(url,params){return this._request("POST",url,params)}put(url,params){return this._request("PUT",url,params)}delete(url,params){return this._request("DELETE",url,params)}patch(url,options){return this._request("PATCH",url,options)}getSSE(method,url,options){var _a2,_b;const headers=new HTTPHeaders(options==null?void 0:options.headers),params=new HTTPParams(options==null?void 0:options.params),request=new HTTPRequest(method,url,{headers,params,withCredentials:(_a2=options==null?void 0:options.withCredentials)!=null?_a2:!1,reportProgress:!0,responseType:(_b=options==null?void 0:options.responseType)!=null?_b:"json",body:["GET","DELETE"].includes(method)||options==null?void 0:options.body});return rxjs.of(request).pipe(operators.concatMap(request2=>this._runInterceptorsAndImplementation(request2)))}async _request(method,url,options){var _a2,_b;const headers=new HTTPHeaders(options==null?void 0:options.headers),params=new HTTPParams(options==null?void 0:options.params),request=new HTTPRequest(method,url,{headers,params,withCredentials:(_a2=options==null?void 0:options.withCredentials)!=null?_a2:!1,responseType:(_b=options==null?void 0:options.responseType)!=null?_b:"json",body:["GET","DELETE"].includes(method)||options==null?void 0:options.body}),events$=rxjs.of(request).pipe(operators.concatMap(request2=>this._runInterceptorsAndImplementation(request2)));return await rxjs.firstValueFrom(events$)}_runInterceptorsAndImplementation(request){return this._pipe||(this._pipe=this._interceptors.map(handler=>handler.interceptor).reduceRight((nextHandlerFunction,interceptorFunction)=>chainInterceptorFn(nextHandlerFunction,interceptorFunction),(requestFromPrevInterceptor,finalHandler)=>finalHandler(requestFromPrevInterceptor))),this._pipe(request,requestToNext=>this._http.send(requestToNext))}},__name(_a,"HTTPService"),_a);exports.HTTPService=__decorateClass([__decorateParam(0,IHTTPImplementation)],exports.HTTPService);function chainInterceptorFn(afterInterceptorChain,currentInterceptorFn){return(prevRequest,nextHandlerFn)=>currentInterceptorFn(prevRequest,nextRequest=>afterInterceptorChain(nextRequest,nextHandlerFn))}__name(chainInterceptorFn,"chainInterceptorFn");var HTTPEventType=(HTTPEventType2=>(HTTPEventType2[HTTPEventType2.DownloadProgress=0]="DownloadProgress",HTTPEventType2[HTTPEventType2.Response=1]="Response",HTTPEventType2))(HTTPEventType||{});const _HTTPResponse=class _HTTPResponse{constructor({body,headers,status,statusText}){__publicField(this,"type",1);__publicField(this,"body");__publicField(this,"headers");__publicField(this,"status");__publicField(this,"statusText");this.body=body,this.headers=headers,this.status=status,this.statusText=statusText}};__name(_HTTPResponse,"HTTPResponse");let HTTPResponse=_HTTPResponse;const _HTTPProgress=class _HTTPProgress{constructor(total,loaded,partialText){__publicField(this,"type",0);this.total=total,this.loaded=loaded,this.partialText=partialText}};__name(_HTTPProgress,"HTTPProgress");let HTTPProgress=_HTTPProgress;const _ResponseHeader=class _ResponseHeader{constructor(headers,status,statusText){this.headers=headers,this.status=status,this.statusText=statusText}};__name(_ResponseHeader,"ResponseHeader");let ResponseHeader=_ResponseHeader;const _HTTPResponseError=class _HTTPResponseError{constructor({headers,status,statusText,error}){__publicField(this,"headers");__publicField(this,"status");__publicField(this,"statusText");__publicField(this,"error");this.headers=headers,this.status=status,this.statusText=statusText,this.error=error}};__name(_HTTPResponseError,"HTTPResponseError");let HTTPResponseError=_HTTPResponseError;const SuccessStatusCodeLowerBound=200,ErrorStatusCodeLowerBound=300;var HTTPStatusCode=(HTTPStatusCode2=>(HTTPStatusCode2[HTTPStatusCode2.Continue=100]="Continue",HTTPStatusCode2[HTTPStatusCode2.SwitchingProtocols=101]="SwitchingProtocols",HTTPStatusCode2[HTTPStatusCode2.Processing=102]="Processing",HTTPStatusCode2[HTTPStatusCode2.EarlyHints=103]="EarlyHints",HTTPStatusCode2[HTTPStatusCode2.Ok=200]="Ok",HTTPStatusCode2[HTTPStatusCode2.Created=201]="Created",HTTPStatusCode2[HTTPStatusCode2.Accepted=202]="Accepted",HTTPStatusCode2[HTTPStatusCode2.NonAuthoritativeInformation=203]="NonAuthoritativeInformation",HTTPStatusCode2[HTTPStatusCode2.NoContent=204]="NoContent",HTTPStatusCode2[HTTPStatusCode2.ResetContent=205]="ResetContent",HTTPStatusCode2[HTTPStatusCode2.PartialContent=206]="PartialContent",HTTPStatusCode2[HTTPStatusCode2.MultiStatus=207]="MultiStatus",HTTPStatusCode2[HTTPStatusCode2.AlreadyReported=208]="AlreadyReported",HTTPStatusCode2[HTTPStatusCode2.ImUsed=226]="ImUsed",HTTPStatusCode2[HTTPStatusCode2.MultipleChoices=300]="MultipleChoices",HTTPStatusCode2[HTTPStatusCode2.MovedPermanently=301]="MovedPermanently",HTTPStatusCode2[HTTPStatusCode2.Found=302]="Found",HTTPStatusCode2[HTTPStatusCode2.SeeOther=303]="SeeOther",HTTPStatusCode2[HTTPStatusCode2.NotModified=304]="NotModified",HTTPStatusCode2[HTTPStatusCode2.UseProxy=305]="UseProxy",HTTPStatusCode2[HTTPStatusCode2.Unused=306]="Unused",HTTPStatusCode2[HTTPStatusCode2.TemporaryRedirect=307]="TemporaryRedirect",HTTPStatusCode2[HTTPStatusCode2.PermanentRedirect=308]="PermanentRedirect",HTTPStatusCode2[HTTPStatusCode2.BadRequest=400]="BadRequest",HTTPStatusCode2[HTTPStatusCode2.Unauthorized=401]="Unauthorized",HTTPStatusCode2[HTTPStatusCode2.PaymentRequired=402]="PaymentRequired",HTTPStatusCode2[HTTPStatusCode2.Forbidden=403]="Forbidden",HTTPStatusCode2[HTTPStatusCode2.NotFound=404]="NotFound",HTTPStatusCode2[HTTPStatusCode2.MethodNotAllowed=405]="MethodNotAllowed",HTTPStatusCode2[HTTPStatusCode2.NotAcceptable=406]="NotAcceptable",HTTPStatusCode2[HTTPStatusCode2.ProxyAuthenticationRequired=407]="ProxyAuthenticationRequired",HTTPStatusCode2[HTTPStatusCode2.RequestTimeout=408]="RequestTimeout",HTTPStatusCode2[HTTPStatusCode2.Conflict=409]="Conflict",HTTPStatusCode2[HTTPStatusCode2.Gone=410]="Gone",HTTPStatusCode2[HTTPStatusCode2.LengthRequired=411]="LengthRequired",HTTPStatusCode2[HTTPStatusCode2.PreconditionFailed=412]="PreconditionFailed",HTTPStatusCode2[HTTPStatusCode2.PayloadTooLarge=413]="PayloadTooLarge",HTTPStatusCode2[HTTPStatusCode2.UriTooLong=414]="UriTooLong",HTTPStatusCode2[HTTPStatusCode2.UnsupportedMediaType=415]="UnsupportedMediaType",HTTPStatusCode2[HTTPStatusCode2.RangeNotSatisfiable=416]="RangeNotSatisfiable",HTTPStatusCode2[HTTPStatusCode2.ExpectationFailed=417]="ExpectationFailed",HTTPStatusCode2[HTTPStatusCode2.ImATeapot=418]="ImATeapot",HTTPStatusCode2[HTTPStatusCode2.MisdirectedRequest=421]="MisdirectedRequest",HTTPStatusCode2[HTTPStatusCode2.UnprocessableEntity=422]="UnprocessableEntity",HTTPStatusCode2[HTTPStatusCode2.Locked=423]="Locked",HTTPStatusCode2[HTTPStatusCode2.FailedDependency=424]="FailedDependency",HTTPStatusCode2[HTTPStatusCode2.TooEarly=425]="TooEarly",HTTPStatusCode2[HTTPStatusCode2.UpgradeRequired=426]="UpgradeRequired",HTTPStatusCode2[HTTPStatusCode2.PreconditionRequired=428]="PreconditionRequired",HTTPStatusCode2[HTTPStatusCode2.TooManyRequests=429]="TooManyRequests",HTTPStatusCode2[HTTPStatusCode2.RequestHeaderFieldsTooLarge=431]="RequestHeaderFieldsTooLarge",HTTPStatusCode2[HTTPStatusCode2.UnavailableForLegalReasons=451]="UnavailableForLegalReasons",HTTPStatusCode2[HTTPStatusCode2.InternalServerError=500]="InternalServerError",HTTPStatusCode2[HTTPStatusCode2.NotImplemented=501]="NotImplemented",HTTPStatusCode2[HTTPStatusCode2.BadGateway=502]="BadGateway",HTTPStatusCode2[HTTPStatusCode2.ServiceUnavailable=503]="ServiceUnavailable",HTTPStatusCode2[HTTPStatusCode2.GatewayTimeout=504]="GatewayTimeout",HTTPStatusCode2[HTTPStatusCode2.HttpVersionNotSupported=505]="HttpVersionNotSupported",HTTPStatusCode2[HTTPStatusCode2.VariantAlsoNegotiates=506]="VariantAlsoNegotiates",HTTPStatusCode2[HTTPStatusCode2.InsufficientStorage=507]="InsufficientStorage",HTTPStatusCode2[HTTPStatusCode2.LoopDetected=508]="LoopDetected",HTTPStatusCode2[HTTPStatusCode2.NotExtended=510]="NotExtended",HTTPStatusCode2[HTTPStatusCode2.NetworkAuthenticationRequired=511]="NetworkAuthenticationRequired",HTTPStatusCode2))(HTTPStatusCode||{});const _FetchHTTPImplementation=class _FetchHTTPImplementation{send(request){return new rxjs.Observable(subscriber=>{const abortController=new AbortController;return this._send(request,subscriber,abortController).then(()=>{},error=>{subscriber.error(new HTTPResponseError({error}))}),()=>abortController.abort()})}async _send(request,subscriber,abortController){var _a2,_b;let response;try{const fetchParams=this._parseFetchParamsFromRequest(request);response=await fetch(request.getUrlWithParams(),{signal:abortController.signal,...fetchParams})}catch(error){subscriber.error(new HTTPResponseError({error,status:(_a2=error.status)!=null?_a2:0,statusText:(_b=error.statusText)!=null?_b:"Unknown Error",headers:error.headers}));return}const responseHeaders=new HTTPHeaders(response.headers),status=response.status,statusText=response.statusText;let body=null;response.body&&(body=await this._readBody(request,response,subscriber)),status>=HTTPStatusCode.Ok&&status<HTTPStatusCode.MultipleChoices?subscriber.next(new HTTPResponse({body,headers:responseHeaders,status,statusText})):subscriber.error(new HTTPResponseError({error:body,status,statusText,headers:responseHeaders})),subscriber.complete()}async _readBody(request,response,subscriber){var _a2,_b;const chunks=[],reader=response.body.getReader(),contentLength=response.headers.get("content-length");let receivedLength=0;const reportProgress=(_a2=request.requestParams)==null?void 0:_a2.reportProgress,responseType=request.responseType;let partialText,decoder;for(;;){const{done,value}=await reader.read();if(done)break;chunks.push(value),receivedLength+=value.length,reportProgress&&responseType==="text"&&(partialText=(partialText!=null?partialText:"")+(decoder!=null?decoder:decoder=new TextDecoder).decode(value,{stream:!0}),subscriber.next(new HTTPProgress(contentLength?Number.parseInt(contentLength,10):void 0,receivedLength,partialText)))}const all=mergeChunks(chunks,receivedLength);try{const contentType=(_b=response.headers.get("content-type"))!=null?_b:"";return deserialize(request,all,contentType)}catch(error){return subscriber.error(new HTTPResponseError({error,status:response.status,statusText:response.statusText,headers:new HTTPHeaders(response.headers)})),null}}_parseFetchParamsFromRequest(request){return{method:request.method,headers:request.getHeadersInit(),body:request.getBody(),credentials:request.withCredentials?"include":void 0}}};__name(_FetchHTTPImplementation,"FetchHTTPImplementation");let FetchHTTPImplementation=_FetchHTTPImplementation;function mergeChunks(chunks,totalLength){const all=new Uint8Array(totalLength);let position=0;for(const chunk of chunks)all.set(chunk,position),position+=chunk.length;return all}__name(mergeChunks,"mergeChunks");const XSSI_PREFIX=/^\)\]\}',?\n/;function deserialize(request,bin,contentType){switch(request.responseType){case"json":const text=new TextDecoder().decode(bin).replace(XSSI_PREFIX,"");return text===""?null:JSON.parse(text);case"text":return new TextDecoder().decode(bin);case"blob":return new Blob([bin],{type:contentType});case"arraybuffer":return bin.buffer;default:throw new Error(`[FetchHTTPImplementation]: unknown response type: ${request.responseType}.`)}}__name(deserialize,"deserialize");const _XHRHTTPImplementation=class _XHRHTTPImplementation{send(request){return new rxjs.Observable(observer=>{const xhr=new XMLHttpRequest;xhr.open(request.method,request.getUrlWithParams()),request.withCredentials&&(xhr.withCredentials=!0),request.headers.forEach((key,value)=>xhr.setRequestHeader(key,value.join(","))),request.headers.has("Accept")||xhr.setRequestHeader("Accept","application/json, text/plain, */*"),request.headers.has("Content-Type")||xhr.setRequestHeader("Content-Type","application/json;charset=UTF-8");const buildResponseHeader=__name(()=>{const statusText=xhr.statusText||"OK",headers=new HTTPHeaders(xhr.getAllResponseHeaders());return new ResponseHeader(headers,xhr.status,statusText)},"buildResponseHeader"),onLoadHandler=__name(()=>{const{headers,statusText,status}=buildResponseHeader(),{responseType}=request;let body2=null,error=null;status!==HTTPStatusCode.NoContent&&(body2=typeof xhr.response>"u"?xhr.responseText:xhr.response);let success=status>=SuccessStatusCodeLowerBound&&status<ErrorStatusCodeLowerBound;if(responseType==="json"&&typeof body2=="string"){const originalBody=body2;try{body2=body2?JSON.parse(body2):null}catch(e){success=!1,body2=originalBody,error=e}}success?observer.next(new HTTPResponse({body:body2,headers,status,statusText})):observer.error(new HTTPResponseError({error,headers,status,statusText}))},"onLoadHandler"),onErrorHandler=__name(error=>{const res=new HTTPResponseError({error,status:xhr.status||0,statusText:xhr.statusText||"Unknown Error",headers:buildResponseHeader().headers});observer.error(res)},"onErrorHandler");xhr.addEventListener("load",onLoadHandler),xhr.addEventListener("error",onErrorHandler),xhr.addEventListener("abort",onErrorHandler),xhr.addEventListener("timeout",onErrorHandler);const body=request.getBody();return xhr.send(body),()=>{xhr.readyState!==xhr.DONE&&xhr.abort(),xhr.removeEventListener("load",onLoadHandler),xhr.removeEventListener("error",onErrorHandler),xhr.removeEventListener("abort",onErrorHandler),xhr.removeEventListener("timeout",onErrorHandler)}})}};__name(_XHRHTTPImplementation,"XHRHTTPImplementation");let XHRHTTPImplementation=_XHRHTTPImplementation;const ISocketService=core.createIdentifier("univer.socket"),_WebSocketService=class _WebSocketService extends core.Disposable{createSocket(URL){try{const connection=new WebSocket(URL),disposables=new core.DisposableCollection;return{URL,close:__name((code,reason)=>{connection.close(code,reason),disposables.dispose()},"close"),send:__name(data=>{connection.send(data)},"send"),open$:new rxjs.Observable(subscriber=>{const callback=__name(event=>subscriber.next(event),"callback");connection.addEventListener("open",callback),disposables.add(core.toDisposable(()=>connection.removeEventListener("open",callback)))}).pipe(operators.share()),close$:new rxjs.Observable(subscriber=>{const callback=__name(event=>subscriber.next(event),"callback");connection.addEventListener("close",callback),disposables.add(core.toDisposable(()=>connection.removeEventListener("close",callback)))}).pipe(operators.share()),error$:new rxjs.Observable(subscriber=>{const callback=__name(event=>subscriber.next(event),"callback");connection.addEventListener("error",callback),disposables.add(core.toDisposable(()=>connection.removeEventListener("error",callback)))}).pipe(operators.share()),message$:new rxjs.Observable(subscriber=>{const callback=__name(event=>subscriber.next(event),"callback");connection.addEventListener("message",callback),disposables.add(core.toDisposable(()=>connection.removeEventListener("message",callback)))}).pipe(operators.share())}}catch(e){return console.error(e),null}}};__name(_WebSocketService,"WebSocketService");let WebSocketService=_WebSocketService;const DEFAULT_MAX_RETRY_ATTEMPTS=3,DELAY_INTERVAL=1e3,RetryInterceptorFactory=__name((_accessor,params)=>{var _a2,_b;const maxRetryAttempts=(_a2=params==null?void 0:params.maxRetryAttempts)!=null?_a2:DEFAULT_MAX_RETRY_ATTEMPTS,delayInterval=(_b=params==null?void 0:params.delayInterval)!=null?_b:DELAY_INTERVAL;return(request,next)=>next(request).pipe(operators.retry({delay:delayInterval,count:maxRetryAttempts}))},"RetryInterceptorFactory"),ThresholdInterceptorFactory=__name(params=>{const handlers=[],ongoingHandlers=new Set,tick=__name(()=>{var _a2;for(;ongoingHandlers.size<((_a2=params==null?void 0:params.maxParallel)!=null?_a2:1)&&handlers.length>0;){const handler=handlers.shift();ongoingHandlers.add(handler),handler()}},"tick");return(request,next)=>new rxjs.Observable(observer=>{const handler=__name(()=>next(request).subscribe({next:__name(event=>observer.next(event),"next"),error:__name(err=>observer.next(err),"error"),complete:__name(()=>observer.complete(),"complete")}),"handler"),teardown=__name(()=>{ongoingHandlers.delete(handler),core.remove(handlers,handler),tick()},"teardown");return handlers.push(handler),tick(),teardown})},"ThresholdInterceptorFactory"),AuthInterceptorFactory=__name(params=>{const{errorStatusCodes,onAuthError}=params;return __name((request,next)=>next(request).pipe(rxjs.catchError(error=>(error instanceof HTTPResponseError&&errorStatusCodes.some(c=>c===error.status)&&onAuthError(),rxjs.throwError(()=>error)))),"authInterceptor")},"AuthInterceptorFactory"),createDefaultFetchCheck=__name((time=300)=>{let cancel=__name(()=>{},"noop");return _currentConfig=>new Promise(res=>{cancel();const t=setTimeout(()=>{res(!0)},time);cancel=__name(()=>{clearTimeout(t),res(!1)},"cancel")})},"createDefaultFetchCheck"),createDistributeResult=__name(()=>(result,list)=>list.map(config=>({config,result})),"createDistributeResult"),MergeInterceptorFactory=__name((config,options={})=>{const{isMatch,getParamsFromRequest,mergeParamsToRequest}=config,{fetchCheck=createDefaultFetchCheck(300),distributeResult=createDistributeResult()}=options,hookList=[],getPlainList=__name(_list=>_list.map(item=>item.config),"getPlainList");return(requestConfig,next)=>isMatch(requestConfig)?new rxjs.Observable(observer=>{const params=getParamsFromRequest(requestConfig);hookList.push({next:__name(v=>observer.next(v),"next"),error:__name(error=>observer.error(error),"error"),config:params});const list=getPlainList(hookList);fetchCheck(requestConfig).then(isFetch=>{if(isFetch){const currentHookList=[];list.forEach(config2=>{const index=hookList.findIndex(item=>item.config===config2);if(index>=0){const[hook]=hookList.splice(index,1);currentHookList.push(hook)}}),next(mergeParamsToRequest(list,requestConfig)).subscribe({next:__name(e=>{if(e.type===HTTPEventType.Response){const body=e.body,configList=distributeResult(body,list);currentHookList.forEach(hookItem=>{const res=configList.find(item=>item.config===hookItem.config);if(res){const response=new HTTPResponse({body:res.result,headers:e.headers,status:e.status,statusText:e.statusText});hookItem.next(response)}else hookItem.error("batch error")})}},"next"),complete:__name(()=>observer.complete(),"complete"),error:__name(e=>observer.error(e),"error")})}})}):next(requestConfig)},"MergeInterceptorFactory");exports.AuthInterceptorFactory=AuthInterceptorFactory;exports.FetchHTTPImplementation=FetchHTTPImplementation;exports.HTTPEventType=HTTPEventType;exports.HTTPHeaders=HTTPHeaders;exports.HTTPProgress=HTTPProgress;exports.HTTPRequest=HTTPRequest;exports.HTTPResponse=HTTPResponse;exports.HTTPResponseError=HTTPResponseError;exports.HTTPStatusCode=HTTPStatusCode;exports.IHTTPImplementation=IHTTPImplementation;exports.ISocketService=ISocketService;exports.MergeInterceptorFactory=MergeInterceptorFactory;exports.ResponseHeader=ResponseHeader;exports.RetryInterceptorFactory=RetryInterceptorFactory;exports.ThresholdInterceptorFactory=ThresholdInterceptorFactory;exports.WebSocketService=WebSocketService;exports.XHRHTTPImplementation=XHRHTTPImplementation;
|
package/lib/es/index.js
CHANGED
|
@@ -1,65 +1,66 @@
|
|
|
1
|
-
var
|
|
2
|
-
var
|
|
3
|
-
var
|
|
4
|
-
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
const
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
return this._headers.has(n) ? this._headers.get(n) : null;
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value;
|
|
3
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: !0 });
|
|
4
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key != "symbol" ? key + "" : key, value);
|
|
5
|
+
import { createIdentifier, Disposable, toDisposable, remove, DisposableCollection } from "@univerjs/core";
|
|
6
|
+
import { of, firstValueFrom, Observable, catchError, throwError } from "rxjs";
|
|
7
|
+
import { concatMap, share, retry } from "rxjs/operators";
|
|
8
|
+
const ApplicationJSONType = "application/json", _HTTPHeaders = class _HTTPHeaders {
|
|
9
|
+
constructor(headers) {
|
|
10
|
+
__publicField(this, "_headers", /* @__PURE__ */ new Map());
|
|
11
|
+
typeof headers == "string" ? this._handleHeadersString(headers) : headers instanceof Headers ? this._handleHeaders(headers) : headers && this._handleHeadersConstructorProps(headers);
|
|
12
|
+
}
|
|
13
|
+
forEach(callback) {
|
|
14
|
+
this._headers.forEach((v, key) => callback(key, v));
|
|
15
|
+
}
|
|
16
|
+
has(key) {
|
|
17
|
+
return !!this._headers.has(key.toLowerCase());
|
|
18
|
+
}
|
|
19
|
+
get(key) {
|
|
20
|
+
const k = key.toLowerCase();
|
|
21
|
+
return this._headers.has(k) ? this._headers.get(k) : null;
|
|
23
22
|
}
|
|
24
23
|
toHeadersInit() {
|
|
25
|
-
var
|
|
26
|
-
const
|
|
27
|
-
return this._headers.forEach((
|
|
28
|
-
|
|
29
|
-
}), (
|
|
30
|
-
}
|
|
31
|
-
_setHeader(
|
|
32
|
-
const
|
|
33
|
-
this._headers.has(
|
|
34
|
-
}
|
|
35
|
-
_handleHeadersString(
|
|
36
|
-
|
|
37
|
-
`).forEach((
|
|
38
|
-
const [
|
|
39
|
-
|
|
24
|
+
var _a2, _b;
|
|
25
|
+
const headers = {};
|
|
26
|
+
return this._headers.forEach((values, key) => {
|
|
27
|
+
headers[key] = values.join(",");
|
|
28
|
+
}), (_a2 = headers.accept) != null || (headers.accept = "application/json, text/plain, */*"), (_b = headers["content-type"]) != null || (headers["content-type"] = "application/json;charset=UTF-8"), headers;
|
|
29
|
+
}
|
|
30
|
+
_setHeader(name, value) {
|
|
31
|
+
const lowerCase = name.toLowerCase();
|
|
32
|
+
this._headers.has(lowerCase) ? this._headers.get(lowerCase).push(value.toString()) : this._headers.set(lowerCase, [value.toString()]);
|
|
33
|
+
}
|
|
34
|
+
_handleHeadersString(headers) {
|
|
35
|
+
headers.split(`
|
|
36
|
+
`).forEach((header) => {
|
|
37
|
+
const [name, value] = header.split(":");
|
|
38
|
+
name && value && this._setHeader(name, value);
|
|
40
39
|
});
|
|
41
40
|
}
|
|
42
|
-
_handleHeadersConstructorProps(
|
|
43
|
-
Object.entries(
|
|
41
|
+
_handleHeadersConstructorProps(headers) {
|
|
42
|
+
Object.entries(headers).forEach(([name, value]) => this._setHeader(name, value));
|
|
44
43
|
}
|
|
45
|
-
_handleHeaders(
|
|
46
|
-
|
|
44
|
+
_handleHeaders(headers) {
|
|
45
|
+
headers.forEach((value, name) => this._setHeader(name, value));
|
|
47
46
|
}
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
47
|
+
};
|
|
48
|
+
__name(_HTTPHeaders, "HTTPHeaders");
|
|
49
|
+
let HTTPHeaders = _HTTPHeaders;
|
|
50
|
+
const IHTTPImplementation = createIdentifier("network.http-implementation"), _HTTPParams = class _HTTPParams {
|
|
51
|
+
constructor(params) {
|
|
52
|
+
this.params = params;
|
|
53
53
|
}
|
|
54
54
|
toString() {
|
|
55
|
-
return this.params ? Object.keys(this.params).map((
|
|
55
|
+
return this.params ? Object.keys(this.params).map((key) => `${key}=${this.params[key]}`).join("&") : "";
|
|
56
56
|
}
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
this
|
|
57
|
+
};
|
|
58
|
+
__name(_HTTPParams, "HTTPParams");
|
|
59
|
+
let HTTPParams = _HTTPParams, HTTPRequestUID = 0;
|
|
60
|
+
const _HTTPRequest = class _HTTPRequest {
|
|
61
|
+
constructor(method, url, requestParams) {
|
|
62
|
+
__publicField(this, "uid", HTTPRequestUID++);
|
|
63
|
+
this.method = method, this.url = url, this.requestParams = requestParams;
|
|
63
64
|
}
|
|
64
65
|
get headers() {
|
|
65
66
|
return this.requestParams.headers;
|
|
@@ -71,31 +72,33 @@ class D {
|
|
|
71
72
|
return this.requestParams.responseType;
|
|
72
73
|
}
|
|
73
74
|
getUrlWithParams() {
|
|
74
|
-
var
|
|
75
|
-
const
|
|
76
|
-
return
|
|
75
|
+
var _a2, _b;
|
|
76
|
+
const params = (_b = (_a2 = this.requestParams) == null ? void 0 : _a2.params) == null ? void 0 : _b.toString();
|
|
77
|
+
return params ? `${this.url}${this.url.includes("?") ? "&" : "?"}${params}` : this.url;
|
|
77
78
|
}
|
|
78
79
|
getBody() {
|
|
79
|
-
var
|
|
80
|
-
const
|
|
81
|
-
return
|
|
80
|
+
var _a2, _b;
|
|
81
|
+
const contentType = (_a2 = this.headers.get("Content-Type")) != null ? _a2 : ApplicationJSONType, body = (_b = this.requestParams) == null ? void 0 : _b.body;
|
|
82
|
+
return contentType === ApplicationJSONType && body && typeof body == "object" ? JSON.stringify(body) : body ? `${body}` : null;
|
|
82
83
|
}
|
|
83
84
|
getHeadersInit() {
|
|
84
85
|
return this.headers.toHeadersInit();
|
|
85
86
|
}
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
87
|
+
};
|
|
88
|
+
__name(_HTTPRequest, "HTTPRequest");
|
|
89
|
+
let HTTPRequest = _HTTPRequest;
|
|
90
|
+
var __defProp2 = Object.defineProperty, __getOwnPropDesc = Object.getOwnPropertyDescriptor, __decorateClass = /* @__PURE__ */ __name((decorators, target, key, kind) => {
|
|
91
|
+
for (var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target, i = decorators.length - 1, decorator; i >= 0; i--)
|
|
92
|
+
(decorator = decorators[i]) && (result = (kind ? decorator(target, key, result) : decorator(result)) || result);
|
|
93
|
+
return kind && result && __defProp2(target, key, result), result;
|
|
94
|
+
}, "__decorateClass"), __decorateParam = /* @__PURE__ */ __name((index, decorator) => (target, key) => decorator(target, key, index), "__decorateParam"), _a;
|
|
95
|
+
let HTTPService = (_a = class extends Disposable {
|
|
96
|
+
constructor(_http) {
|
|
94
97
|
super();
|
|
95
|
-
|
|
98
|
+
__publicField(this, "_interceptors", []);
|
|
96
99
|
// eslint-disable-next-line ts/no-explicit-any
|
|
97
|
-
|
|
98
|
-
this._http =
|
|
100
|
+
__publicField(this, "_pipe");
|
|
101
|
+
this._http = _http;
|
|
99
102
|
}
|
|
100
103
|
/**
|
|
101
104
|
* Register an HTTP interceptor.
|
|
@@ -103,410 +106,426 @@ let O = class extends j {
|
|
|
103
106
|
* @param interceptor the http interceptor
|
|
104
107
|
* @returns a disposable handler to remove the interceptor
|
|
105
108
|
*/
|
|
106
|
-
registerHTTPInterceptor(
|
|
107
|
-
if (this._interceptors.indexOf(
|
|
109
|
+
registerHTTPInterceptor(interceptor) {
|
|
110
|
+
if (this._interceptors.indexOf(interceptor) !== -1)
|
|
108
111
|
throw new Error("[HTTPService]: The interceptor has already been registered!");
|
|
109
|
-
return this._interceptors.push(
|
|
110
|
-
var
|
|
111
|
-
return ((
|
|
112
|
-
}), this._pipe = null,
|
|
112
|
+
return this._interceptors.push(interceptor), this._interceptors = this._interceptors.sort((a, b) => {
|
|
113
|
+
var _a2, _b;
|
|
114
|
+
return ((_a2 = a.priority) != null ? _a2 : 0) - ((_b = b.priority) != null ? _b : 0);
|
|
115
|
+
}), this._pipe = null, toDisposable(() => remove(this._interceptors, interceptor));
|
|
113
116
|
}
|
|
114
|
-
get(
|
|
115
|
-
return this._request("GET",
|
|
117
|
+
get(url, params) {
|
|
118
|
+
return this._request("GET", url, params);
|
|
116
119
|
}
|
|
117
|
-
post(
|
|
118
|
-
return this._request("POST",
|
|
120
|
+
post(url, params) {
|
|
121
|
+
return this._request("POST", url, params);
|
|
119
122
|
}
|
|
120
|
-
put(
|
|
121
|
-
return this._request("PUT",
|
|
123
|
+
put(url, params) {
|
|
124
|
+
return this._request("PUT", url, params);
|
|
122
125
|
}
|
|
123
|
-
delete(
|
|
124
|
-
return this._request("DELETE",
|
|
126
|
+
delete(url, params) {
|
|
127
|
+
return this._request("DELETE", url, params);
|
|
125
128
|
}
|
|
126
|
-
patch(
|
|
127
|
-
return this._request("PATCH",
|
|
129
|
+
patch(url, options) {
|
|
130
|
+
return this._request("PATCH", url, options);
|
|
128
131
|
}
|
|
129
|
-
getSSE(
|
|
130
|
-
var
|
|
131
|
-
const
|
|
132
|
-
headers
|
|
133
|
-
params
|
|
134
|
-
withCredentials: (
|
|
132
|
+
getSSE(method, url, options) {
|
|
133
|
+
var _a2, _b;
|
|
134
|
+
const headers = new HTTPHeaders(options == null ? void 0 : options.headers), params = new HTTPParams(options == null ? void 0 : options.params), request = new HTTPRequest(method, url, {
|
|
135
|
+
headers,
|
|
136
|
+
params,
|
|
137
|
+
withCredentials: (_a2 = options == null ? void 0 : options.withCredentials) != null ? _a2 : !1,
|
|
135
138
|
reportProgress: !0,
|
|
136
|
-
responseType: (
|
|
137
|
-
body: ["GET", "DELETE"].includes(
|
|
139
|
+
responseType: (_b = options == null ? void 0 : options.responseType) != null ? _b : "json",
|
|
140
|
+
body: ["GET", "DELETE"].includes(method) || options == null ? void 0 : options.body
|
|
138
141
|
});
|
|
139
|
-
return
|
|
142
|
+
return of(request).pipe(concatMap((request2) => this._runInterceptorsAndImplementation(request2)));
|
|
140
143
|
}
|
|
141
144
|
/** The HTTP request implementations */
|
|
142
|
-
async _request(
|
|
143
|
-
var
|
|
144
|
-
const
|
|
145
|
-
headers
|
|
146
|
-
params
|
|
147
|
-
withCredentials: (
|
|
145
|
+
async _request(method, url, options) {
|
|
146
|
+
var _a2, _b;
|
|
147
|
+
const headers = new HTTPHeaders(options == null ? void 0 : options.headers), params = new HTTPParams(options == null ? void 0 : options.params), request = new HTTPRequest(method, url, {
|
|
148
|
+
headers,
|
|
149
|
+
params,
|
|
150
|
+
withCredentials: (_a2 = options == null ? void 0 : options.withCredentials) != null ? _a2 : !1,
|
|
148
151
|
// default value for withCredentials is false by MDN
|
|
149
|
-
responseType: (
|
|
150
|
-
body: ["GET", "DELETE"].includes(
|
|
151
|
-
}),
|
|
152
|
-
|
|
152
|
+
responseType: (_b = options == null ? void 0 : options.responseType) != null ? _b : "json",
|
|
153
|
+
body: ["GET", "DELETE"].includes(method) || options == null ? void 0 : options.body
|
|
154
|
+
}), events$ = of(request).pipe(
|
|
155
|
+
concatMap((request2) => this._runInterceptorsAndImplementation(request2))
|
|
153
156
|
);
|
|
154
|
-
return await
|
|
157
|
+
return await firstValueFrom(events$);
|
|
155
158
|
}
|
|
156
159
|
// eslint-disable-next-line ts/no-explicit-any
|
|
157
|
-
_runInterceptorsAndImplementation(
|
|
158
|
-
return this._pipe || (this._pipe = this._interceptors.map((
|
|
159
|
-
(
|
|
160
|
-
(
|
|
160
|
+
_runInterceptorsAndImplementation(request) {
|
|
161
|
+
return this._pipe || (this._pipe = this._interceptors.map((handler) => handler.interceptor).reduceRight(
|
|
162
|
+
(nextHandlerFunction, interceptorFunction) => chainInterceptorFn(nextHandlerFunction, interceptorFunction),
|
|
163
|
+
(requestFromPrevInterceptor, finalHandler) => finalHandler(requestFromPrevInterceptor)
|
|
161
164
|
)), this._pipe(
|
|
162
|
-
|
|
163
|
-
(
|
|
165
|
+
request,
|
|
166
|
+
(requestToNext) => this._http.send(requestToNext)
|
|
164
167
|
/* final handler */
|
|
165
168
|
);
|
|
166
169
|
}
|
|
167
|
-
};
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
],
|
|
171
|
-
function
|
|
172
|
-
return (
|
|
170
|
+
}, __name(_a, "HTTPService"), _a);
|
|
171
|
+
HTTPService = __decorateClass([
|
|
172
|
+
__decorateParam(0, IHTTPImplementation)
|
|
173
|
+
], HTTPService);
|
|
174
|
+
function chainInterceptorFn(afterInterceptorChain, currentInterceptorFn) {
|
|
175
|
+
return (prevRequest, nextHandlerFn) => currentInterceptorFn(prevRequest, (nextRequest) => afterInterceptorChain(nextRequest, nextHandlerFn));
|
|
173
176
|
}
|
|
174
|
-
|
|
175
|
-
|
|
177
|
+
__name(chainInterceptorFn, "chainInterceptorFn");
|
|
178
|
+
var HTTPEventType = /* @__PURE__ */ ((HTTPEventType2) => (HTTPEventType2[HTTPEventType2.DownloadProgress = 0] = "DownloadProgress", HTTPEventType2[HTTPEventType2.Response = 1] = "Response", HTTPEventType2))(HTTPEventType || {});
|
|
179
|
+
const _HTTPResponse = class _HTTPResponse {
|
|
176
180
|
constructor({
|
|
177
|
-
body
|
|
178
|
-
headers
|
|
179
|
-
status
|
|
180
|
-
statusText
|
|
181
|
+
body,
|
|
182
|
+
headers,
|
|
183
|
+
status,
|
|
184
|
+
statusText
|
|
181
185
|
}) {
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
this.body =
|
|
186
|
+
__publicField(this, "type", 1);
|
|
187
|
+
__publicField(this, "body");
|
|
188
|
+
__publicField(this, "headers");
|
|
189
|
+
__publicField(this, "status");
|
|
190
|
+
__publicField(this, "statusText");
|
|
191
|
+
this.body = body, this.headers = headers, this.status = status, this.statusText = statusText;
|
|
188
192
|
}
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
193
|
+
};
|
|
194
|
+
__name(_HTTPResponse, "HTTPResponse");
|
|
195
|
+
let HTTPResponse = _HTTPResponse;
|
|
196
|
+
const _HTTPProgress = class _HTTPProgress {
|
|
197
|
+
constructor(total, loaded, partialText) {
|
|
198
|
+
__publicField(this, "type", 0);
|
|
199
|
+
this.total = total, this.loaded = loaded, this.partialText = partialText;
|
|
194
200
|
}
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
201
|
+
};
|
|
202
|
+
__name(_HTTPProgress, "HTTPProgress");
|
|
203
|
+
let HTTPProgress = _HTTPProgress;
|
|
204
|
+
const _ResponseHeader = class _ResponseHeader {
|
|
205
|
+
constructor(headers, status, statusText) {
|
|
206
|
+
this.headers = headers, this.status = status, this.statusText = statusText;
|
|
199
207
|
}
|
|
200
|
-
}
|
|
201
|
-
|
|
208
|
+
};
|
|
209
|
+
__name(_ResponseHeader, "ResponseHeader");
|
|
210
|
+
let ResponseHeader = _ResponseHeader;
|
|
211
|
+
const _HTTPResponseError = class _HTTPResponseError {
|
|
202
212
|
constructor({
|
|
203
|
-
headers
|
|
204
|
-
status
|
|
205
|
-
statusText
|
|
206
|
-
error
|
|
213
|
+
headers,
|
|
214
|
+
status,
|
|
215
|
+
statusText,
|
|
216
|
+
error
|
|
207
217
|
}) {
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
this.headers =
|
|
218
|
+
__publicField(this, "headers");
|
|
219
|
+
__publicField(this, "status");
|
|
220
|
+
__publicField(this, "statusText");
|
|
221
|
+
__publicField(this, "error");
|
|
222
|
+
this.headers = headers, this.status = status, this.statusText = statusText, this.error = error;
|
|
213
223
|
}
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
224
|
+
};
|
|
225
|
+
__name(_HTTPResponseError, "HTTPResponseError");
|
|
226
|
+
let HTTPResponseError = _HTTPResponseError;
|
|
227
|
+
const SuccessStatusCodeLowerBound = 200, ErrorStatusCodeLowerBound = 300;
|
|
228
|
+
var HTTPStatusCode = /* @__PURE__ */ ((HTTPStatusCode2) => (HTTPStatusCode2[HTTPStatusCode2.Continue = 100] = "Continue", HTTPStatusCode2[HTTPStatusCode2.SwitchingProtocols = 101] = "SwitchingProtocols", HTTPStatusCode2[HTTPStatusCode2.Processing = 102] = "Processing", HTTPStatusCode2[HTTPStatusCode2.EarlyHints = 103] = "EarlyHints", HTTPStatusCode2[HTTPStatusCode2.Ok = 200] = "Ok", HTTPStatusCode2[HTTPStatusCode2.Created = 201] = "Created", HTTPStatusCode2[HTTPStatusCode2.Accepted = 202] = "Accepted", HTTPStatusCode2[HTTPStatusCode2.NonAuthoritativeInformation = 203] = "NonAuthoritativeInformation", HTTPStatusCode2[HTTPStatusCode2.NoContent = 204] = "NoContent", HTTPStatusCode2[HTTPStatusCode2.ResetContent = 205] = "ResetContent", HTTPStatusCode2[HTTPStatusCode2.PartialContent = 206] = "PartialContent", HTTPStatusCode2[HTTPStatusCode2.MultiStatus = 207] = "MultiStatus", HTTPStatusCode2[HTTPStatusCode2.AlreadyReported = 208] = "AlreadyReported", HTTPStatusCode2[HTTPStatusCode2.ImUsed = 226] = "ImUsed", HTTPStatusCode2[HTTPStatusCode2.MultipleChoices = 300] = "MultipleChoices", HTTPStatusCode2[HTTPStatusCode2.MovedPermanently = 301] = "MovedPermanently", HTTPStatusCode2[HTTPStatusCode2.Found = 302] = "Found", HTTPStatusCode2[HTTPStatusCode2.SeeOther = 303] = "SeeOther", HTTPStatusCode2[HTTPStatusCode2.NotModified = 304] = "NotModified", HTTPStatusCode2[HTTPStatusCode2.UseProxy = 305] = "UseProxy", HTTPStatusCode2[HTTPStatusCode2.Unused = 306] = "Unused", HTTPStatusCode2[HTTPStatusCode2.TemporaryRedirect = 307] = "TemporaryRedirect", HTTPStatusCode2[HTTPStatusCode2.PermanentRedirect = 308] = "PermanentRedirect", HTTPStatusCode2[HTTPStatusCode2.BadRequest = 400] = "BadRequest", HTTPStatusCode2[HTTPStatusCode2.Unauthorized = 401] = "Unauthorized", HTTPStatusCode2[HTTPStatusCode2.PaymentRequired = 402] = "PaymentRequired", HTTPStatusCode2[HTTPStatusCode2.Forbidden = 403] = "Forbidden", HTTPStatusCode2[HTTPStatusCode2.NotFound = 404] = "NotFound", HTTPStatusCode2[HTTPStatusCode2.MethodNotAllowed = 405] = "MethodNotAllowed", HTTPStatusCode2[HTTPStatusCode2.NotAcceptable = 406] = "NotAcceptable", HTTPStatusCode2[HTTPStatusCode2.ProxyAuthenticationRequired = 407] = "ProxyAuthenticationRequired", HTTPStatusCode2[HTTPStatusCode2.RequestTimeout = 408] = "RequestTimeout", HTTPStatusCode2[HTTPStatusCode2.Conflict = 409] = "Conflict", HTTPStatusCode2[HTTPStatusCode2.Gone = 410] = "Gone", HTTPStatusCode2[HTTPStatusCode2.LengthRequired = 411] = "LengthRequired", HTTPStatusCode2[HTTPStatusCode2.PreconditionFailed = 412] = "PreconditionFailed", HTTPStatusCode2[HTTPStatusCode2.PayloadTooLarge = 413] = "PayloadTooLarge", HTTPStatusCode2[HTTPStatusCode2.UriTooLong = 414] = "UriTooLong", HTTPStatusCode2[HTTPStatusCode2.UnsupportedMediaType = 415] = "UnsupportedMediaType", HTTPStatusCode2[HTTPStatusCode2.RangeNotSatisfiable = 416] = "RangeNotSatisfiable", HTTPStatusCode2[HTTPStatusCode2.ExpectationFailed = 417] = "ExpectationFailed", HTTPStatusCode2[HTTPStatusCode2.ImATeapot = 418] = "ImATeapot", HTTPStatusCode2[HTTPStatusCode2.MisdirectedRequest = 421] = "MisdirectedRequest", HTTPStatusCode2[HTTPStatusCode2.UnprocessableEntity = 422] = "UnprocessableEntity", HTTPStatusCode2[HTTPStatusCode2.Locked = 423] = "Locked", HTTPStatusCode2[HTTPStatusCode2.FailedDependency = 424] = "FailedDependency", HTTPStatusCode2[HTTPStatusCode2.TooEarly = 425] = "TooEarly", HTTPStatusCode2[HTTPStatusCode2.UpgradeRequired = 426] = "UpgradeRequired", HTTPStatusCode2[HTTPStatusCode2.PreconditionRequired = 428] = "PreconditionRequired", HTTPStatusCode2[HTTPStatusCode2.TooManyRequests = 429] = "TooManyRequests", HTTPStatusCode2[HTTPStatusCode2.RequestHeaderFieldsTooLarge = 431] = "RequestHeaderFieldsTooLarge", HTTPStatusCode2[HTTPStatusCode2.UnavailableForLegalReasons = 451] = "UnavailableForLegalReasons", HTTPStatusCode2[HTTPStatusCode2.InternalServerError = 500] = "InternalServerError", HTTPStatusCode2[HTTPStatusCode2.NotImplemented = 501] = "NotImplemented", HTTPStatusCode2[HTTPStatusCode2.BadGateway = 502] = "BadGateway", HTTPStatusCode2[HTTPStatusCode2.ServiceUnavailable = 503] = "ServiceUnavailable", HTTPStatusCode2[HTTPStatusCode2.GatewayTimeout = 504] = "GatewayTimeout", HTTPStatusCode2[HTTPStatusCode2.HttpVersionNotSupported = 505] = "HttpVersionNotSupported", HTTPStatusCode2[HTTPStatusCode2.VariantAlsoNegotiates = 506] = "VariantAlsoNegotiates", HTTPStatusCode2[HTTPStatusCode2.InsufficientStorage = 507] = "InsufficientStorage", HTTPStatusCode2[HTTPStatusCode2.LoopDetected = 508] = "LoopDetected", HTTPStatusCode2[HTTPStatusCode2.NotExtended = 510] = "NotExtended", HTTPStatusCode2[HTTPStatusCode2.NetworkAuthenticationRequired = 511] = "NetworkAuthenticationRequired", HTTPStatusCode2))(HTTPStatusCode || {});
|
|
229
|
+
const _FetchHTTPImplementation = class _FetchHTTPImplementation {
|
|
230
|
+
send(request) {
|
|
231
|
+
return new Observable((subscriber) => {
|
|
232
|
+
const abortController = new AbortController();
|
|
233
|
+
return this._send(request, subscriber, abortController).then(() => {
|
|
234
|
+
}, (error) => {
|
|
235
|
+
subscriber.error(new HTTPResponseError({
|
|
236
|
+
error
|
|
225
237
|
}));
|
|
226
|
-
}), () =>
|
|
238
|
+
}), () => abortController.abort();
|
|
227
239
|
});
|
|
228
240
|
}
|
|
229
|
-
async _send(
|
|
230
|
-
var
|
|
231
|
-
let
|
|
241
|
+
async _send(request, subscriber, abortController) {
|
|
242
|
+
var _a2, _b;
|
|
243
|
+
let response;
|
|
232
244
|
try {
|
|
233
|
-
const
|
|
234
|
-
|
|
235
|
-
signal:
|
|
236
|
-
...
|
|
245
|
+
const fetchParams = this._parseFetchParamsFromRequest(request);
|
|
246
|
+
response = await fetch(request.getUrlWithParams(), {
|
|
247
|
+
signal: abortController.signal,
|
|
248
|
+
...fetchParams
|
|
237
249
|
});
|
|
238
|
-
} catch (
|
|
239
|
-
|
|
240
|
-
error
|
|
241
|
-
status: (
|
|
242
|
-
statusText: (
|
|
243
|
-
headers:
|
|
250
|
+
} catch (error) {
|
|
251
|
+
subscriber.error(new HTTPResponseError({
|
|
252
|
+
error,
|
|
253
|
+
status: (_a2 = error.status) != null ? _a2 : 0,
|
|
254
|
+
statusText: (_b = error.statusText) != null ? _b : "Unknown Error",
|
|
255
|
+
headers: error.headers
|
|
244
256
|
}));
|
|
245
257
|
return;
|
|
246
258
|
}
|
|
247
|
-
const
|
|
248
|
-
let
|
|
249
|
-
|
|
250
|
-
body
|
|
251
|
-
headers:
|
|
252
|
-
status
|
|
253
|
-
statusText
|
|
254
|
-
})) :
|
|
255
|
-
error:
|
|
256
|
-
status
|
|
257
|
-
statusText
|
|
258
|
-
headers:
|
|
259
|
-
})),
|
|
260
|
-
}
|
|
261
|
-
async _readBody(
|
|
262
|
-
var
|
|
263
|
-
const
|
|
264
|
-
let
|
|
265
|
-
const
|
|
266
|
-
let
|
|
259
|
+
const responseHeaders = new HTTPHeaders(response.headers), status = response.status, statusText = response.statusText;
|
|
260
|
+
let body = null;
|
|
261
|
+
response.body && (body = await this._readBody(request, response, subscriber)), status >= HTTPStatusCode.Ok && status < HTTPStatusCode.MultipleChoices ? subscriber.next(new HTTPResponse({
|
|
262
|
+
body,
|
|
263
|
+
headers: responseHeaders,
|
|
264
|
+
status,
|
|
265
|
+
statusText
|
|
266
|
+
})) : subscriber.error(new HTTPResponseError({
|
|
267
|
+
error: body,
|
|
268
|
+
status,
|
|
269
|
+
statusText,
|
|
270
|
+
headers: responseHeaders
|
|
271
|
+
})), subscriber.complete();
|
|
272
|
+
}
|
|
273
|
+
async _readBody(request, response, subscriber) {
|
|
274
|
+
var _a2, _b;
|
|
275
|
+
const chunks = [], reader = response.body.getReader(), contentLength = response.headers.get("content-length");
|
|
276
|
+
let receivedLength = 0;
|
|
277
|
+
const reportProgress = (_a2 = request.requestParams) == null ? void 0 : _a2.reportProgress, responseType = request.responseType;
|
|
278
|
+
let partialText, decoder;
|
|
267
279
|
for (; ; ) {
|
|
268
|
-
const { done
|
|
269
|
-
if (
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
280
|
+
const { done, value } = await reader.read();
|
|
281
|
+
if (done) break;
|
|
282
|
+
chunks.push(value), receivedLength += value.length, reportProgress && responseType === "text" && (partialText = (partialText != null ? partialText : "") + (decoder != null ? decoder : decoder = new TextDecoder()).decode(value, { stream: !0 }), subscriber.next(new HTTPProgress(
|
|
283
|
+
contentLength ? Number.parseInt(contentLength, 10) : void 0,
|
|
284
|
+
receivedLength,
|
|
285
|
+
partialText
|
|
274
286
|
)));
|
|
275
287
|
}
|
|
276
|
-
const
|
|
288
|
+
const all = mergeChunks(chunks, receivedLength);
|
|
277
289
|
try {
|
|
278
|
-
const
|
|
279
|
-
return
|
|
280
|
-
} catch (
|
|
281
|
-
return
|
|
282
|
-
error
|
|
283
|
-
status:
|
|
284
|
-
statusText:
|
|
285
|
-
headers: new
|
|
290
|
+
const contentType = (_b = response.headers.get("content-type")) != null ? _b : "";
|
|
291
|
+
return deserialize(request, all, contentType);
|
|
292
|
+
} catch (error) {
|
|
293
|
+
return subscriber.error(new HTTPResponseError({
|
|
294
|
+
error,
|
|
295
|
+
status: response.status,
|
|
296
|
+
statusText: response.statusText,
|
|
297
|
+
headers: new HTTPHeaders(response.headers)
|
|
286
298
|
})), null;
|
|
287
299
|
}
|
|
288
300
|
}
|
|
289
|
-
_parseFetchParamsFromRequest(
|
|
301
|
+
_parseFetchParamsFromRequest(request) {
|
|
290
302
|
return {
|
|
291
|
-
method:
|
|
292
|
-
headers:
|
|
293
|
-
body:
|
|
294
|
-
credentials:
|
|
303
|
+
method: request.method,
|
|
304
|
+
headers: request.getHeadersInit(),
|
|
305
|
+
body: request.getBody(),
|
|
306
|
+
credentials: request.withCredentials ? "include" : void 0
|
|
295
307
|
};
|
|
296
308
|
}
|
|
309
|
+
};
|
|
310
|
+
__name(_FetchHTTPImplementation, "FetchHTTPImplementation");
|
|
311
|
+
let FetchHTTPImplementation = _FetchHTTPImplementation;
|
|
312
|
+
function mergeChunks(chunks, totalLength) {
|
|
313
|
+
const all = new Uint8Array(totalLength);
|
|
314
|
+
let position = 0;
|
|
315
|
+
for (const chunk of chunks)
|
|
316
|
+
all.set(chunk, position), position += chunk.length;
|
|
317
|
+
return all;
|
|
297
318
|
}
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
n.set(s, t), t += s.length;
|
|
303
|
-
return n;
|
|
304
|
-
}
|
|
305
|
-
const oe = /^\)\]\}',?\n/;
|
|
306
|
-
function ie(e, r, n) {
|
|
307
|
-
switch (e.responseType) {
|
|
319
|
+
__name(mergeChunks, "mergeChunks");
|
|
320
|
+
const XSSI_PREFIX = /^\)\]\}',?\n/;
|
|
321
|
+
function deserialize(request, bin, contentType) {
|
|
322
|
+
switch (request.responseType) {
|
|
308
323
|
case "json":
|
|
309
|
-
const
|
|
310
|
-
return
|
|
324
|
+
const text = new TextDecoder().decode(bin).replace(XSSI_PREFIX, "");
|
|
325
|
+
return text === "" ? null : JSON.parse(text);
|
|
311
326
|
case "text":
|
|
312
|
-
return new TextDecoder().decode(
|
|
327
|
+
return new TextDecoder().decode(bin);
|
|
313
328
|
case "blob":
|
|
314
|
-
return new Blob([
|
|
329
|
+
return new Blob([bin], { type: contentType });
|
|
315
330
|
case "arraybuffer":
|
|
316
|
-
return
|
|
331
|
+
return bin.buffer;
|
|
317
332
|
default:
|
|
318
|
-
throw new Error(`[FetchHTTPImplementation]: unknown response type: ${
|
|
333
|
+
throw new Error(`[FetchHTTPImplementation]: unknown response type: ${request.responseType}.`);
|
|
319
334
|
}
|
|
320
335
|
}
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
+
__name(deserialize, "deserialize");
|
|
337
|
+
const _XHRHTTPImplementation = class _XHRHTTPImplementation {
|
|
338
|
+
send(request) {
|
|
339
|
+
return new Observable((observer) => {
|
|
340
|
+
const xhr = new XMLHttpRequest();
|
|
341
|
+
xhr.open(request.method, request.getUrlWithParams()), request.withCredentials && (xhr.withCredentials = !0), request.headers.forEach((key, value) => xhr.setRequestHeader(key, value.join(","))), request.headers.has("Accept") || xhr.setRequestHeader("Accept", "application/json, text/plain, */*"), request.headers.has("Content-Type") || xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
|
|
342
|
+
const buildResponseHeader = /* @__PURE__ */ __name(() => {
|
|
343
|
+
const statusText = xhr.statusText || "OK", headers = new HTTPHeaders(xhr.getAllResponseHeaders());
|
|
344
|
+
return new ResponseHeader(headers, xhr.status, statusText);
|
|
345
|
+
}, "buildResponseHeader"), onLoadHandler = /* @__PURE__ */ __name(() => {
|
|
346
|
+
const { headers, statusText, status } = buildResponseHeader(), { responseType } = request;
|
|
347
|
+
let body2 = null, error = null;
|
|
348
|
+
status !== HTTPStatusCode.NoContent && (body2 = typeof xhr.response > "u" ? xhr.responseText : xhr.response);
|
|
349
|
+
let success = status >= SuccessStatusCodeLowerBound && status < ErrorStatusCodeLowerBound;
|
|
350
|
+
if (responseType === "json" && typeof body2 == "string") {
|
|
351
|
+
const originalBody = body2;
|
|
336
352
|
try {
|
|
337
|
-
|
|
338
|
-
} catch (
|
|
339
|
-
|
|
353
|
+
body2 = body2 ? JSON.parse(body2) : null;
|
|
354
|
+
} catch (e) {
|
|
355
|
+
success = !1, body2 = originalBody, error = e;
|
|
340
356
|
}
|
|
341
357
|
}
|
|
342
|
-
|
|
343
|
-
new
|
|
344
|
-
body:
|
|
345
|
-
headers
|
|
346
|
-
status
|
|
347
|
-
statusText
|
|
358
|
+
success ? observer.next(
|
|
359
|
+
new HTTPResponse({
|
|
360
|
+
body: body2,
|
|
361
|
+
headers,
|
|
362
|
+
status,
|
|
363
|
+
statusText
|
|
348
364
|
})
|
|
349
|
-
) :
|
|
350
|
-
new
|
|
351
|
-
error
|
|
352
|
-
headers
|
|
353
|
-
status
|
|
354
|
-
statusText
|
|
365
|
+
) : observer.error(
|
|
366
|
+
new HTTPResponseError({
|
|
367
|
+
error,
|
|
368
|
+
headers,
|
|
369
|
+
status,
|
|
370
|
+
statusText
|
|
355
371
|
})
|
|
356
372
|
);
|
|
357
|
-
},
|
|
358
|
-
const
|
|
359
|
-
error
|
|
360
|
-
status:
|
|
361
|
-
statusText:
|
|
362
|
-
headers:
|
|
373
|
+
}, "onLoadHandler"), onErrorHandler = /* @__PURE__ */ __name((error) => {
|
|
374
|
+
const res = new HTTPResponseError({
|
|
375
|
+
error,
|
|
376
|
+
status: xhr.status || 0,
|
|
377
|
+
statusText: xhr.statusText || "Unknown Error",
|
|
378
|
+
headers: buildResponseHeader().headers
|
|
363
379
|
});
|
|
364
|
-
|
|
365
|
-
};
|
|
366
|
-
|
|
367
|
-
const
|
|
368
|
-
return
|
|
369
|
-
|
|
380
|
+
observer.error(res);
|
|
381
|
+
}, "onErrorHandler");
|
|
382
|
+
xhr.addEventListener("load", onLoadHandler), xhr.addEventListener("error", onErrorHandler), xhr.addEventListener("abort", onErrorHandler), xhr.addEventListener("timeout", onErrorHandler);
|
|
383
|
+
const body = request.getBody();
|
|
384
|
+
return xhr.send(body), () => {
|
|
385
|
+
xhr.readyState !== xhr.DONE && xhr.abort(), xhr.removeEventListener("load", onLoadHandler), xhr.removeEventListener("error", onErrorHandler), xhr.removeEventListener("abort", onErrorHandler), xhr.removeEventListener("timeout", onErrorHandler);
|
|
370
386
|
};
|
|
371
387
|
});
|
|
372
388
|
}
|
|
373
|
-
}
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
389
|
+
};
|
|
390
|
+
__name(_XHRHTTPImplementation, "XHRHTTPImplementation");
|
|
391
|
+
let XHRHTTPImplementation = _XHRHTTPImplementation;
|
|
392
|
+
const ISocketService = createIdentifier("univer.socket"), _WebSocketService = class _WebSocketService extends Disposable {
|
|
393
|
+
createSocket(URL) {
|
|
377
394
|
try {
|
|
378
|
-
const
|
|
395
|
+
const connection = new WebSocket(URL), disposables = new DisposableCollection();
|
|
379
396
|
return {
|
|
380
|
-
URL
|
|
381
|
-
close: (
|
|
382
|
-
|
|
383
|
-
},
|
|
384
|
-
send: (
|
|
385
|
-
|
|
386
|
-
},
|
|
387
|
-
open$: new
|
|
388
|
-
const
|
|
389
|
-
|
|
390
|
-
}).pipe(
|
|
391
|
-
close$: new
|
|
392
|
-
const
|
|
393
|
-
|
|
394
|
-
}).pipe(
|
|
395
|
-
error$: new
|
|
396
|
-
const
|
|
397
|
-
|
|
398
|
-
}).pipe(
|
|
399
|
-
message$: new
|
|
400
|
-
const
|
|
401
|
-
|
|
402
|
-
}).pipe(
|
|
397
|
+
URL,
|
|
398
|
+
close: /* @__PURE__ */ __name((code, reason) => {
|
|
399
|
+
connection.close(code, reason), disposables.dispose();
|
|
400
|
+
}, "close"),
|
|
401
|
+
send: /* @__PURE__ */ __name((data) => {
|
|
402
|
+
connection.send(data);
|
|
403
|
+
}, "send"),
|
|
404
|
+
open$: new Observable((subscriber) => {
|
|
405
|
+
const callback = /* @__PURE__ */ __name((event) => subscriber.next(event), "callback");
|
|
406
|
+
connection.addEventListener("open", callback), disposables.add(toDisposable(() => connection.removeEventListener("open", callback)));
|
|
407
|
+
}).pipe(share()),
|
|
408
|
+
close$: new Observable((subscriber) => {
|
|
409
|
+
const callback = /* @__PURE__ */ __name((event) => subscriber.next(event), "callback");
|
|
410
|
+
connection.addEventListener("close", callback), disposables.add(toDisposable(() => connection.removeEventListener("close", callback)));
|
|
411
|
+
}).pipe(share()),
|
|
412
|
+
error$: new Observable((subscriber) => {
|
|
413
|
+
const callback = /* @__PURE__ */ __name((event) => subscriber.next(event), "callback");
|
|
414
|
+
connection.addEventListener("error", callback), disposables.add(toDisposable(() => connection.removeEventListener("error", callback)));
|
|
415
|
+
}).pipe(share()),
|
|
416
|
+
message$: new Observable((subscriber) => {
|
|
417
|
+
const callback = /* @__PURE__ */ __name((event) => subscriber.next(event), "callback");
|
|
418
|
+
connection.addEventListener("message", callback), disposables.add(toDisposable(() => connection.removeEventListener("message", callback)));
|
|
419
|
+
}).pipe(share())
|
|
403
420
|
};
|
|
404
|
-
} catch (
|
|
405
|
-
return console.error(
|
|
421
|
+
} catch (e) {
|
|
422
|
+
return console.error(e), null;
|
|
406
423
|
}
|
|
407
424
|
}
|
|
408
|
-
}
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
425
|
+
};
|
|
426
|
+
__name(_WebSocketService, "WebSocketService");
|
|
427
|
+
let WebSocketService = _WebSocketService;
|
|
428
|
+
const DEFAULT_MAX_RETRY_ATTEMPTS = 3, DELAY_INTERVAL = 1e3, RetryInterceptorFactory = /* @__PURE__ */ __name((_accessor, params) => {
|
|
429
|
+
var _a2, _b;
|
|
430
|
+
const maxRetryAttempts = (_a2 = params == null ? void 0 : params.maxRetryAttempts) != null ? _a2 : DEFAULT_MAX_RETRY_ATTEMPTS, delayInterval = (_b = params == null ? void 0 : params.delayInterval) != null ? _b : DELAY_INTERVAL;
|
|
431
|
+
return (request, next) => next(request).pipe(retry({ delay: delayInterval, count: maxRetryAttempts }));
|
|
432
|
+
}, "RetryInterceptorFactory"), ThresholdInterceptorFactory = /* @__PURE__ */ __name((params) => {
|
|
433
|
+
const handlers = [], ongoingHandlers = /* @__PURE__ */ new Set(), tick = /* @__PURE__ */ __name(() => {
|
|
434
|
+
var _a2;
|
|
435
|
+
for (; ongoingHandlers.size < ((_a2 = params == null ? void 0 : params.maxParallel) != null ? _a2 : 1) && handlers.length > 0; ) {
|
|
436
|
+
const handler = handlers.shift();
|
|
437
|
+
ongoingHandlers.add(handler), handler();
|
|
419
438
|
}
|
|
420
|
-
};
|
|
421
|
-
return (
|
|
422
|
-
const
|
|
423
|
-
next: (
|
|
424
|
-
error: (
|
|
425
|
-
complete: () =>
|
|
426
|
-
}),
|
|
427
|
-
|
|
428
|
-
};
|
|
429
|
-
return
|
|
439
|
+
}, "tick");
|
|
440
|
+
return (request, next) => new Observable((observer) => {
|
|
441
|
+
const handler = /* @__PURE__ */ __name(() => next(request).subscribe({
|
|
442
|
+
next: /* @__PURE__ */ __name((event) => observer.next(event), "next"),
|
|
443
|
+
error: /* @__PURE__ */ __name((err) => observer.next(err), "error"),
|
|
444
|
+
complete: /* @__PURE__ */ __name(() => observer.complete(), "complete")
|
|
445
|
+
}), "handler"), teardown = /* @__PURE__ */ __name(() => {
|
|
446
|
+
ongoingHandlers.delete(handler), remove(handlers, handler), tick();
|
|
447
|
+
}, "teardown");
|
|
448
|
+
return handlers.push(handler), tick(), teardown;
|
|
430
449
|
});
|
|
431
|
-
},
|
|
432
|
-
const { errorStatusCodes
|
|
433
|
-
return (
|
|
434
|
-
|
|
435
|
-
);
|
|
436
|
-
},
|
|
437
|
-
let
|
|
438
|
-
};
|
|
439
|
-
return (
|
|
440
|
-
|
|
441
|
-
const
|
|
442
|
-
|
|
443
|
-
},
|
|
444
|
-
|
|
445
|
-
clearTimeout(
|
|
446
|
-
};
|
|
450
|
+
}, "ThresholdInterceptorFactory"), AuthInterceptorFactory = /* @__PURE__ */ __name((params) => {
|
|
451
|
+
const { errorStatusCodes, onAuthError } = params;
|
|
452
|
+
return /* @__PURE__ */ __name((request, next) => next(request).pipe(
|
|
453
|
+
catchError((error) => (error instanceof HTTPResponseError && errorStatusCodes.some((c) => c === error.status) && onAuthError(), throwError(() => error)))
|
|
454
|
+
), "authInterceptor");
|
|
455
|
+
}, "AuthInterceptorFactory"), createDefaultFetchCheck = /* @__PURE__ */ __name((time = 300) => {
|
|
456
|
+
let cancel = /* @__PURE__ */ __name(() => {
|
|
457
|
+
}, "noop");
|
|
458
|
+
return (_currentConfig) => new Promise((res) => {
|
|
459
|
+
cancel();
|
|
460
|
+
const t = setTimeout(() => {
|
|
461
|
+
res(!0);
|
|
462
|
+
}, time);
|
|
463
|
+
cancel = /* @__PURE__ */ __name(() => {
|
|
464
|
+
clearTimeout(t), res(!1);
|
|
465
|
+
}, "cancel");
|
|
447
466
|
});
|
|
448
|
-
},
|
|
449
|
-
const { isMatch
|
|
450
|
-
return (
|
|
451
|
-
const
|
|
452
|
-
|
|
453
|
-
next: (
|
|
454
|
-
error: (
|
|
455
|
-
config:
|
|
467
|
+
}, "createDefaultFetchCheck"), createDistributeResult = /* @__PURE__ */ __name(() => (result, list) => list.map((config) => ({ config, result })), "createDistributeResult"), MergeInterceptorFactory = /* @__PURE__ */ __name((config, options = {}) => {
|
|
468
|
+
const { isMatch, getParamsFromRequest, mergeParamsToRequest } = config, { fetchCheck = createDefaultFetchCheck(300), distributeResult = createDistributeResult() } = options, hookList = [], getPlainList = /* @__PURE__ */ __name((_list) => _list.map((item) => item.config), "getPlainList");
|
|
469
|
+
return (requestConfig, next) => isMatch(requestConfig) ? new Observable((observer) => {
|
|
470
|
+
const params = getParamsFromRequest(requestConfig);
|
|
471
|
+
hookList.push({
|
|
472
|
+
next: /* @__PURE__ */ __name((v) => observer.next(v), "next"),
|
|
473
|
+
error: /* @__PURE__ */ __name((error) => observer.error(error), "error"),
|
|
474
|
+
config: params
|
|
456
475
|
});
|
|
457
|
-
const
|
|
458
|
-
|
|
459
|
-
if (
|
|
460
|
-
const
|
|
461
|
-
|
|
462
|
-
const
|
|
463
|
-
if (
|
|
464
|
-
const [
|
|
465
|
-
|
|
476
|
+
const list = getPlainList(hookList);
|
|
477
|
+
fetchCheck(requestConfig).then((isFetch) => {
|
|
478
|
+
if (isFetch) {
|
|
479
|
+
const currentHookList = [];
|
|
480
|
+
list.forEach((config2) => {
|
|
481
|
+
const index = hookList.findIndex((item) => item.config === config2);
|
|
482
|
+
if (index >= 0) {
|
|
483
|
+
const [hook] = hookList.splice(index, 1);
|
|
484
|
+
currentHookList.push(hook);
|
|
466
485
|
}
|
|
467
|
-
}),
|
|
468
|
-
next: (
|
|
469
|
-
if (
|
|
470
|
-
const
|
|
471
|
-
|
|
472
|
-
const
|
|
473
|
-
if (
|
|
474
|
-
const
|
|
475
|
-
body:
|
|
476
|
-
headers:
|
|
477
|
-
status:
|
|
478
|
-
statusText:
|
|
486
|
+
}), next(mergeParamsToRequest(list, requestConfig)).subscribe({
|
|
487
|
+
next: /* @__PURE__ */ __name((e) => {
|
|
488
|
+
if (e.type === HTTPEventType.Response) {
|
|
489
|
+
const body = e.body, configList = distributeResult(body, list);
|
|
490
|
+
currentHookList.forEach((hookItem) => {
|
|
491
|
+
const res = configList.find((item) => item.config === hookItem.config);
|
|
492
|
+
if (res) {
|
|
493
|
+
const response = new HTTPResponse({
|
|
494
|
+
body: res.result,
|
|
495
|
+
headers: e.headers,
|
|
496
|
+
status: e.status,
|
|
497
|
+
statusText: e.statusText
|
|
479
498
|
});
|
|
480
|
-
|
|
499
|
+
hookItem.next(response);
|
|
481
500
|
} else
|
|
482
|
-
|
|
501
|
+
hookItem.error("batch error");
|
|
483
502
|
});
|
|
484
503
|
}
|
|
485
|
-
},
|
|
486
|
-
complete: () =>
|
|
487
|
-
error: (
|
|
504
|
+
}, "next"),
|
|
505
|
+
complete: /* @__PURE__ */ __name(() => observer.complete(), "complete"),
|
|
506
|
+
error: /* @__PURE__ */ __name((e) => observer.error(e), "error")
|
|
488
507
|
});
|
|
489
508
|
}
|
|
490
509
|
});
|
|
491
|
-
}) :
|
|
492
|
-
};
|
|
510
|
+
}) : next(requestConfig);
|
|
511
|
+
}, "MergeInterceptorFactory");
|
|
493
512
|
export {
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
513
|
+
AuthInterceptorFactory,
|
|
514
|
+
FetchHTTPImplementation,
|
|
515
|
+
HTTPEventType,
|
|
516
|
+
HTTPHeaders,
|
|
517
|
+
HTTPProgress,
|
|
518
|
+
HTTPRequest,
|
|
519
|
+
HTTPResponse,
|
|
520
|
+
HTTPResponseError,
|
|
521
|
+
HTTPService,
|
|
522
|
+
HTTPStatusCode,
|
|
523
|
+
IHTTPImplementation,
|
|
524
|
+
ISocketService,
|
|
525
|
+
MergeInterceptorFactory,
|
|
526
|
+
ResponseHeader,
|
|
527
|
+
RetryInterceptorFactory,
|
|
528
|
+
ThresholdInterceptorFactory,
|
|
529
|
+
WebSocketService,
|
|
530
|
+
XHRHTTPImplementation
|
|
512
531
|
};
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { Observable } from 'rxjs';
|
|
2
|
-
import { Disposable } from '@univerjs/core';
|
|
3
|
-
import { Injector } from '@wendellhu/redi';
|
|
2
|
+
import { Disposable, Injector } from '@univerjs/core';
|
|
4
3
|
import { IHTTPImplementation } from '../implementations/implementation';
|
|
5
4
|
import { HTTPRequest } from '../request';
|
|
6
5
|
import { HTTPEvent, HTTPResponse, HTTPResponseError } from '../response';
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import { Disposable } from '@univerjs/core';
|
|
2
|
-
import { IDisposable } from '@wendellhu/redi';
|
|
1
|
+
import { IDisposable, Disposable } from '@univerjs/core';
|
|
3
2
|
import { Observable } from 'rxjs';
|
|
4
3
|
import { HTTPResponseType } from './http';
|
|
5
4
|
import { IHTTPImplementation } from './implementations/implementation';
|
|
@@ -12,4 +12,4 @@ export interface IHTTPImplementation {
|
|
|
12
12
|
*/
|
|
13
13
|
send(request: HTTPRequest): Observable<HTTPEvent<any>>;
|
|
14
14
|
}
|
|
15
|
-
export declare const IHTTPImplementation: import('@
|
|
15
|
+
export declare const IHTTPImplementation: import('@univerjs/core').IdentifierDecorator<IHTTPImplementation>;
|
|
@@ -5,7 +5,7 @@ export type SocketBodyType = string | ArrayBufferLike | Blob | ArrayBufferView;
|
|
|
5
5
|
/**
|
|
6
6
|
* This service is responsible for establishing bidi-directional connection to a remote server.
|
|
7
7
|
*/
|
|
8
|
-
export declare const ISocketService: import('@
|
|
8
|
+
export declare const ISocketService: import('@univerjs/core').IdentifierDecorator<ISocketService>;
|
|
9
9
|
export interface ISocketService {
|
|
10
10
|
createSocket(url: string): Nullable<ISocket>;
|
|
11
11
|
}
|
package/lib/umd/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(
|
|
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 O=k.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 G=0;class x{constructor(n,r,t){w(this,"uid",G++);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:D,r=(s=this.requestParams)==null?void 0:s.body;return n===D&&r&&typeof r=="object"?JSON.stringify(r):r?`${r}`:null}getHeadersInit(){return this.headers.toHeadersInit()}}var V=Object.defineProperty,W=Object.getOwnPropertyDescriptor,X=(e,n,r,t)=>{for(var s=t>1?void 0:t?W(n,r):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(t?i(n,r,s):i(s))||s);return t&&s&&V(n,r,s),s},z=(e,n)=>(r,t)=>n(r,t,e);c.HTTPService=class extends p.Disposable{constructor(r){super();w(this,"_interceptors",[]);w(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,l;const o=new _(s==null?void 0:s.headers),i=new M(s==null?void 0:s.params),a=new x(r,t,{headers:o,params:i,withCredentials:(d=s==null?void 0:s.withCredentials)!=null?d:!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 y.of(a).pipe(E.concatMap(h=>this._runInterceptorsAndImplementation(h)))}async _request(r,t,s){var h,m;const o=new _(s==null?void 0:s.headers),i=new M(s==null?void 0:s.params),a=new x(r,t,{headers:o,params:i,withCredentials:(h=s==null?void 0:s.withCredentials)!=null?h:!1,responseType:(m=s==null?void 0:s.responseType)!=null?m:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body}),d=y.of(a).pipe(E.concatMap(u=>this._runInterceptorsAndImplementation(u)));return await y.firstValueFrom(d)}_runInterceptorsAndImplementation(r){return this._pipe||(this._pipe=this._interceptors.map(t=>t.interceptor).reduceRight((t,s)=>J(t,s),(t,s)=>s(t))),this._pipe(r,t=>this._http.send(t))}},c.HTTPService=X([z(0,O)],c.HTTPService);function J(e,n){return(r,t)=>n(r,s=>e(s,t))}var q=(e=>(e[e.DownloadProgress=0]="DownloadProgress",e[e.Response=1]="Response",e))(q||{});class F{constructor({body:n,headers:r,status:t,statusText:s}){w(this,"type",1);w(this,"body");w(this,"headers");w(this,"status");w(this,"statusText");this.body=n,this.headers=r,this.status=t,this.statusText=s}}class j{constructor(n,r,t){w(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 R{constructor({headers:n,status:r,statusText:t,error:s}){w(this,"headers");w(this,"status");w(this,"statusText");w(this,"error");this.headers=n,this.status=r,this.statusText=t,this.error=s}}const Y=200,K=300;var I=(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))(I||{});class Q{send(n){return new y.Observable(r=>{const t=new AbortController;return this._send(n,r,t).then(()=>{},s=>{r.error(new R({error:s}))}),()=>t.abort()})}async _send(n,r,t){var h,m;let s;try{const u=this._parseFetchParamsFromRequest(n);s=await fetch(n.getUrlWithParams(),{signal:t.signal,...u})}catch(u){r.error(new R({error:u,status:(h=u.status)!=null?h:0,statusText:(m=u.statusText)!=null?m:"Unknown Error",headers:u.headers}));return}const o=new _(s.headers),i=s.status,a=s.statusText;let d=null;s.body&&(d=await this._readBody(n,s,r)),i>=I.Ok&&i<I.MultipleChoices?r.next(new F({body:d,headers:o,status:i,statusText:a})):r.error(new R({error:d,status:i,statusText:a,headers:o})),r.complete()}async _readBody(n,r,t){var b,g;const s=[],o=r.body.getReader(),i=r.headers.get("content-length");let a=0;const d=(b=n.requestParams)==null?void 0:b.reportProgress,l=n.responseType;let h,m;for(;;){const{done:v,value:f}=await o.read();if(v)break;s.push(f),a+=f.length,d&&l==="text"&&(h=(h!=null?h:"")+(m!=null?m:m=new TextDecoder).decode(f,{stream:!0}),t.next(new j(i?Number.parseInt(i,10):void 0,a,h)))}const u=Z(s,a);try{const v=(g=r.headers.get("content-type"))!=null?g:"";return H(n,u,v)}catch(v){return t.error(new R({error:v,status:r.status,statusText:r.statusText,headers:new _(r.headers)})),null}}_parseFetchParamsFromRequest(n){return{method:n.method,headers:n.getHeadersInit(),body:n.getBody(),credentials:n.withCredentials?"include":void 0}}}function Z(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 P=/^\)\]\}',?\n/;function H(e,n,r){switch(e.responseType){case"json":const t=new TextDecoder().decode(n).replace(P,"");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}.`)}}class S{send(n){return new y.Observable(r=>{const t=new XMLHttpRequest;t.open(n.method,n.getUrlWithParams()),n.withCredentials&&(t.withCredentials=!0),n.headers.forEach((d,l)=>t.setRequestHeader(d,l.join(","))),n.headers.has("Accept")||t.setRequestHeader("Accept","application/json, text/plain, */*"),n.headers.has("Content-Type")||t.setRequestHeader("Content-Type","application/json;charset=UTF-8");const s=()=>{const d=t.statusText||"OK",l=new _(t.getAllResponseHeaders());return new B(l,t.status,d)},o=()=>{const{headers:d,statusText:l,status:h}=s(),{responseType:m}=n;let u=null,b=null;h!==I.NoContent&&(u=typeof t.response>"u"?t.responseText:t.response);let g=h>=Y&&h<K;if(m==="json"&&typeof u=="string"){const v=u;try{u=u?JSON.parse(u):null}catch(f){g=!1,u=v,b=f}}g?r.next(new F({body:u,headers:d,status:h,statusText:l})):r.error(new R({error:b,headers:d,status:h,statusText:l}))},i=d=>{const l=new R({error:d,status:t.status||0,statusText:t.statusText||"Unknown Error",headers:s().headers});r.error(l)};t.addEventListener("load",o),t.addEventListener("error",i),t.addEventListener("abort",i),t.addEventListener("timeout",i);const a=n.getBody();return t.send(a),()=>{t.readyState!==t.DONE&&t.abort(),t.removeEventListener("load",o),t.removeEventListener("error",i),t.removeEventListener("abort",i),t.removeEventListener("timeout",i)}})}}const C=k.createIdentifier("univer.socket");class T 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 y.Observable(o=>{const i=a=>o.next(a);r.addEventListener("open",i),t.add(p.toDisposable(()=>r.removeEventListener("open",i)))}).pipe(E.share()),close$:new y.Observable(o=>{const i=a=>o.next(a);r.addEventListener("close",i),t.add(p.toDisposable(()=>r.removeEventListener("close",i)))}).pipe(E.share()),error$:new y.Observable(o=>{const i=a=>o.next(a);r.addEventListener("error",i),t.add(p.toDisposable(()=>r.removeEventListener("error",i)))}).pipe(E.share()),message$:new y.Observable(o=>{const i=a=>o.next(a);r.addEventListener("message",i),t.add(p.toDisposable(()=>r.removeEventListener("message",i)))}).pipe(E.share())}}catch(r){return console.error(r),null}}}const ee=3,re=1e3,te=(e,n)=>{var s,o;const r=(s=n==null?void 0:n.maxRetryAttempts)!=null?s:ee,t=(o=n==null?void 0:n.delayInterval)!=null?o:re;return(i,a)=>a(i).pipe(E.retry({delay:t,count:r}))},ne=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 y.Observable(i=>{const a=()=>o(s).subscribe({next:l=>i.next(l),error:l=>i.next(l),complete:()=>i.complete()}),d=()=>{r.delete(a),p.remove(n,a),t()};return n.push(a),t(),d})},se=e=>{const{errorStatusCodes:n,onAuthError:r}=e;return(s,o)=>o(s).pipe(y.catchError(i=>(i instanceof R&&n.some(a=>a===i.status)&&r(),y.throwError(()=>i))))},ie=(e=300)=>{let r=()=>{};return t=>new Promise(s=>{r();const o=setTimeout(()=>{s(!0)},e);r=()=>{clearTimeout(o),s(!1)}})},oe=()=>(e,n)=>n.map(r=>({config:r,result:e})),ce=(e,n={})=>{const{isMatch:r,getParamsFromRequest:t,mergeParamsToRequest:s}=e,{fetchCheck:o=ie(300),distributeResult:i=oe()}=n,a=[],d=l=>l.map(h=>h.config);return(l,h)=>r(l)?new y.Observable(m=>{const u=t(l);a.push({next:g=>m.next(g),error:g=>m.error(g),config:u});const b=d(a);o(l).then(g=>{if(g){const v=[];b.forEach(f=>{const A=a.findIndex(L=>L.config===f);if(A>=0){const[L]=a.splice(A,1);v.push(L)}}),h(s(b,l)).subscribe({next:f=>{if(f.type===q.Response){const A=f.body,L=i(A,b);v.forEach(N=>{const $=L.find(U=>U.config===N.config);if($){const U=new F({body:$.result,headers:f.headers,status:f.status,statusText:f.statusText});N.next(U)}else N.error("batch error")})}},complete:()=>m.complete(),error:f=>m.error(f)})}})}):h(l)};c.AuthInterceptorFactory=se,c.FetchHTTPImplementation=Q,c.HTTPEventType=q,c.HTTPHeaders=_,c.HTTPProgress=j,c.HTTPRequest=x,c.HTTPResponse=F,c.HTTPResponseError=R,c.HTTPStatusCode=I,c.IHTTPImplementation=O,c.ISocketService=C,c.MergeInterceptorFactory=ce,c.ResponseHeader=B,c.RetryInterceptorFactory=te,c.ThresholdInterceptorFactory=ne,c.WebSocketService=T,c.XHRHTTPImplementation=S,Object.defineProperty(c,Symbol.toStringTag,{value:"Module"})});
|
|
1
|
+
(function(global,factory){typeof exports=="object"&&typeof module<"u"?factory(exports,require("@univerjs/core"),require("rxjs"),require("rxjs/operators")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","rxjs","rxjs/operators"],factory):(global=typeof globalThis<"u"?globalThis:global||self,factory(global.UniverNetwork={},global.UniverCore,global.rxjs,global.rxjs.operators))})(this,function(exports2,core,rxjs,operators){"use strict";var __defProp=Object.defineProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!="symbol"?key+"":key,value);var _a;const ApplicationJSONType="application/json",_HTTPHeaders=class _HTTPHeaders{constructor(headers){__publicField(this,"_headers",new Map);typeof headers=="string"?this._handleHeadersString(headers):headers instanceof Headers?this._handleHeaders(headers):headers&&this._handleHeadersConstructorProps(headers)}forEach(callback){this._headers.forEach((v,key)=>callback(key,v))}has(key){return!!this._headers.has(key.toLowerCase())}get(key){const k=key.toLowerCase();return this._headers.has(k)?this._headers.get(k):null}toHeadersInit(){var _a2,_b;const headers={};return this._headers.forEach((values,key)=>{headers[key]=values.join(",")}),(_a2=headers.accept)!=null||(headers.accept="application/json, text/plain, */*"),(_b=headers["content-type"])!=null||(headers["content-type"]="application/json;charset=UTF-8"),headers}_setHeader(name,value){const lowerCase=name.toLowerCase();this._headers.has(lowerCase)?this._headers.get(lowerCase).push(value.toString()):this._headers.set(lowerCase,[value.toString()])}_handleHeadersString(headers){headers.split(`
|
|
2
|
+
`).forEach(header=>{const[name,value]=header.split(":");name&&value&&this._setHeader(name,value)})}_handleHeadersConstructorProps(headers){Object.entries(headers).forEach(([name,value])=>this._setHeader(name,value))}_handleHeaders(headers){headers.forEach((value,name)=>this._setHeader(name,value))}};__name(_HTTPHeaders,"HTTPHeaders");let HTTPHeaders=_HTTPHeaders;const IHTTPImplementation=core.createIdentifier("network.http-implementation"),_HTTPParams=class _HTTPParams{constructor(params){this.params=params}toString(){return this.params?Object.keys(this.params).map(key=>`${key}=${this.params[key]}`).join("&"):""}};__name(_HTTPParams,"HTTPParams");let HTTPParams=_HTTPParams,HTTPRequestUID=0;const _HTTPRequest=class _HTTPRequest{constructor(method,url,requestParams){__publicField(this,"uid",HTTPRequestUID++);this.method=method,this.url=url,this.requestParams=requestParams}get headers(){return this.requestParams.headers}get withCredentials(){return this.requestParams.withCredentials}get responseType(){return this.requestParams.responseType}getUrlWithParams(){var _a2,_b;const params=(_b=(_a2=this.requestParams)==null?void 0:_a2.params)==null?void 0:_b.toString();return params?`${this.url}${this.url.includes("?")?"&":"?"}${params}`:this.url}getBody(){var _a2,_b;const contentType=(_a2=this.headers.get("Content-Type"))!=null?_a2:ApplicationJSONType,body=(_b=this.requestParams)==null?void 0:_b.body;return contentType===ApplicationJSONType&&body&&typeof body=="object"?JSON.stringify(body):body?`${body}`:null}getHeadersInit(){return this.headers.toHeadersInit()}};__name(_HTTPRequest,"HTTPRequest");let HTTPRequest=_HTTPRequest;var __defProp2=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__decorateClass=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp2(target,key,result),result},"__decorateClass"),__decorateParam=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam");exports2.HTTPService=(_a=class extends core.Disposable{constructor(_http){super();__publicField(this,"_interceptors",[]);__publicField(this,"_pipe");this._http=_http}registerHTTPInterceptor(interceptor){if(this._interceptors.indexOf(interceptor)!==-1)throw new Error("[HTTPService]: The interceptor has already been registered!");return this._interceptors.push(interceptor),this._interceptors=this._interceptors.sort((a,b)=>{var _a2,_b;return((_a2=a.priority)!=null?_a2:0)-((_b=b.priority)!=null?_b:0)}),this._pipe=null,core.toDisposable(()=>core.remove(this._interceptors,interceptor))}get(url,params){return this._request("GET",url,params)}post(url,params){return this._request("POST",url,params)}put(url,params){return this._request("PUT",url,params)}delete(url,params){return this._request("DELETE",url,params)}patch(url,options){return this._request("PATCH",url,options)}getSSE(method,url,options){var _a2,_b;const headers=new HTTPHeaders(options==null?void 0:options.headers),params=new HTTPParams(options==null?void 0:options.params),request=new HTTPRequest(method,url,{headers,params,withCredentials:(_a2=options==null?void 0:options.withCredentials)!=null?_a2:!1,reportProgress:!0,responseType:(_b=options==null?void 0:options.responseType)!=null?_b:"json",body:["GET","DELETE"].includes(method)||options==null?void 0:options.body});return rxjs.of(request).pipe(operators.concatMap(request2=>this._runInterceptorsAndImplementation(request2)))}async _request(method,url,options){var _a2,_b;const headers=new HTTPHeaders(options==null?void 0:options.headers),params=new HTTPParams(options==null?void 0:options.params),request=new HTTPRequest(method,url,{headers,params,withCredentials:(_a2=options==null?void 0:options.withCredentials)!=null?_a2:!1,responseType:(_b=options==null?void 0:options.responseType)!=null?_b:"json",body:["GET","DELETE"].includes(method)||options==null?void 0:options.body}),events$=rxjs.of(request).pipe(operators.concatMap(request2=>this._runInterceptorsAndImplementation(request2)));return await rxjs.firstValueFrom(events$)}_runInterceptorsAndImplementation(request){return this._pipe||(this._pipe=this._interceptors.map(handler=>handler.interceptor).reduceRight((nextHandlerFunction,interceptorFunction)=>chainInterceptorFn(nextHandlerFunction,interceptorFunction),(requestFromPrevInterceptor,finalHandler)=>finalHandler(requestFromPrevInterceptor))),this._pipe(request,requestToNext=>this._http.send(requestToNext))}},__name(_a,"HTTPService"),_a),exports2.HTTPService=__decorateClass([__decorateParam(0,IHTTPImplementation)],exports2.HTTPService);function chainInterceptorFn(afterInterceptorChain,currentInterceptorFn){return(prevRequest,nextHandlerFn)=>currentInterceptorFn(prevRequest,nextRequest=>afterInterceptorChain(nextRequest,nextHandlerFn))}__name(chainInterceptorFn,"chainInterceptorFn");var HTTPEventType=(HTTPEventType2=>(HTTPEventType2[HTTPEventType2.DownloadProgress=0]="DownloadProgress",HTTPEventType2[HTTPEventType2.Response=1]="Response",HTTPEventType2))(HTTPEventType||{});const _HTTPResponse=class _HTTPResponse{constructor({body,headers,status,statusText}){__publicField(this,"type",1);__publicField(this,"body");__publicField(this,"headers");__publicField(this,"status");__publicField(this,"statusText");this.body=body,this.headers=headers,this.status=status,this.statusText=statusText}};__name(_HTTPResponse,"HTTPResponse");let HTTPResponse=_HTTPResponse;const _HTTPProgress=class _HTTPProgress{constructor(total,loaded,partialText){__publicField(this,"type",0);this.total=total,this.loaded=loaded,this.partialText=partialText}};__name(_HTTPProgress,"HTTPProgress");let HTTPProgress=_HTTPProgress;const _ResponseHeader=class _ResponseHeader{constructor(headers,status,statusText){this.headers=headers,this.status=status,this.statusText=statusText}};__name(_ResponseHeader,"ResponseHeader");let ResponseHeader=_ResponseHeader;const _HTTPResponseError=class _HTTPResponseError{constructor({headers,status,statusText,error}){__publicField(this,"headers");__publicField(this,"status");__publicField(this,"statusText");__publicField(this,"error");this.headers=headers,this.status=status,this.statusText=statusText,this.error=error}};__name(_HTTPResponseError,"HTTPResponseError");let HTTPResponseError=_HTTPResponseError;const SuccessStatusCodeLowerBound=200,ErrorStatusCodeLowerBound=300;var HTTPStatusCode=(HTTPStatusCode2=>(HTTPStatusCode2[HTTPStatusCode2.Continue=100]="Continue",HTTPStatusCode2[HTTPStatusCode2.SwitchingProtocols=101]="SwitchingProtocols",HTTPStatusCode2[HTTPStatusCode2.Processing=102]="Processing",HTTPStatusCode2[HTTPStatusCode2.EarlyHints=103]="EarlyHints",HTTPStatusCode2[HTTPStatusCode2.Ok=200]="Ok",HTTPStatusCode2[HTTPStatusCode2.Created=201]="Created",HTTPStatusCode2[HTTPStatusCode2.Accepted=202]="Accepted",HTTPStatusCode2[HTTPStatusCode2.NonAuthoritativeInformation=203]="NonAuthoritativeInformation",HTTPStatusCode2[HTTPStatusCode2.NoContent=204]="NoContent",HTTPStatusCode2[HTTPStatusCode2.ResetContent=205]="ResetContent",HTTPStatusCode2[HTTPStatusCode2.PartialContent=206]="PartialContent",HTTPStatusCode2[HTTPStatusCode2.MultiStatus=207]="MultiStatus",HTTPStatusCode2[HTTPStatusCode2.AlreadyReported=208]="AlreadyReported",HTTPStatusCode2[HTTPStatusCode2.ImUsed=226]="ImUsed",HTTPStatusCode2[HTTPStatusCode2.MultipleChoices=300]="MultipleChoices",HTTPStatusCode2[HTTPStatusCode2.MovedPermanently=301]="MovedPermanently",HTTPStatusCode2[HTTPStatusCode2.Found=302]="Found",HTTPStatusCode2[HTTPStatusCode2.SeeOther=303]="SeeOther",HTTPStatusCode2[HTTPStatusCode2.NotModified=304]="NotModified",HTTPStatusCode2[HTTPStatusCode2.UseProxy=305]="UseProxy",HTTPStatusCode2[HTTPStatusCode2.Unused=306]="Unused",HTTPStatusCode2[HTTPStatusCode2.TemporaryRedirect=307]="TemporaryRedirect",HTTPStatusCode2[HTTPStatusCode2.PermanentRedirect=308]="PermanentRedirect",HTTPStatusCode2[HTTPStatusCode2.BadRequest=400]="BadRequest",HTTPStatusCode2[HTTPStatusCode2.Unauthorized=401]="Unauthorized",HTTPStatusCode2[HTTPStatusCode2.PaymentRequired=402]="PaymentRequired",HTTPStatusCode2[HTTPStatusCode2.Forbidden=403]="Forbidden",HTTPStatusCode2[HTTPStatusCode2.NotFound=404]="NotFound",HTTPStatusCode2[HTTPStatusCode2.MethodNotAllowed=405]="MethodNotAllowed",HTTPStatusCode2[HTTPStatusCode2.NotAcceptable=406]="NotAcceptable",HTTPStatusCode2[HTTPStatusCode2.ProxyAuthenticationRequired=407]="ProxyAuthenticationRequired",HTTPStatusCode2[HTTPStatusCode2.RequestTimeout=408]="RequestTimeout",HTTPStatusCode2[HTTPStatusCode2.Conflict=409]="Conflict",HTTPStatusCode2[HTTPStatusCode2.Gone=410]="Gone",HTTPStatusCode2[HTTPStatusCode2.LengthRequired=411]="LengthRequired",HTTPStatusCode2[HTTPStatusCode2.PreconditionFailed=412]="PreconditionFailed",HTTPStatusCode2[HTTPStatusCode2.PayloadTooLarge=413]="PayloadTooLarge",HTTPStatusCode2[HTTPStatusCode2.UriTooLong=414]="UriTooLong",HTTPStatusCode2[HTTPStatusCode2.UnsupportedMediaType=415]="UnsupportedMediaType",HTTPStatusCode2[HTTPStatusCode2.RangeNotSatisfiable=416]="RangeNotSatisfiable",HTTPStatusCode2[HTTPStatusCode2.ExpectationFailed=417]="ExpectationFailed",HTTPStatusCode2[HTTPStatusCode2.ImATeapot=418]="ImATeapot",HTTPStatusCode2[HTTPStatusCode2.MisdirectedRequest=421]="MisdirectedRequest",HTTPStatusCode2[HTTPStatusCode2.UnprocessableEntity=422]="UnprocessableEntity",HTTPStatusCode2[HTTPStatusCode2.Locked=423]="Locked",HTTPStatusCode2[HTTPStatusCode2.FailedDependency=424]="FailedDependency",HTTPStatusCode2[HTTPStatusCode2.TooEarly=425]="TooEarly",HTTPStatusCode2[HTTPStatusCode2.UpgradeRequired=426]="UpgradeRequired",HTTPStatusCode2[HTTPStatusCode2.PreconditionRequired=428]="PreconditionRequired",HTTPStatusCode2[HTTPStatusCode2.TooManyRequests=429]="TooManyRequests",HTTPStatusCode2[HTTPStatusCode2.RequestHeaderFieldsTooLarge=431]="RequestHeaderFieldsTooLarge",HTTPStatusCode2[HTTPStatusCode2.UnavailableForLegalReasons=451]="UnavailableForLegalReasons",HTTPStatusCode2[HTTPStatusCode2.InternalServerError=500]="InternalServerError",HTTPStatusCode2[HTTPStatusCode2.NotImplemented=501]="NotImplemented",HTTPStatusCode2[HTTPStatusCode2.BadGateway=502]="BadGateway",HTTPStatusCode2[HTTPStatusCode2.ServiceUnavailable=503]="ServiceUnavailable",HTTPStatusCode2[HTTPStatusCode2.GatewayTimeout=504]="GatewayTimeout",HTTPStatusCode2[HTTPStatusCode2.HttpVersionNotSupported=505]="HttpVersionNotSupported",HTTPStatusCode2[HTTPStatusCode2.VariantAlsoNegotiates=506]="VariantAlsoNegotiates",HTTPStatusCode2[HTTPStatusCode2.InsufficientStorage=507]="InsufficientStorage",HTTPStatusCode2[HTTPStatusCode2.LoopDetected=508]="LoopDetected",HTTPStatusCode2[HTTPStatusCode2.NotExtended=510]="NotExtended",HTTPStatusCode2[HTTPStatusCode2.NetworkAuthenticationRequired=511]="NetworkAuthenticationRequired",HTTPStatusCode2))(HTTPStatusCode||{});const _FetchHTTPImplementation=class _FetchHTTPImplementation{send(request){return new rxjs.Observable(subscriber=>{const abortController=new AbortController;return this._send(request,subscriber,abortController).then(()=>{},error=>{subscriber.error(new HTTPResponseError({error}))}),()=>abortController.abort()})}async _send(request,subscriber,abortController){var _a2,_b;let response;try{const fetchParams=this._parseFetchParamsFromRequest(request);response=await fetch(request.getUrlWithParams(),{signal:abortController.signal,...fetchParams})}catch(error){subscriber.error(new HTTPResponseError({error,status:(_a2=error.status)!=null?_a2:0,statusText:(_b=error.statusText)!=null?_b:"Unknown Error",headers:error.headers}));return}const responseHeaders=new HTTPHeaders(response.headers),status=response.status,statusText=response.statusText;let body=null;response.body&&(body=await this._readBody(request,response,subscriber)),status>=HTTPStatusCode.Ok&&status<HTTPStatusCode.MultipleChoices?subscriber.next(new HTTPResponse({body,headers:responseHeaders,status,statusText})):subscriber.error(new HTTPResponseError({error:body,status,statusText,headers:responseHeaders})),subscriber.complete()}async _readBody(request,response,subscriber){var _a2,_b;const chunks=[],reader=response.body.getReader(),contentLength=response.headers.get("content-length");let receivedLength=0;const reportProgress=(_a2=request.requestParams)==null?void 0:_a2.reportProgress,responseType=request.responseType;let partialText,decoder;for(;;){const{done,value}=await reader.read();if(done)break;chunks.push(value),receivedLength+=value.length,reportProgress&&responseType==="text"&&(partialText=(partialText!=null?partialText:"")+(decoder!=null?decoder:decoder=new TextDecoder).decode(value,{stream:!0}),subscriber.next(new HTTPProgress(contentLength?Number.parseInt(contentLength,10):void 0,receivedLength,partialText)))}const all=mergeChunks(chunks,receivedLength);try{const contentType=(_b=response.headers.get("content-type"))!=null?_b:"";return deserialize(request,all,contentType)}catch(error){return subscriber.error(new HTTPResponseError({error,status:response.status,statusText:response.statusText,headers:new HTTPHeaders(response.headers)})),null}}_parseFetchParamsFromRequest(request){return{method:request.method,headers:request.getHeadersInit(),body:request.getBody(),credentials:request.withCredentials?"include":void 0}}};__name(_FetchHTTPImplementation,"FetchHTTPImplementation");let FetchHTTPImplementation=_FetchHTTPImplementation;function mergeChunks(chunks,totalLength){const all=new Uint8Array(totalLength);let position=0;for(const chunk of chunks)all.set(chunk,position),position+=chunk.length;return all}__name(mergeChunks,"mergeChunks");const XSSI_PREFIX=/^\)\]\}',?\n/;function deserialize(request,bin,contentType){switch(request.responseType){case"json":const text=new TextDecoder().decode(bin).replace(XSSI_PREFIX,"");return text===""?null:JSON.parse(text);case"text":return new TextDecoder().decode(bin);case"blob":return new Blob([bin],{type:contentType});case"arraybuffer":return bin.buffer;default:throw new Error(`[FetchHTTPImplementation]: unknown response type: ${request.responseType}.`)}}__name(deserialize,"deserialize");const _XHRHTTPImplementation=class _XHRHTTPImplementation{send(request){return new rxjs.Observable(observer=>{const xhr=new XMLHttpRequest;xhr.open(request.method,request.getUrlWithParams()),request.withCredentials&&(xhr.withCredentials=!0),request.headers.forEach((key,value)=>xhr.setRequestHeader(key,value.join(","))),request.headers.has("Accept")||xhr.setRequestHeader("Accept","application/json, text/plain, */*"),request.headers.has("Content-Type")||xhr.setRequestHeader("Content-Type","application/json;charset=UTF-8");const buildResponseHeader=__name(()=>{const statusText=xhr.statusText||"OK",headers=new HTTPHeaders(xhr.getAllResponseHeaders());return new ResponseHeader(headers,xhr.status,statusText)},"buildResponseHeader"),onLoadHandler=__name(()=>{const{headers,statusText,status}=buildResponseHeader(),{responseType}=request;let body2=null,error=null;status!==HTTPStatusCode.NoContent&&(body2=typeof xhr.response>"u"?xhr.responseText:xhr.response);let success=status>=SuccessStatusCodeLowerBound&&status<ErrorStatusCodeLowerBound;if(responseType==="json"&&typeof body2=="string"){const originalBody=body2;try{body2=body2?JSON.parse(body2):null}catch(e){success=!1,body2=originalBody,error=e}}success?observer.next(new HTTPResponse({body:body2,headers,status,statusText})):observer.error(new HTTPResponseError({error,headers,status,statusText}))},"onLoadHandler"),onErrorHandler=__name(error=>{const res=new HTTPResponseError({error,status:xhr.status||0,statusText:xhr.statusText||"Unknown Error",headers:buildResponseHeader().headers});observer.error(res)},"onErrorHandler");xhr.addEventListener("load",onLoadHandler),xhr.addEventListener("error",onErrorHandler),xhr.addEventListener("abort",onErrorHandler),xhr.addEventListener("timeout",onErrorHandler);const body=request.getBody();return xhr.send(body),()=>{xhr.readyState!==xhr.DONE&&xhr.abort(),xhr.removeEventListener("load",onLoadHandler),xhr.removeEventListener("error",onErrorHandler),xhr.removeEventListener("abort",onErrorHandler),xhr.removeEventListener("timeout",onErrorHandler)}})}};__name(_XHRHTTPImplementation,"XHRHTTPImplementation");let XHRHTTPImplementation=_XHRHTTPImplementation;const ISocketService=core.createIdentifier("univer.socket"),_WebSocketService=class _WebSocketService extends core.Disposable{createSocket(URL){try{const connection=new WebSocket(URL),disposables=new core.DisposableCollection;return{URL,close:__name((code,reason)=>{connection.close(code,reason),disposables.dispose()},"close"),send:__name(data=>{connection.send(data)},"send"),open$:new rxjs.Observable(subscriber=>{const callback=__name(event=>subscriber.next(event),"callback");connection.addEventListener("open",callback),disposables.add(core.toDisposable(()=>connection.removeEventListener("open",callback)))}).pipe(operators.share()),close$:new rxjs.Observable(subscriber=>{const callback=__name(event=>subscriber.next(event),"callback");connection.addEventListener("close",callback),disposables.add(core.toDisposable(()=>connection.removeEventListener("close",callback)))}).pipe(operators.share()),error$:new rxjs.Observable(subscriber=>{const callback=__name(event=>subscriber.next(event),"callback");connection.addEventListener("error",callback),disposables.add(core.toDisposable(()=>connection.removeEventListener("error",callback)))}).pipe(operators.share()),message$:new rxjs.Observable(subscriber=>{const callback=__name(event=>subscriber.next(event),"callback");connection.addEventListener("message",callback),disposables.add(core.toDisposable(()=>connection.removeEventListener("message",callback)))}).pipe(operators.share())}}catch(e){return console.error(e),null}}};__name(_WebSocketService,"WebSocketService");let WebSocketService=_WebSocketService;const DEFAULT_MAX_RETRY_ATTEMPTS=3,DELAY_INTERVAL=1e3,RetryInterceptorFactory=__name((_accessor,params)=>{var _a2,_b;const maxRetryAttempts=(_a2=params==null?void 0:params.maxRetryAttempts)!=null?_a2:DEFAULT_MAX_RETRY_ATTEMPTS,delayInterval=(_b=params==null?void 0:params.delayInterval)!=null?_b:DELAY_INTERVAL;return(request,next)=>next(request).pipe(operators.retry({delay:delayInterval,count:maxRetryAttempts}))},"RetryInterceptorFactory"),ThresholdInterceptorFactory=__name(params=>{const handlers=[],ongoingHandlers=new Set,tick=__name(()=>{var _a2;for(;ongoingHandlers.size<((_a2=params==null?void 0:params.maxParallel)!=null?_a2:1)&&handlers.length>0;){const handler=handlers.shift();ongoingHandlers.add(handler),handler()}},"tick");return(request,next)=>new rxjs.Observable(observer=>{const handler=__name(()=>next(request).subscribe({next:__name(event=>observer.next(event),"next"),error:__name(err=>observer.next(err),"error"),complete:__name(()=>observer.complete(),"complete")}),"handler"),teardown=__name(()=>{ongoingHandlers.delete(handler),core.remove(handlers,handler),tick()},"teardown");return handlers.push(handler),tick(),teardown})},"ThresholdInterceptorFactory"),AuthInterceptorFactory=__name(params=>{const{errorStatusCodes,onAuthError}=params;return __name((request,next)=>next(request).pipe(rxjs.catchError(error=>(error instanceof HTTPResponseError&&errorStatusCodes.some(c=>c===error.status)&&onAuthError(),rxjs.throwError(()=>error)))),"authInterceptor")},"AuthInterceptorFactory"),createDefaultFetchCheck=__name((time=300)=>{let cancel=__name(()=>{},"noop");return _currentConfig=>new Promise(res=>{cancel();const t=setTimeout(()=>{res(!0)},time);cancel=__name(()=>{clearTimeout(t),res(!1)},"cancel")})},"createDefaultFetchCheck"),createDistributeResult=__name(()=>(result,list)=>list.map(config=>({config,result})),"createDistributeResult"),MergeInterceptorFactory=__name((config,options={})=>{const{isMatch,getParamsFromRequest,mergeParamsToRequest}=config,{fetchCheck=createDefaultFetchCheck(300),distributeResult=createDistributeResult()}=options,hookList=[],getPlainList=__name(_list=>_list.map(item=>item.config),"getPlainList");return(requestConfig,next)=>isMatch(requestConfig)?new rxjs.Observable(observer=>{const params=getParamsFromRequest(requestConfig);hookList.push({next:__name(v=>observer.next(v),"next"),error:__name(error=>observer.error(error),"error"),config:params});const list=getPlainList(hookList);fetchCheck(requestConfig).then(isFetch=>{if(isFetch){const currentHookList=[];list.forEach(config2=>{const index=hookList.findIndex(item=>item.config===config2);if(index>=0){const[hook]=hookList.splice(index,1);currentHookList.push(hook)}}),next(mergeParamsToRequest(list,requestConfig)).subscribe({next:__name(e=>{if(e.type===HTTPEventType.Response){const body=e.body,configList=distributeResult(body,list);currentHookList.forEach(hookItem=>{const res=configList.find(item=>item.config===hookItem.config);if(res){const response=new HTTPResponse({body:res.result,headers:e.headers,status:e.status,statusText:e.statusText});hookItem.next(response)}else hookItem.error("batch error")})}},"next"),complete:__name(()=>observer.complete(),"complete"),error:__name(e=>observer.error(e),"error")})}})}):next(requestConfig)},"MergeInterceptorFactory");exports2.AuthInterceptorFactory=AuthInterceptorFactory,exports2.FetchHTTPImplementation=FetchHTTPImplementation,exports2.HTTPEventType=HTTPEventType,exports2.HTTPHeaders=HTTPHeaders,exports2.HTTPProgress=HTTPProgress,exports2.HTTPRequest=HTTPRequest,exports2.HTTPResponse=HTTPResponse,exports2.HTTPResponseError=HTTPResponseError,exports2.HTTPStatusCode=HTTPStatusCode,exports2.IHTTPImplementation=IHTTPImplementation,exports2.ISocketService=ISocketService,exports2.MergeInterceptorFactory=MergeInterceptorFactory,exports2.ResponseHeader=ResponseHeader,exports2.RetryInterceptorFactory=RetryInterceptorFactory,exports2.ThresholdInterceptorFactory=ThresholdInterceptorFactory,exports2.WebSocketService=WebSocketService,exports2.XHRHTTPImplementation=XHRHTTPImplementation,Object.defineProperty(exports2,Symbol.toStringTag,{value:"Module"})});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@univerjs/network",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.6",
|
|
4
4
|
"private": false,
|
|
5
5
|
"author": "DreamNum <developer@univer.ai>",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -45,18 +45,16 @@
|
|
|
45
45
|
"lib"
|
|
46
46
|
],
|
|
47
47
|
"peerDependencies": {
|
|
48
|
-
"@wendellhu/redi": "0.16.0",
|
|
49
48
|
"rxjs": ">=7.0.0",
|
|
50
|
-
"@univerjs/core": "0.2.
|
|
49
|
+
"@univerjs/core": "0.2.6"
|
|
51
50
|
},
|
|
52
51
|
"devDependencies": {
|
|
53
|
-
"@wendellhu/redi": "0.16.0",
|
|
54
52
|
"rxjs": "^7.8.1",
|
|
55
|
-
"typescript": "^5.5.
|
|
56
|
-
"vite": "^5.3.
|
|
57
|
-
"vitest": "^2.0.
|
|
58
|
-
"@univerjs/core": "0.2.
|
|
59
|
-
"@univerjs/shared": "0.2.
|
|
53
|
+
"typescript": "^5.5.4",
|
|
54
|
+
"vite": "^5.3.5",
|
|
55
|
+
"vitest": "^2.0.4",
|
|
56
|
+
"@univerjs/core": "0.2.6",
|
|
57
|
+
"@univerjs/shared": "0.2.6"
|
|
60
58
|
},
|
|
61
59
|
"univerSpace": {
|
|
62
60
|
".": {
|