@univerjs/network 0.2.5 → 0.2.7
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 -393
- package/lib/umd/index.js +2 -2
- package/package.json +7 -7
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 O=f.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 G=0;class q{constructor(t,r,n){y(this,"uid",G++);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 V=Object.defineProperty,W=Object.getOwnPropertyDescriptor,X=(e,t,r,n)=>{for(var s=n>1?void 0:n?W(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&&V(t,r,s),s},z=(e,t)=>(r,n)=>t(r,n,e);exports.HTTPService=class extends f.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,f.toDisposable(()=>f.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,d;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:(d=s==null?void 0:s.responseType)!=null?d:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body}),h=m.of(i).pipe(v.concatMap(p=>this._runInterceptorsAndImplementation(p)));return await m.firstValueFrom(h)}_runInterceptorsAndImplementation(r){return this._pipe||(this._pipe=this._interceptors.map(n=>n.interceptor).reduceRight((n,s)=>J(n,s),(n,s)=>s(n))),this._pipe(r,n=>this._http.send(n))}};exports.HTTPService=X([z(0,O)],exports.HTTPService);function J(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 M{constructor(t,r,n){y(this,"type",0);this.total=t,this.loaded=r,this.partialText=n}}class j{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 Y=200,K=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 Q{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,d;let s;try{const p=this._parseFetchParamsFromRequest(t);s=await fetch(t.getUrlWithParams(),{signal:n.signal,...p})}catch(p){r.error(new R({error:p,status:(l=p.status)!=null?l:0,statusText:(d=p.statusText)!=null?d:"Unknown Error",headers:p.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 g,w;const s=[],c=r.body.getReader(),o=r.headers.get("content-length");let i=0;const h=(g=t.requestParams)==null?void 0:g.reportProgress,a=t.responseType;let l,d;for(;;){const{done:b,value:u}=await c.read();if(b)break;s.push(u),i+=u.length,h&&a==="text"&&(l=(l!=null?l:"")+(d!=null?d:d=new TextDecoder).decode(u,{stream:!0}),n.next(new M(o?Number.parseInt(o,10):void 0,i,l)))}const p=Z(s,i);try{const b=(w=r.headers.get("content-type"))!=null?w:"";return H(t,p,b)}catch(b){return n.error(new R({error:b,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 Z(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 P=/^\)\]\}',?\n/;function H(e,t,r){switch(e.responseType){case"json":const n=new TextDecoder().decode(t).replace(P,"");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 S{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 j(a,n.status,h)},c=()=>{const{headers:h,statusText:a,status:l}=s(),{responseType:d}=t;let p=null,g=null;l!==x.NoContent&&(p=typeof n.response>"u"?n.responseText:n.response);let w=l>=Y&&l<K;if(d==="json"&&typeof p=="string"){const b=p;try{p=p?JSON.parse(p):null}catch(u){w=!1,p=b,g=u}}w?r.next(new L({body:p,headers:h,status:l,statusText:a})):r.error(new R({error:g,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 C=f.createIdentifier("univer.socket");class T extends f.Disposable{createSocket(t){try{const r=new WebSocket(t),n=new f.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(f.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(f.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(f.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(f.toDisposable(()=>r.removeEventListener("message",o)))}).pipe(v.share())}}catch(r){return console.error(r),null}}}const ee=3,re=1e3,te=(e,t)=>{var s,c;const r=(s=t==null?void 0:t.maxRetryAttempts)!=null?s:ee,n=(c=t==null?void 0:t.delayInterval)!=null?c:re;return(o,i)=>i(o).pipe(v.retry({delay:n,count:r}))},ne=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),f.remove(t,i),n()};return t.push(i),n(),h})},se=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))))},oe=(e=300)=>{let r=()=>{};return n=>new Promise(s=>{r();const c=setTimeout(()=>{s(!0)},e);r=()=>{clearTimeout(c),s(!1)}})},ce=()=>(e,t)=>t.map(r=>({config:r,result:e})),ie=(e,t={})=>{const{isMatch:r,getParamsFromRequest:n,mergeParamsToRequest:s}=e,{fetchCheck:c=oe(300),distributeResult:o=ce()}=t,i=[],h=a=>a.map(l=>l.config);return(a,l)=>r(a)?new m.Observable(d=>{const p=n(a);i.push({next:w=>d.next(w),error:w=>d.error(w),config:p});const g=h(i);c(a).then(w=>{if(w){const b=[];g.forEach(u=>{const I=i.findIndex(_=>_.config===u);if(I>=0){const[_]=i.splice(I,1);b.push(_)}}),l(s(g,a)).subscribe({next:u=>{if(u.type===N.Response){const I=u.body,_=o(I,g);b.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:()=>d.complete(),error:u=>d.error(u)})}})}):l(a)};exports.AuthInterceptorFactory=se;exports.FetchHTTPImplementation=Q;exports.HTTPEventType=N;exports.HTTPHeaders=E;exports.HTTPProgress=M;exports.HTTPRequest=q;exports.HTTPResponse=L;exports.HTTPResponseError=R;exports.HTTPStatusCode=x;exports.IHTTPImplementation=O;exports.ISocketService=C;exports.MergeInterceptorFactory=ie;exports.ResponseHeader=j;exports.RetryInterceptorFactory=te;exports.ThresholdInterceptorFactory=ne;exports.WebSocketService=T;exports.XHRHTTPImplementation=S;
|
|
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,64 +1,66 @@
|
|
|
1
|
-
var
|
|
2
|
-
var
|
|
3
|
-
var
|
|
4
|
-
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
|
|
8
|
-
class
|
|
9
|
-
constructor(
|
|
10
|
-
|
|
11
|
-
typeof
|
|
12
|
-
}
|
|
13
|
-
forEach(
|
|
14
|
-
this._headers.forEach((
|
|
15
|
-
}
|
|
16
|
-
has(
|
|
17
|
-
return !!this._headers.has(
|
|
18
|
-
}
|
|
19
|
-
get(
|
|
20
|
-
const
|
|
21
|
-
return this._headers.has(
|
|
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;
|
|
22
22
|
}
|
|
23
23
|
toHeadersInit() {
|
|
24
|
-
var
|
|
25
|
-
const
|
|
26
|
-
return this._headers.forEach((
|
|
27
|
-
|
|
28
|
-
}), (
|
|
29
|
-
}
|
|
30
|
-
_setHeader(
|
|
31
|
-
const
|
|
32
|
-
this._headers.has(
|
|
33
|
-
}
|
|
34
|
-
_handleHeadersString(
|
|
35
|
-
|
|
36
|
-
`).forEach((
|
|
37
|
-
const [
|
|
38
|
-
|
|
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);
|
|
39
39
|
});
|
|
40
40
|
}
|
|
41
|
-
_handleHeadersConstructorProps(
|
|
42
|
-
Object.entries(
|
|
41
|
+
_handleHeadersConstructorProps(headers) {
|
|
42
|
+
Object.entries(headers).forEach(([name, value]) => this._setHeader(name, value));
|
|
43
43
|
}
|
|
44
|
-
_handleHeaders(
|
|
45
|
-
|
|
44
|
+
_handleHeaders(headers) {
|
|
45
|
+
headers.forEach((value, name) => this._setHeader(name, value));
|
|
46
46
|
}
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
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;
|
|
52
53
|
}
|
|
53
54
|
toString() {
|
|
54
|
-
return this.params ? Object.keys(this.params).map((
|
|
55
|
+
return this.params ? Object.keys(this.params).map((key) => `${key}=${this.params[key]}`).join("&") : "";
|
|
55
56
|
}
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
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;
|
|
62
64
|
}
|
|
63
65
|
get headers() {
|
|
64
66
|
return this.requestParams.headers;
|
|
@@ -70,31 +72,33 @@ class D {
|
|
|
70
72
|
return this.requestParams.responseType;
|
|
71
73
|
}
|
|
72
74
|
getUrlWithParams() {
|
|
73
|
-
var
|
|
74
|
-
const
|
|
75
|
-
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;
|
|
76
78
|
}
|
|
77
79
|
getBody() {
|
|
78
|
-
var
|
|
79
|
-
const
|
|
80
|
-
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;
|
|
81
83
|
}
|
|
82
84
|
getHeadersInit() {
|
|
83
85
|
return this.headers.toHeadersInit();
|
|
84
86
|
}
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
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) {
|
|
93
97
|
super();
|
|
94
|
-
|
|
98
|
+
__publicField(this, "_interceptors", []);
|
|
95
99
|
// eslint-disable-next-line ts/no-explicit-any
|
|
96
|
-
|
|
97
|
-
this._http =
|
|
100
|
+
__publicField(this, "_pipe");
|
|
101
|
+
this._http = _http;
|
|
98
102
|
}
|
|
99
103
|
/**
|
|
100
104
|
* Register an HTTP interceptor.
|
|
@@ -102,410 +106,426 @@ let O = class extends B {
|
|
|
102
106
|
* @param interceptor the http interceptor
|
|
103
107
|
* @returns a disposable handler to remove the interceptor
|
|
104
108
|
*/
|
|
105
|
-
registerHTTPInterceptor(
|
|
106
|
-
if (this._interceptors.indexOf(
|
|
109
|
+
registerHTTPInterceptor(interceptor) {
|
|
110
|
+
if (this._interceptors.indexOf(interceptor) !== -1)
|
|
107
111
|
throw new Error("[HTTPService]: The interceptor has already been registered!");
|
|
108
|
-
return this._interceptors.push(
|
|
109
|
-
var
|
|
110
|
-
return ((
|
|
111
|
-
}), 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));
|
|
112
116
|
}
|
|
113
|
-
get(
|
|
114
|
-
return this._request("GET",
|
|
117
|
+
get(url, params) {
|
|
118
|
+
return this._request("GET", url, params);
|
|
115
119
|
}
|
|
116
|
-
post(
|
|
117
|
-
return this._request("POST",
|
|
120
|
+
post(url, params) {
|
|
121
|
+
return this._request("POST", url, params);
|
|
118
122
|
}
|
|
119
|
-
put(
|
|
120
|
-
return this._request("PUT",
|
|
123
|
+
put(url, params) {
|
|
124
|
+
return this._request("PUT", url, params);
|
|
121
125
|
}
|
|
122
|
-
delete(
|
|
123
|
-
return this._request("DELETE",
|
|
126
|
+
delete(url, params) {
|
|
127
|
+
return this._request("DELETE", url, params);
|
|
124
128
|
}
|
|
125
|
-
patch(
|
|
126
|
-
return this._request("PATCH",
|
|
129
|
+
patch(url, options) {
|
|
130
|
+
return this._request("PATCH", url, options);
|
|
127
131
|
}
|
|
128
|
-
getSSE(
|
|
129
|
-
var
|
|
130
|
-
const
|
|
131
|
-
headers
|
|
132
|
-
params
|
|
133
|
-
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,
|
|
134
138
|
reportProgress: !0,
|
|
135
|
-
responseType: (
|
|
136
|
-
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
|
|
137
141
|
});
|
|
138
|
-
return
|
|
142
|
+
return of(request).pipe(concatMap((request2) => this._runInterceptorsAndImplementation(request2)));
|
|
139
143
|
}
|
|
140
144
|
/** The HTTP request implementations */
|
|
141
|
-
async _request(
|
|
142
|
-
var
|
|
143
|
-
const
|
|
144
|
-
headers
|
|
145
|
-
params
|
|
146
|
-
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,
|
|
147
151
|
// default value for withCredentials is false by MDN
|
|
148
|
-
responseType: (
|
|
149
|
-
body: ["GET", "DELETE"].includes(
|
|
150
|
-
}),
|
|
151
|
-
|
|
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))
|
|
152
156
|
);
|
|
153
|
-
return await
|
|
157
|
+
return await firstValueFrom(events$);
|
|
154
158
|
}
|
|
155
159
|
// eslint-disable-next-line ts/no-explicit-any
|
|
156
|
-
_runInterceptorsAndImplementation(
|
|
157
|
-
return this._pipe || (this._pipe = this._interceptors.map((
|
|
158
|
-
(
|
|
159
|
-
(
|
|
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)
|
|
160
164
|
)), this._pipe(
|
|
161
|
-
|
|
162
|
-
(
|
|
165
|
+
request,
|
|
166
|
+
(requestToNext) => this._http.send(requestToNext)
|
|
163
167
|
/* final handler */
|
|
164
168
|
);
|
|
165
169
|
}
|
|
166
|
-
};
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
],
|
|
170
|
-
function
|
|
171
|
-
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));
|
|
172
176
|
}
|
|
173
|
-
|
|
174
|
-
|
|
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 {
|
|
175
180
|
constructor({
|
|
176
|
-
body
|
|
177
|
-
headers
|
|
178
|
-
status
|
|
179
|
-
statusText
|
|
181
|
+
body,
|
|
182
|
+
headers,
|
|
183
|
+
status,
|
|
184
|
+
statusText
|
|
180
185
|
}) {
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
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;
|
|
187
192
|
}
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
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;
|
|
193
200
|
}
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
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;
|
|
198
207
|
}
|
|
199
|
-
}
|
|
200
|
-
|
|
208
|
+
};
|
|
209
|
+
__name(_ResponseHeader, "ResponseHeader");
|
|
210
|
+
let ResponseHeader = _ResponseHeader;
|
|
211
|
+
const _HTTPResponseError = class _HTTPResponseError {
|
|
201
212
|
constructor({
|
|
202
|
-
headers
|
|
203
|
-
status
|
|
204
|
-
statusText
|
|
205
|
-
error
|
|
213
|
+
headers,
|
|
214
|
+
status,
|
|
215
|
+
statusText,
|
|
216
|
+
error
|
|
206
217
|
}) {
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
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;
|
|
212
223
|
}
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
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
|
|
224
237
|
}));
|
|
225
|
-
}), () =>
|
|
238
|
+
}), () => abortController.abort();
|
|
226
239
|
});
|
|
227
240
|
}
|
|
228
|
-
async _send(
|
|
229
|
-
var
|
|
230
|
-
let
|
|
241
|
+
async _send(request, subscriber, abortController) {
|
|
242
|
+
var _a2, _b;
|
|
243
|
+
let response;
|
|
231
244
|
try {
|
|
232
|
-
const
|
|
233
|
-
|
|
234
|
-
signal:
|
|
235
|
-
...
|
|
245
|
+
const fetchParams = this._parseFetchParamsFromRequest(request);
|
|
246
|
+
response = await fetch(request.getUrlWithParams(), {
|
|
247
|
+
signal: abortController.signal,
|
|
248
|
+
...fetchParams
|
|
236
249
|
});
|
|
237
|
-
} catch (
|
|
238
|
-
|
|
239
|
-
error
|
|
240
|
-
status: (
|
|
241
|
-
statusText: (
|
|
242
|
-
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
|
|
243
256
|
}));
|
|
244
257
|
return;
|
|
245
258
|
}
|
|
246
|
-
const
|
|
247
|
-
let
|
|
248
|
-
|
|
249
|
-
body
|
|
250
|
-
headers:
|
|
251
|
-
status
|
|
252
|
-
statusText
|
|
253
|
-
})) :
|
|
254
|
-
error:
|
|
255
|
-
status
|
|
256
|
-
statusText
|
|
257
|
-
headers:
|
|
258
|
-
})),
|
|
259
|
-
}
|
|
260
|
-
async _readBody(
|
|
261
|
-
var
|
|
262
|
-
const
|
|
263
|
-
let
|
|
264
|
-
const
|
|
265
|
-
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;
|
|
266
279
|
for (; ; ) {
|
|
267
|
-
const { done
|
|
268
|
-
if (
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
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
|
|
273
286
|
)));
|
|
274
287
|
}
|
|
275
|
-
const
|
|
288
|
+
const all = mergeChunks(chunks, receivedLength);
|
|
276
289
|
try {
|
|
277
|
-
const
|
|
278
|
-
return
|
|
279
|
-
} catch (
|
|
280
|
-
return
|
|
281
|
-
error
|
|
282
|
-
status:
|
|
283
|
-
statusText:
|
|
284
|
-
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)
|
|
285
298
|
})), null;
|
|
286
299
|
}
|
|
287
300
|
}
|
|
288
|
-
_parseFetchParamsFromRequest(
|
|
301
|
+
_parseFetchParamsFromRequest(request) {
|
|
289
302
|
return {
|
|
290
|
-
method:
|
|
291
|
-
headers:
|
|
292
|
-
body:
|
|
293
|
-
credentials:
|
|
303
|
+
method: request.method,
|
|
304
|
+
headers: request.getHeadersInit(),
|
|
305
|
+
body: request.getBody(),
|
|
306
|
+
credentials: request.withCredentials ? "include" : void 0
|
|
294
307
|
};
|
|
295
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;
|
|
296
318
|
}
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
n.set(s, t), t += s.length;
|
|
302
|
-
return n;
|
|
303
|
-
}
|
|
304
|
-
const oe = /^\)\]\}',?\n/;
|
|
305
|
-
function ie(e, r, n) {
|
|
306
|
-
switch (e.responseType) {
|
|
319
|
+
__name(mergeChunks, "mergeChunks");
|
|
320
|
+
const XSSI_PREFIX = /^\)\]\}',?\n/;
|
|
321
|
+
function deserialize(request, bin, contentType) {
|
|
322
|
+
switch (request.responseType) {
|
|
307
323
|
case "json":
|
|
308
|
-
const
|
|
309
|
-
return
|
|
324
|
+
const text = new TextDecoder().decode(bin).replace(XSSI_PREFIX, "");
|
|
325
|
+
return text === "" ? null : JSON.parse(text);
|
|
310
326
|
case "text":
|
|
311
|
-
return new TextDecoder().decode(
|
|
327
|
+
return new TextDecoder().decode(bin);
|
|
312
328
|
case "blob":
|
|
313
|
-
return new Blob([
|
|
329
|
+
return new Blob([bin], { type: contentType });
|
|
314
330
|
case "arraybuffer":
|
|
315
|
-
return
|
|
331
|
+
return bin.buffer;
|
|
316
332
|
default:
|
|
317
|
-
throw new Error(`[FetchHTTPImplementation]: unknown response type: ${
|
|
333
|
+
throw new Error(`[FetchHTTPImplementation]: unknown response type: ${request.responseType}.`);
|
|
318
334
|
}
|
|
319
335
|
}
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
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;
|
|
335
352
|
try {
|
|
336
|
-
|
|
337
|
-
} catch (
|
|
338
|
-
|
|
353
|
+
body2 = body2 ? JSON.parse(body2) : null;
|
|
354
|
+
} catch (e) {
|
|
355
|
+
success = !1, body2 = originalBody, error = e;
|
|
339
356
|
}
|
|
340
357
|
}
|
|
341
|
-
|
|
342
|
-
new
|
|
343
|
-
body:
|
|
344
|
-
headers
|
|
345
|
-
status
|
|
346
|
-
statusText
|
|
358
|
+
success ? observer.next(
|
|
359
|
+
new HTTPResponse({
|
|
360
|
+
body: body2,
|
|
361
|
+
headers,
|
|
362
|
+
status,
|
|
363
|
+
statusText
|
|
347
364
|
})
|
|
348
|
-
) :
|
|
349
|
-
new
|
|
350
|
-
error
|
|
351
|
-
headers
|
|
352
|
-
status
|
|
353
|
-
statusText
|
|
365
|
+
) : observer.error(
|
|
366
|
+
new HTTPResponseError({
|
|
367
|
+
error,
|
|
368
|
+
headers,
|
|
369
|
+
status,
|
|
370
|
+
statusText
|
|
354
371
|
})
|
|
355
372
|
);
|
|
356
|
-
},
|
|
357
|
-
const
|
|
358
|
-
error
|
|
359
|
-
status:
|
|
360
|
-
statusText:
|
|
361
|
-
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
|
|
362
379
|
});
|
|
363
|
-
|
|
364
|
-
};
|
|
365
|
-
|
|
366
|
-
const
|
|
367
|
-
return
|
|
368
|
-
|
|
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);
|
|
369
386
|
};
|
|
370
387
|
});
|
|
371
388
|
}
|
|
372
|
-
}
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
389
|
+
};
|
|
390
|
+
__name(_XHRHTTPImplementation, "XHRHTTPImplementation");
|
|
391
|
+
let XHRHTTPImplementation = _XHRHTTPImplementation;
|
|
392
|
+
const ISocketService = createIdentifier("univer.socket"), _WebSocketService = class _WebSocketService extends Disposable {
|
|
393
|
+
createSocket(URL) {
|
|
376
394
|
try {
|
|
377
|
-
const
|
|
395
|
+
const connection = new WebSocket(URL), disposables = new DisposableCollection();
|
|
378
396
|
return {
|
|
379
|
-
URL
|
|
380
|
-
close: (
|
|
381
|
-
|
|
382
|
-
},
|
|
383
|
-
send: (
|
|
384
|
-
|
|
385
|
-
},
|
|
386
|
-
open$: new
|
|
387
|
-
const
|
|
388
|
-
|
|
389
|
-
}).pipe(
|
|
390
|
-
close$: new
|
|
391
|
-
const
|
|
392
|
-
|
|
393
|
-
}).pipe(
|
|
394
|
-
error$: new
|
|
395
|
-
const
|
|
396
|
-
|
|
397
|
-
}).pipe(
|
|
398
|
-
message$: new
|
|
399
|
-
const
|
|
400
|
-
|
|
401
|
-
}).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())
|
|
402
420
|
};
|
|
403
|
-
} catch (
|
|
404
|
-
return console.error(
|
|
421
|
+
} catch (e) {
|
|
422
|
+
return console.error(e), null;
|
|
405
423
|
}
|
|
406
424
|
}
|
|
407
|
-
}
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
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();
|
|
418
438
|
}
|
|
419
|
-
};
|
|
420
|
-
return (
|
|
421
|
-
const
|
|
422
|
-
next: (
|
|
423
|
-
error: (
|
|
424
|
-
complete: () =>
|
|
425
|
-
}),
|
|
426
|
-
|
|
427
|
-
};
|
|
428
|
-
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;
|
|
429
449
|
});
|
|
430
|
-
},
|
|
431
|
-
const { errorStatusCodes
|
|
432
|
-
return (
|
|
433
|
-
|
|
434
|
-
);
|
|
435
|
-
},
|
|
436
|
-
let
|
|
437
|
-
};
|
|
438
|
-
return (
|
|
439
|
-
|
|
440
|
-
const
|
|
441
|
-
|
|
442
|
-
},
|
|
443
|
-
|
|
444
|
-
clearTimeout(
|
|
445
|
-
};
|
|
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");
|
|
446
466
|
});
|
|
447
|
-
},
|
|
448
|
-
const { isMatch
|
|
449
|
-
return (
|
|
450
|
-
const
|
|
451
|
-
|
|
452
|
-
next: (
|
|
453
|
-
error: (
|
|
454
|
-
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
|
|
455
475
|
});
|
|
456
|
-
const
|
|
457
|
-
|
|
458
|
-
if (
|
|
459
|
-
const
|
|
460
|
-
|
|
461
|
-
const
|
|
462
|
-
if (
|
|
463
|
-
const [
|
|
464
|
-
|
|
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);
|
|
465
485
|
}
|
|
466
|
-
}),
|
|
467
|
-
next: (
|
|
468
|
-
if (
|
|
469
|
-
const
|
|
470
|
-
|
|
471
|
-
const
|
|
472
|
-
if (
|
|
473
|
-
const
|
|
474
|
-
body:
|
|
475
|
-
headers:
|
|
476
|
-
status:
|
|
477
|
-
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
|
|
478
498
|
});
|
|
479
|
-
|
|
499
|
+
hookItem.next(response);
|
|
480
500
|
} else
|
|
481
|
-
|
|
501
|
+
hookItem.error("batch error");
|
|
482
502
|
});
|
|
483
503
|
}
|
|
484
|
-
},
|
|
485
|
-
complete: () =>
|
|
486
|
-
error: (
|
|
504
|
+
}, "next"),
|
|
505
|
+
complete: /* @__PURE__ */ __name(() => observer.complete(), "complete"),
|
|
506
|
+
error: /* @__PURE__ */ __name((e) => observer.error(e), "error")
|
|
487
507
|
});
|
|
488
508
|
}
|
|
489
509
|
});
|
|
490
|
-
}) :
|
|
491
|
-
};
|
|
510
|
+
}) : next(requestConfig);
|
|
511
|
+
}, "MergeInterceptorFactory");
|
|
492
512
|
export {
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
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
|
|
511
531
|
};
|
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 D=h.createIdentifier("network.http-implementation");class O{constructor(n){this.params=n}toString(){return this.params?Object.keys(this.params).map(n=>`${n}=${this.params[n]}`).join("&"):""}}let $=0;class x{constructor(n,r,t){w(this,"uid",$++);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:k,r=(s=this.requestParams)==null?void 0:s.body;return n===k&&r&&typeof r=="object"?JSON.stringify(r):r?`${r}`:null}getHeadersInit(){return this.headers.toHeadersInit()}}var G=Object.defineProperty,V=Object.getOwnPropertyDescriptor,W=(e,n,r,t)=>{for(var s=t>1?void 0:t?V(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&&G(n,r,s),s},X=(e,n)=>(r,t)=>n(r,t,e);a.HTTPService=class extends h.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,h.toDisposable(()=>h.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 p,l;const o=new _(s==null?void 0:s.headers),i=new O(s==null?void 0:s.params),c=new x(r,t,{headers:o,params:i,withCredentials:(p=s==null?void 0:s.withCredentials)!=null?p:!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(c).pipe(E.concatMap(d=>this._runInterceptorsAndImplementation(d)))}async _request(r,t,s){var d,m;const o=new _(s==null?void 0:s.headers),i=new O(s==null?void 0:s.params),c=new x(r,t,{headers:o,params:i,withCredentials:(d=s==null?void 0:s.withCredentials)!=null?d:!1,responseType:(m=s==null?void 0:s.responseType)!=null?m:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body}),p=y.of(c).pipe(E.concatMap(u=>this._runInterceptorsAndImplementation(u)));return await y.firstValueFrom(p)}_runInterceptorsAndImplementation(r){return this._pipe||(this._pipe=this._interceptors.map(t=>t.interceptor).reduceRight((t,s)=>z(t,s),(t,s)=>s(t))),this._pipe(r,t=>this._http.send(t))}},a.HTTPService=W([X(0,D)],a.HTTPService);function z(e,n){return(r,t)=>n(r,s=>e(s,t))}var N=(e=>(e[e.DownloadProgress=0]="DownloadProgress",e[e.Response=1]="Response",e))(N||{});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 M{constructor(n,r,t){w(this,"type",0);this.total=n,this.loaded=r,this.partialText=t}}class j{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 J=200,Y=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 K{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 d,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:(d=u.status)!=null?d:0,statusText:(m=u.statusText)!=null?m:"Unknown Error",headers:u.headers}));return}const o=new _(s.headers),i=s.status,c=s.statusText;let p=null;s.body&&(p=await this._readBody(n,s,r)),i>=I.Ok&&i<I.MultipleChoices?r.next(new F({body:p,headers:o,status:i,statusText:c})):r.error(new R({error:p,status:i,statusText:c,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 c=0;const p=(b=n.requestParams)==null?void 0:b.reportProgress,l=n.responseType;let d,m;for(;;){const{done:v,value:f}=await o.read();if(v)break;s.push(f),c+=f.length,p&&l==="text"&&(d=(d!=null?d:"")+(m!=null?m:m=new TextDecoder).decode(f,{stream:!0}),t.next(new M(i?Number.parseInt(i,10):void 0,c,d)))}const u=Q(s,c);try{const v=(g=r.headers.get("content-type"))!=null?g:"";return P(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 Q(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 Z=/^\)\]\}',?\n/;function P(e,n,r){switch(e.responseType){case"json":const t=new TextDecoder().decode(n).replace(Z,"");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 H{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((p,l)=>t.setRequestHeader(p,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 p=t.statusText||"OK",l=new _(t.getAllResponseHeaders());return new j(l,t.status,p)},o=()=>{const{headers:p,statusText:l,status:d}=s(),{responseType:m}=n;let u=null,b=null;d!==I.NoContent&&(u=typeof t.response>"u"?t.responseText:t.response);let g=d>=J&&d<Y;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:p,status:d,statusText:l})):r.error(new R({error:b,headers:p,status:d,statusText:l}))},i=p=>{const l=new R({error:p,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 c=n.getBody();return t.send(c),()=>{t.readyState!==t.DONE&&t.abort(),t.removeEventListener("load",o),t.removeEventListener("error",i),t.removeEventListener("abort",i),t.removeEventListener("timeout",i)}})}}const S=h.createIdentifier("univer.socket");class C extends h.Disposable{createSocket(n){try{const r=new WebSocket(n),t=new h.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=c=>o.next(c);r.addEventListener("open",i),t.add(h.toDisposable(()=>r.removeEventListener("open",i)))}).pipe(E.share()),close$:new y.Observable(o=>{const i=c=>o.next(c);r.addEventListener("close",i),t.add(h.toDisposable(()=>r.removeEventListener("close",i)))}).pipe(E.share()),error$:new y.Observable(o=>{const i=c=>o.next(c);r.addEventListener("error",i),t.add(h.toDisposable(()=>r.removeEventListener("error",i)))}).pipe(E.share()),message$:new y.Observable(o=>{const i=c=>o.next(c);r.addEventListener("message",i),t.add(h.toDisposable(()=>r.removeEventListener("message",i)))}).pipe(E.share())}}catch(r){return console.error(r),null}}}const T=3,ee=1e3,re=(e,n)=>{var s,o;const r=(s=n==null?void 0:n.maxRetryAttempts)!=null?s:T,t=(o=n==null?void 0:n.delayInterval)!=null?o:ee;return(i,c)=>c(i).pipe(E.retry({delay:t,count:r}))},te=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 c=()=>o(s).subscribe({next:l=>i.next(l),error:l=>i.next(l),complete:()=>i.complete()}),p=()=>{r.delete(c),h.remove(n,c),t()};return n.push(c),t(),p})},ne=e=>{const{errorStatusCodes:n,onAuthError:r}=e;return(s,o)=>o(s).pipe(y.catchError(i=>(i instanceof R&&n.some(c=>c===i.status)&&r(),y.throwError(()=>i))))},se=(e=300)=>{let r=()=>{};return t=>new Promise(s=>{r();const o=setTimeout(()=>{s(!0)},e);r=()=>{clearTimeout(o),s(!1)}})},ie=()=>(e,n)=>n.map(r=>({config:r,result:e})),oe=(e,n={})=>{const{isMatch:r,getParamsFromRequest:t,mergeParamsToRequest:s}=e,{fetchCheck:o=se(300),distributeResult:i=ie()}=n,c=[],p=l=>l.map(d=>d.config);return(l,d)=>r(l)?new y.Observable(m=>{const u=t(l);c.push({next:g=>m.next(g),error:g=>m.error(g),config:u});const b=p(c);o(l).then(g=>{if(g){const v=[];b.forEach(f=>{const A=c.findIndex(L=>L.config===f);if(A>=0){const[L]=c.splice(A,1);v.push(L)}}),d(s(b,l)).subscribe({next:f=>{if(f.type===N.Response){const A=f.body,L=i(A,b);v.forEach(q=>{const B=L.find(U=>U.config===q.config);if(B){const U=new F({body:B.result,headers:f.headers,status:f.status,statusText:f.statusText});q.next(U)}else q.error("batch error")})}},complete:()=>m.complete(),error:f=>m.error(f)})}})}):d(l)};a.AuthInterceptorFactory=ne,a.FetchHTTPImplementation=K,a.HTTPEventType=N,a.HTTPHeaders=_,a.HTTPProgress=M,a.HTTPRequest=x,a.HTTPResponse=F,a.HTTPResponseError=R,a.HTTPStatusCode=I,a.IHTTPImplementation=D,a.ISocketService=S,a.MergeInterceptorFactory=oe,a.ResponseHeader=j,a.RetryInterceptorFactory=re,a.ThresholdInterceptorFactory=te,a.WebSocketService=C,a.XHRHTTPImplementation=H,Object.defineProperty(a,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.7",
|
|
4
4
|
"private": false,
|
|
5
5
|
"author": "DreamNum <developer@univer.ai>",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -46,15 +46,15 @@
|
|
|
46
46
|
],
|
|
47
47
|
"peerDependencies": {
|
|
48
48
|
"rxjs": ">=7.0.0",
|
|
49
|
-
"@univerjs/core": "0.2.
|
|
49
|
+
"@univerjs/core": "0.2.7"
|
|
50
50
|
},
|
|
51
51
|
"devDependencies": {
|
|
52
52
|
"rxjs": "^7.8.1",
|
|
53
|
-
"typescript": "^5.5.
|
|
54
|
-
"vite": "^5.3.
|
|
55
|
-
"vitest": "^2.0.
|
|
56
|
-
"@univerjs/
|
|
57
|
-
"@univerjs/
|
|
53
|
+
"typescript": "^5.5.4",
|
|
54
|
+
"vite": "^5.3.5",
|
|
55
|
+
"vitest": "^2.0.5",
|
|
56
|
+
"@univerjs/shared": "0.2.7",
|
|
57
|
+
"@univerjs/core": "0.2.7"
|
|
58
58
|
},
|
|
59
59
|
"univerSpace": {
|
|
60
60
|
".": {
|