@univerjs/network 0.4.2 → 0.5.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/cjs/index.js +2 -2
- package/lib/es/index.js +414 -434
- package/lib/umd/index.js +2 -2
- package/package.json +11 -10
package/lib/umd/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(
|
|
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,_b2;const params=(_b2=(_a2=this.requestParams)==null?void 0:_a2.params)==null?void 0:_b2.toString();return params?`${this.url}${this.url.includes("?")?"&":"?"}${params}`:this.url}getBody(){var _a2,_b2;const contentType=(_a2=this.headers.get("Content-Type"))!=null?_a2:ApplicationJSONType,body=(_b2=this.requestParams)==null?void 0:_b2.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 __defProp$1=Object.defineProperty,__getOwnPropDesc$1=Object.getOwnPropertyDescriptor,__decorateClass$1=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$1(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&&__defProp$1(target,key,result),result},"__decorateClass$1"),__decorateParam$1=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$1");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,_b2;return((_a2=a.priority)!=null?_a2:0)-((_b2=b.priority)!=null?_b2: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,_b2;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:(_b2=options==null?void 0:options.responseType)!=null?_b2:"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,_b2;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:(_b2=options==null?void 0:options.responseType)!=null?_b2:"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$1([__decorateParam$1(0,IHTTPImplementation)],exports2.HTTPService);function chainInterceptorFn(afterInterceptorChain,currentInterceptorFn){return(prevRequest,nextHandlerFn)=>currentInterceptorFn(prevRequest,nextRequest=>afterInterceptorChain(nextRequest,nextHandlerFn))}__name(chainInterceptorFn,"chainInterceptorFn");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||{}),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 _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;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.UniverNetworkPlugin=(_b=class extends core.Plugin{constructor(_config=void 0,_injector){super(),this._config=_config,this._injector=_injector}onStarting(){var _a2;core.registerDependencies(this._injector,core.mergeOverrideWithDependencies([[exports2.HTTPService],[IHTTPImplementation,{useClass:XHRHTTPImplementation}]],(_a2=this._config)==null?void 0:_a2.override))}},__name(_b,"UniverNetworkPlugin"),__publicField(_b,"pluginName","UNIVER_NETWORK_PLUGIN"),_b),exports2.UniverNetworkPlugin=__decorateClass([__decorateParam(1,core.Inject(core.Injector))],exports2.UniverNetworkPlugin);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,_b2;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:(_b2=error.statusText)!=null?_b2:"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,_b2;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=(_b2=response.headers.get("content-type"))!=null?_b2:"";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 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(params=>{var _a2,_b2;const maxRetryAttempts=(_a2=params==null?void 0:params.maxRetryAttempts)!=null?_a2:DEFAULT_MAX_RETRY_ATTEMPTS,delayInterval=(_b2=params==null?void 0:params.delayInterval)!=null?_b2: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.error(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"})});
|
|
1
|
+
(function(a,l){typeof exports=="object"&&typeof module<"u"?l(exports,require("@univerjs/core"),require("rxjs"),require("rxjs/operators")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","rxjs","rxjs/operators"],l):(a=typeof globalThis<"u"?globalThis:a||self,l(a.UniverNetwork={},a.UniverCore,a.rxjs,a.rxjs.operators))})(this,function(a,l,y,R){"use strict";var pe=Object.defineProperty;var ue=(a,l,y)=>l in a?pe(a,l,{enumerable:!0,configurable:!0,writable:!0,value:y}):a[l]=y;var g=(a,l,y)=>ue(a,typeof l!="symbol"?l+"":l,y);var q;const x="application/json";class E{constructor(n){g(this,"_headers",new Map);typeof n=="string"?this._handleHeadersString(n):n instanceof Headers?this._handleHeaders(n):n&&this._handleHeadersConstructorProps(n)}forEach(n){this._headers.forEach((r,t)=>n(t,r))}has(n){return!!this._headers.has(n.toLowerCase())}get(n){const r=n.toLowerCase();return this._headers.has(r)?this._headers.get(r):null}set(n,r){this._setHeader(n,r)}toHeadersInit(){var r,t;const n={};return this._headers.forEach((s,o)=>{n[o]=s.join(",")}),(r=n.accept)!=null||(n.accept="application/json, text/plain, */*"),(t=n["content-type"])!=null||(n["content-type"]="application/json;charset=UTF-8"),n}_setHeader(n,r){const t=n.toLowerCase();this._headers.has(t)?this._headers.get(t).push(r.toString()):this._headers.set(t,[r.toString()])}_handleHeadersString(n){n.split(`
|
|
2
|
+
`).forEach(r=>{const[t,s]=r.split(":");t&&s&&this._setHeader(t,s)})}_handleHeadersConstructorProps(n){Object.entries(n).forEach(([r,t])=>this._setHeader(r,t))}_handleHeaders(n){n.forEach((r,t)=>this._setHeader(t,r))}}const A=l.createIdentifier("network.http-implementation");class M{constructor(n){this.params=n}toString(){return this.params?Object.keys(this.params).map(n=>`${n}=${this.params[n]}`).join("&"):""}}let W=0;class U{constructor(n,r,t){g(this,"uid",W++);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:x,r=(s=this.requestParams)==null?void 0:s.body;return n===x&&r&&typeof r=="object"?JSON.stringify(r):r?`${r}`:null}getHeadersInit(){return this.headers.toHeadersInit()}}var V=Object.defineProperty,X=Object.getOwnPropertyDescriptor,z=(e,n,r,t)=>{for(var s=t>1?void 0:t?X(n,r):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(t?i(n,r,s):i(s))||s);return t&&s&&V(n,r,s),s},J=(e,n)=>(r,t)=>n(r,t,e);a.HTTPService=class extends l.Disposable{constructor(r){super();g(this,"_interceptors",[]);g(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,l.toDisposable(()=>l.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,h;const o=new E(s==null?void 0:s.headers),i=new M(s==null?void 0:s.params),c=new U(r,t,{headers:o,params:i,withCredentials:(p=s==null?void 0:s.withCredentials)!=null?p:!1,reportProgress:!0,responseType:(h=s==null?void 0:s.responseType)!=null?h:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body});return y.of(c).pipe(R.concatMap(d=>this._runInterceptorsAndImplementation(d)))}async _request(r,t,s){var d,f;const o=new E(s==null?void 0:s.headers),i=new M(s==null?void 0:s.params),c=new U(r,t,{headers:o,params:i,withCredentials:(d=s==null?void 0:s.withCredentials)!=null?d:!1,responseType:(f=s==null?void 0:s.responseType)!=null?f:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body}),p=y.of(c).pipe(R.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)=>K(t,s),(t,s)=>s(t))),this._pipe(r,t=>this._http.send(t))}},a.HTTPService=z([J(0,A)],a.HTTPService);function K(e,n){return(r,t)=>n(r,s=>e(s,t))}const Y=200,Q=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||{}),O=(e=>(e[e.DownloadProgress=0]="DownloadProgress",e[e.Response=1]="Response",e))(O||{});class N{constructor({body:n,headers:r,status:t,statusText:s}){g(this,"type",1);g(this,"body");g(this,"headers");g(this,"status");g(this,"statusText");this.body=n,this.headers=r,this.status=t,this.statusText=s}}class j{constructor(n,r,t){g(this,"type",0);this.total=n,this.loaded=r,this.partialText=t}}class ${constructor(n,r,t){this.headers=n,this.status=r,this.statusText=t}}class b{constructor({headers:n,status:r,statusText:t,error:s}){g(this,"headers");g(this,"status");g(this,"statusText");g(this,"error");this.headers=n,this.status=r,this.statusText=t,this.error=s}}class B{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,h)=>t.setRequestHeader(p,h.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",h=new E(t.getAllResponseHeaders());return new $(h,t.status,p)},o=()=>{const{headers:p,statusText:h,status:d}=s(),{responseType:f}=n;let u=null,v=null;d!==I.NoContent&&(u=typeof t.response>"u"?t.responseText:t.response);let w=d>=Y&&d<Q;if(f==="json"&&typeof u=="string"){const _=u;try{u=u?JSON.parse(u):null}catch(m){w=!1,u=_,v=m}}w?r.next(new N({body:u,headers:p,status:d,statusText:h})):r.error(new b({error:v,headers:p,status:d,statusText:h}))},i=p=>{const h=new b({error:p,status:t.status||0,statusText:t.statusText||"Unknown Error",headers:s().headers});r.error(h)};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)}})}}var Z=Object.defineProperty,P=Object.getOwnPropertyDescriptor,H=(e,n,r,t)=>{for(var s=t>1?void 0:t?P(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&&Z(n,r,s),s},S=(e,n)=>(r,t)=>n(r,t,e);a.UniverNetworkPlugin=(q=class extends l.Plugin{constructor(n=void 0,r){super(),this._config=n,this._injector=r}onStarting(){var n;l.registerDependencies(this._injector,l.mergeOverrideWithDependencies([[a.HTTPService],[A,{useClass:B}]],(n=this._config)==null?void 0:n.override))}},g(q,"pluginName","UNIVER_NETWORK_PLUGIN"),q),a.UniverNetworkPlugin=H([S(1,l.Inject(l.Injector))],a.UniverNetworkPlugin);class C{send(n){return new y.Observable(r=>{const t=new AbortController;return this._send(n,r,t).then(()=>{},s=>{r.error(new b({error:s}))}),()=>t.abort()})}async _send(n,r,t){var d,f;let s;try{const u=this._parseFetchParamsFromRequest(n);s=await fetch(n.getUrlWithParams(),{signal:t.signal,...u})}catch(u){r.error(new b({error:u,status:(d=u.status)!=null?d:0,statusText:(f=u.statusText)!=null?f:"Unknown Error",headers:u.headers}));return}const o=new E(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 N({body:p,headers:o,status:i,statusText:c})):r.error(new b({error:p,status:i,statusText:c,headers:o})),r.complete()}async _readBody(n,r,t){var v,w;const s=[],o=r.body.getReader(),i=r.headers.get("content-length");let c=0;const p=(v=n.requestParams)==null?void 0:v.reportProgress,h=n.responseType;let d,f;for(;;){const{done:_,value:m}=await o.read();if(_)break;s.push(m),c+=m.length,p&&h==="text"&&(d=(d!=null?d:"")+(f!=null?f:f=new TextDecoder).decode(m,{stream:!0}),t.next(new j(i?Number.parseInt(i,10):void 0,c,d)))}const u=T(s,c);try{const _=(w=r.headers.get("content-type"))!=null?w:"";return re(n,u,_)}catch(_){return t.error(new b({error:_,status:r.status,statusText:r.statusText,headers:new E(r.headers)})),null}}_parseFetchParamsFromRequest(n){return{method:n.method,headers:n.getHeadersInit(),body:n.getBody(),credentials:n.withCredentials?"include":void 0}}}function T(e,n){const r=new Uint8Array(n);let t=0;for(const s of e)r.set(s,t),t+=s.length;return r}const ee=/^\)\]\}',?\n/;function re(e,n,r){switch(e.responseType){case"json":const t=new TextDecoder().decode(n).replace(ee,"");return t===""?null:JSON.parse(t);case"text":return new TextDecoder().decode(n);case"blob":return new Blob([n],{type:r});case"arraybuffer":return n.buffer;default:throw new Error(`[FetchHTTPImplementation]: unknown response type: ${e.responseType}.`)}}const te=l.createIdentifier("univer.socket");class ne extends l.Disposable{createSocket(n){try{const r=new WebSocket(n),t=new l.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(l.toDisposable(()=>r.removeEventListener("open",i)))}).pipe(R.share()),close$:new y.Observable(o=>{const i=c=>o.next(c);r.addEventListener("close",i),t.add(l.toDisposable(()=>r.removeEventListener("close",i)))}).pipe(R.share()),error$:new y.Observable(o=>{const i=c=>o.next(c);r.addEventListener("error",i),t.add(l.toDisposable(()=>r.removeEventListener("error",i)))}).pipe(R.share()),message$:new y.Observable(o=>{const i=c=>o.next(c);r.addEventListener("message",i),t.add(l.toDisposable(()=>r.removeEventListener("message",i)))}).pipe(R.share())}}catch(r){return console.error(r),null}}}const se=3,ie=1e3,oe=e=>{var t,s;const n=(t=e==null?void 0:e.maxRetryAttempts)!=null?t:se,r=(s=e==null?void 0:e.delayInterval)!=null?s:ie;return(o,i)=>i(o).pipe(R.retry({delay:r,count:n}))},ae=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:h=>i.next(h),error:h=>i.error(h),complete:()=>i.complete()}),p=()=>{r.delete(c),l.remove(n,c),t()};return n.push(c),t(),p})},ce=e=>{const{errorStatusCodes:n,onAuthError:r}=e;return(s,o)=>o(s).pipe(y.catchError(i=>(i instanceof b&&n.some(c=>c===i.status)&&r(),y.throwError(()=>i))))},le=(e=300)=>{let r=()=>{};return t=>new Promise(s=>{r();const o=setTimeout(()=>{s(!0)},e);r=()=>{clearTimeout(o),s(!1)}})},he=()=>(e,n)=>n.map(r=>({config:r,result:e})),de=(e,n={})=>{const{isMatch:r,getParamsFromRequest:t,mergeParamsToRequest:s}=e,{fetchCheck:o=le(300),distributeResult:i=he()}=n,c=[],p=h=>h.map(d=>d.config);return(h,d)=>r(h)?new y.Observable(f=>{const u=t(h);c.push({next:w=>f.next(w),error:w=>f.error(w),config:u});const v=p(c);o(h).then(w=>{if(w){const _=[];v.forEach(m=>{const F=c.findIndex(L=>L.config===m);if(F>=0){const[L]=c.splice(F,1);_.push(L)}}),d(s(v,h)).subscribe({next:m=>{if(m.type===O.Response){const F=m.body,L=i(F,v);_.forEach(D=>{const G=L.find(k=>k.config===D.config);if(G){const k=new N({body:G.result,headers:m.headers,status:m.status,statusText:m.statusText});D.next(k)}else D.error("batch error")})}},complete:()=>f.complete(),error:m=>f.error(m)})}})}):d(h)};a.AuthInterceptorFactory=ce,a.FetchHTTPImplementation=C,a.HTTPEventType=O,a.HTTPHeaders=E,a.HTTPProgress=j,a.HTTPRequest=U,a.HTTPResponse=N,a.HTTPResponseError=b,a.HTTPStatusCode=I,a.IHTTPImplementation=A,a.ISocketService=te,a.MergeInterceptorFactory=de,a.ResponseHeader=$,a.RetryInterceptorFactory=oe,a.ThresholdInterceptorFactory=ae,a.WebSocketService=ne,a.XHRHTTPImplementation=B,Object.defineProperty(a,Symbol.toStringTag,{value:"Module"})});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@univerjs/network",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0-alpha.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"author": "DreamNum <developer@univer.ai>",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -32,8 +32,7 @@
|
|
|
32
32
|
},
|
|
33
33
|
"./lib/*": "./lib/*"
|
|
34
34
|
},
|
|
35
|
-
"main": "./lib/
|
|
36
|
-
"module": "./lib/es/index.js",
|
|
35
|
+
"main": "./lib/es/index.js",
|
|
37
36
|
"types": "./lib/types/index.d.ts",
|
|
38
37
|
"publishConfig": {
|
|
39
38
|
"access": "public"
|
|
@@ -48,16 +47,17 @@
|
|
|
48
47
|
"rxjs": ">=7.0.0"
|
|
49
48
|
},
|
|
50
49
|
"dependencies": {
|
|
51
|
-
"@
|
|
50
|
+
"@vitejs/plugin-react": "4.3.3",
|
|
51
|
+
"@univerjs/core": "0.5.0-alpha.0"
|
|
52
52
|
},
|
|
53
53
|
"devDependencies": {
|
|
54
54
|
"rxjs": "^7.8.1",
|
|
55
55
|
"typescript": "^5.6.3",
|
|
56
|
-
"vite": "^5.4.
|
|
57
|
-
"vitest": "^2.1.
|
|
58
|
-
"@univerjs-infra/shared": "0.
|
|
56
|
+
"vite": "^5.4.10",
|
|
57
|
+
"vitest": "^2.1.4",
|
|
58
|
+
"@univerjs-infra/shared": "0.5.0-alpha.0"
|
|
59
59
|
},
|
|
60
|
-
"
|
|
60
|
+
"space": {
|
|
61
61
|
".": {
|
|
62
62
|
"import": "./lib/es/index.js",
|
|
63
63
|
"require": "./lib/cjs/index.js",
|
|
@@ -75,6 +75,7 @@
|
|
|
75
75
|
"test:watch": "vitest",
|
|
76
76
|
"coverage": "vitest run --coverage",
|
|
77
77
|
"lint:types": "tsc --noEmit",
|
|
78
|
-
"build": "
|
|
79
|
-
}
|
|
78
|
+
"build": "tsx build.ts"
|
|
79
|
+
},
|
|
80
|
+
"module": "./lib/es/index.js"
|
|
80
81
|
}
|