@univerjs/network 0.10.3-nightly.202508150623 → 0.10.4-nightly.202508220605
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/cjs/index.js +1 -1
- package/lib/es/index.js +1 -1
- package/lib/index.js +1 -1
- package/lib/umd/facade.js +1 -1
- package/lib/umd/index.js +2 -2
- package/package.json +5 -5
package/lib/cjs/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use strict";var W=Object.defineProperty;var V=(e,n,r)=>n in e?W(e,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[n]=r;var y=(e,n,r)=>V(e,typeof n!="symbol"?n+"":n,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=require("@univerjs/core"),w=require("rxjs"),_=require("rxjs/operators"),J="network.config",$={},A="application/json";function K(e){return Array.isArray(e)?e.some(n=>n.includes(A)):e.includes(A)}class E{constructor(n){y(this,"_headers",new Map);typeof n=="string"?this._handleHeadersString(n):n instanceof Headers?this._handleHeaders(n):n&&this._handleHeadersConstructorProps(n)}forEach(n){this._headers.forEach((r,t)=>n(t,r))}has(n){return!!this._headers.has(n.toLowerCase())}get(n){const r=n.toLowerCase();return this._headers.has(r)?this._headers.get(r):null}set(n,r){this._setHeader(n,r)}toHeadersInit(n){var t,s;const r={};return this._headers.forEach((o,i)=>{r[i]=o.join(",")}),(t=r.accept)!=null||(r.accept="application/json, text/plain, */*"),n instanceof FormData||(s=r["content-type"])!=null||(r["content-type"]="application/json;charset=UTF-8"),r}_setHeader(n,r){const t=n.toLowerCase();this._headers.has(t)?this._headers.get(t).push(r.toString()):this._headers.set(t,[r.toString()])}_handleHeadersString(n){n.split(`
|
|
2
|
-
`).forEach(r=>{const[t,s]=r.split(":");t&&s&&this._setHeader(t,s)})}_handleHeadersConstructorProps(n){Object.entries(n).forEach(([r,t])=>this._setHeader(r,t))}_handleHeaders(n){n.forEach((r,t)=>this._setHeader(t,r))}}const D=h.createIdentifier("network.http-implementation");class j{constructor(n){this.params=n}toString(){return this.params?Object.keys(this.params).map(n=>{const r=this.params[n];return Array.isArray(r)?r.map(t=>`${n}=${t}`).join("&"):`${n}=${r}`}).join("&"):""}}let z=0;class U{constructor(n,r,t){y(this,"uid",z++);this.method=n,this.url=r,this.requestParams=t}get headers(){return this.requestParams.headers}get withCredentials(){return this.requestParams.withCredentials}get responseType(){return this.requestParams.responseType}getUrlWithParams(){var r,t;const n=(t=(r=this.requestParams)==null?void 0:r.params)==null?void 0:t.toString();return n?`${this.url}${this.url.includes("?")?"&":"?"}${n}`:this.url}getBody(){var t,s;const n=(t=this.headers.get("Content-Type"))!=null?t:A,r=(s=this.requestParams)==null?void 0:s.body;return r instanceof FormData?r:K(n)&&r&&typeof r=="object"?JSON.stringify(r):r?`${r}`:null}getHeadersInit(){var r;return this.headers.toHeadersInit((r=this.requestParams)==null?void 0:r.body)}}var Y=Object.getOwnPropertyDescriptor,P=(e,n,r,t)=>{for(var s=t>1?void 0:t?Y(n,r):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},Q=(e,n)=>(r,t)=>n(r,t,e);exports.HTTPService=class extends h.Disposable{constructor(r){super();y(this,"_interceptors",[]);y(this,"_pipe");this._http=r}registerHTTPInterceptor(r){if(this._interceptors.indexOf(r)!==-1)throw new Error("[HTTPService]: The interceptor has already been registered!");return this._interceptors.push(r),this._interceptors=this._interceptors.sort((t,s)=>{var o,i;return((o=t.priority)!=null?o:0)-((i=s.priority)!=null?i:0)}),this._pipe=null,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)}async request(r,t,s){var u,p;const o=new E(s==null?void 0:s.headers),i=new j(s==null?void 0:s.params),c=new U(r,t,{headers:o,params:i,withCredentials:(u=s==null?void 0:s.withCredentials)!=null?u:!1,responseType:(p=s==null?void 0:s.responseType)!=null?p:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body}),m=w.of(c).pipe(_.concatMap(a=>this._runInterceptorsAndImplementation(a)));return await w.firstValueFrom(m)}stream(r,t,s){return this.getSSE(r,t,s)}getSSE(r,t,s){var m,l;const o=new E(s==null?void 0:s.headers),i=new j(s==null?void 0:s.params),c=new U(r,t,{headers:o,params:i,withCredentials:(m=s==null?void 0:s.withCredentials)!=null?m:!1,reportProgress:!0,responseType:(l=s==null?void 0:s.responseType)!=null?l:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body});return w.of(c).pipe(_.concatMap(u=>this._runInterceptorsAndImplementation(u)))}_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))}};exports.HTTPService=P([Q(0,D)],exports.HTTPService);function Z(e,n){return(r,t)=>n(r,s=>e(s,t))}const H=200,S=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||{}),q=(e=>(e[e.DownloadProgress=0]="DownloadProgress",e[e.Response=1]="Response",e))(q||{});class L{constructor({body:n,headers:r,status:t,statusText:s}){y(this,"type",1);y(this,"body");y(this,"headers");y(this,"status");y(this,"statusText");this.body=n,this.headers=r,this.status=t,this.statusText=s}}class B{constructor(n,r,t){y(this,"type",0);this.total=n,this.loaded=r,this.partialText=t}}class G{constructor(n,r,t){this.headers=n,this.status=r,this.statusText=t}}class b{constructor({request:n,headers:r,status:t,statusText:s,error:o}){y(this,"request");y(this,"headers");y(this,"status");y(this,"statusText");y(this,"error");this.request=n,this.headers=r,this.status=t,this.statusText=s,this.error=o}}function X(e){return{method:e.method,headers:e.getHeadersInit(),body:e.getBody(),credentials:e.withCredentials?"include":void 0}}var C=Object.getOwnPropertyDescriptor,T=(e,n,r,t)=>{for(var s=t>1?void 0:t?C(n,r):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},ee=(e,n)=>(r,t)=>n(r,t,e);exports.FetchHTTPImplementation=class{constructor(n){this._logService=n}send(n){return new w.Observable(r=>{const t=new AbortController;return this._send(n,r,t).catch(s=>{r.error(new b({error:s,request:n}))}),()=>t.abort()})}async _send(n,r,t){var u,p;let s;try{const a=X(n),f=n.getUrlWithParams(),g=fetch(f,{signal:t.signal,...a});this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${f} with params ${a}`),s=await g}catch(a){const f=new b({request:n,error:a,status:(u=a.status)!=null?u:0,statusText:(p=a.statusText)!=null?p:"Unknown Error",headers:a.headers});this._logService.error("[FetchHTTPImplementation]: network error",f),r.error(f);return}const o=new E(s.headers),i=s.status,c=s.statusText;let m=null;if(s.body&&(m=await this._readBody(n,s,r)),i>=x.Ok&&i<x.MultipleChoices)r.next(new L({body:m,headers:o,status:i,statusText:c}));else{const a=new b({request:n,error:m,status:i,statusText:c,headers:o});this._logService.error("[FetchHTTPImplementation]: network error",a),r.error(a)}r.complete()}async _readBody(n,r,t){var f,g;const s=[],o=r.body.getReader(),i=r.headers.get("content-length");let c=0;const m=(f=n.requestParams)==null?void 0:f.reportProgress,l=n.responseType;let u,p;for(;;){const{done:v,value:d}=await o.read();if(v)break;s.push(d),c+=d.length,m&&l==="text"&&(u=(u!=null?u:"")+(p!=null?p:p=new TextDecoder).decode(d,{stream:!0}),t.next(new B(i?Number.parseInt(i,10):void 0,c,u)))}const a=re(s,c);try{const v=(g=r.headers.get("content-type"))!=null?g:"";return ne(n,a,v)}catch(v){const d=new b({request:n,error:v,status:r.status,statusText:r.statusText,headers:new E(r.headers)});return this._logService.error("[FetchHTTPImplementation]: network error",d),t.error(d),null}}};exports.FetchHTTPImplementation=T([ee(0,h.ILogService)],exports.FetchHTTPImplementation);function re(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 te=/^\)\]\}',?\n/;function ne(e,n,r){switch(e.responseType){case"json":const t=new TextDecoder().decode(n).replace(te,"");return t===""?null:JSON.parse(t);case"text":return new TextDecoder().decode(n);case"blob":return new Blob([n],{type:r});case"arraybuffer":return n.buffer;default:throw new Error(`[FetchHTTPImplementation]: unknown response type: ${e.responseType}.`)}}var se=Object.getOwnPropertyDescriptor,oe=(e,n,r,t)=>{for(var s=t>1?void 0:t?se(n,r):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},ie=(e,n)=>(r,t)=>n(r,t,e);exports.XHRHTTPImplementation=class{constructor(n){this._logService=n}send(n){return new w.Observable(r=>{const t=new XMLHttpRequest,s=n.getUrlWithParams(),o=X(n),{responseType:i}=n;t.open(n.method,s),n.withCredentials&&(t.withCredentials=!0),o.headers&&Object.entries(o.headers).forEach(([p,a])=>t.setRequestHeader(p,a));const c=()=>{const p=t.statusText||"OK",a=new E(t.getAllResponseHeaders());return new G(a,t.status,p)},m=()=>{const{headers:p,statusText:a,status:f}=c();let g=null,v=null;f!==x.NoContent&&(g=typeof t.response>"u"?t.responseText:t.response);let d=f>=H&&f<S;if(i==="json"&&typeof g=="string"){const I=g;try{g=g?JSON.parse(g):null}catch(R){d=!1,g=I,v=R}}if(i==="blob"&&!(g instanceof Blob)&&(d=!1,v=new Error("Response is not a Blob object")),d)r.next(new L({body:g,headers:p,status:f,statusText:a}));else{const I=new b({request:n,error:v,headers:p,status:f,statusText:a});this._logService.error("[XHRHTTPImplementation]: network error",I),r.error(I)}},l=p=>{const a=new b({request:n,error:p,status:t.status||0,statusText:t.statusText||"Unknown Error",headers:c().headers});this._logService.error("[XHRHTTPImplementation]: network error",a),r.error(a)};t.responseType=i||"",t.addEventListener("load",m),t.addEventListener("error",l),t.addEventListener("abort",l),t.addEventListener("timeout",l);const u=n.getBody();return t.send(u),this._logService.debug("[XHRHTTPImplementation]",`sending request to url ${s} with params ${o}`),()=>{t.readyState!==t.DONE&&t.abort(),t.removeEventListener("load",m),t.removeEventListener("error",l),t.removeEventListener("abort",l),t.removeEventListener("timeout",l)}})}};exports.XHRHTTPImplementation=oe([ie(0,h.ILogService)],exports.XHRHTTPImplementation);var ce=Object.getOwnPropertyDescriptor,ae=(e,n,r,t)=>{for(var s=t>1?void 0:t?ce(n,r):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},k=(e,n)=>(r,t)=>n(r,t,e),O;exports.UniverNetworkPlugin=(O=class extends h.Plugin{constructor(n=$,r,t,s){super(),this._config=n,this._logger=r,this._injector=t,this._configService=s;const{...o}=h.merge({},$,this._config);this._configService.setConfig(J,o)}onStarting(){var t,s,o;if(this._injector.get(exports.HTTPService,h.Quantity.OPTIONAL,h.LookUp.SKIP_SELF)&&!((t=this._config)!=null&&t.forceUseNewInstance)){this._logger.warn("[UniverNetworkPlugin]",'HTTPService is already registered in an ancestor interceptor. Skipping registration. If you want to force a new instance, set "forceUseNewInstance" to true in the plugin configuration.');return}const r=(s=this._config)!=null&&s.useFetchImpl?exports.FetchHTTPImplementation:typeof window<"u"?exports.XHRHTTPImplementation:exports.FetchHTTPImplementation;h.registerDependencies(this._injector,h.mergeOverrideWithDependencies([[exports.HTTPService],[D,{useClass:r}]],(o=this._config)==null?void 0:o.override))}},y(O,"pluginName","UNIVER_NETWORK_PLUGIN"),O);exports.UniverNetworkPlugin=ae([k(1,h.ILogService),k(2,h.Inject(h.Injector)),k(3,h.IConfigService)],exports.UniverNetworkPlugin);const le=e=>{const{errorStatusCodes:n,onAuthError:r}=e;return(s,o)=>o(s).pipe(w.catchError(i=>(i instanceof b&&n.some(c=>c===i.status)&&r(),w.throwError(()=>i))))},he=(e=300)=>{let r=()=>{};return t=>new Promise(s=>{r();const o=setTimeout(()=>{s(!0)},e);r=()=>{clearTimeout(o),s(!1)}})},pe=()=>(e,n)=>n.map(r=>({config:r,result:e})),de=(e,n={})=>{const{isMatch:r,getParamsFromRequest:t,mergeParamsToRequest:s}=e,{fetchCheck:o=he(300),distributeResult:i=pe()}=n,c=[],m=l=>l.map(u=>u.config);return(l,u)=>r(l)?new w.Observable(p=>{const a=t(l);c.push({next:g=>p.next(g),error:g=>p.error(g),config:a});const f=m(c);o(l).then(g=>{if(g){const v=[];f.forEach(d=>{const I=c.findIndex(R=>R.config===d);if(I>=0){const[R]=c.splice(I,1);v.push(R)}}),u(s(f,l)).subscribe({next:d=>{if(d.type===q.Response){const I=d.body,R=i(I,f);v.forEach(F=>{const M=R.find(N=>N.config===F.config);if(M){const N=new L({body:M.result,headers:d.headers,status:d.status,statusText:d.statusText});F.next(N)}else F.error("batch error")})}},complete:()=>p.complete(),error:d=>p.error(d)})}})}):u(l)},ue=3,ge=1e3,fe=e=>{var t,s;const n=(t=e==null?void 0:e.maxRetryAttempts)!=null?t:ue,r=(s=e==null?void 0:e.delayInterval)!=null?s:ge;return(o,i)=>i(o).pipe(_.retry({delay:r,count:n}))},me=e=>{const n=[],r=new Set,t=()=>{var s;for(;r.size<((s=e==null?void 0:e.maxParallel)!=null?s:1)&&n.length>0;){const o=n.shift();r.add(o),o()}};return(s,o)=>new w.Observable(i=>{const c=()=>o(s).subscribe({next:l=>i.next(l),error:l=>i.error(l),complete:()=>i.complete()}),m=()=>{r.delete(c),h.remove(n,c),t()};return n.push(c),t(),m})},ye=h.createIdentifier("univer.network.socket.service");class we 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 w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("open",i),t.add(h.toDisposable(()=>r.removeEventListener("open",i)))}).pipe(_.share()),close$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("close",i),t.add(h.toDisposable(()=>r.removeEventListener("close",i)))}).pipe(_.share()),error$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("error",i),t.add(h.toDisposable(()=>r.removeEventListener("error",i)))}).pipe(_.share()),message$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("message",i),t.add(h.toDisposable(()=>r.removeEventListener("message",i)))}).pipe(_.share())}}catch(r){return console.error(r),null}}}exports.AuthInterceptorFactory=le;exports.HTTPEventType=q;exports.HTTPHeaders=E;exports.HTTPProgress=B;exports.HTTPRequest=U;exports.HTTPResponse=L;exports.HTTPResponseError=b;exports.HTTPStatusCode=x;exports.IHTTPImplementation=D;exports.ISocketService=ye;exports.MergeInterceptorFactory=de;exports.ResponseHeader=G;exports.RetryInterceptorFactory=fe;exports.ThresholdInterceptorFactory=me;exports.WebSocketService=we;
|
|
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 j{constructor(n){this.params=n}toString(){return this.params?Object.keys(this.params).map(n=>{const r=this.params[n];return Array.isArray(r)?r.map(t=>`${n}=${t}`).join("&"):`${n}=${r}`}).join("&"):""}}let z=0;class U{constructor(n,r,t){y(this,"uid",z++);this.method=n,this.url=r,this.requestParams=t}get headers(){return this.requestParams.headers}get withCredentials(){return this.requestParams.withCredentials}get responseType(){return this.requestParams.responseType}getUrlWithParams(){var r,t;const n=(t=(r=this.requestParams)==null?void 0:r.params)==null?void 0:t.toString();return n?`${this.url}${this.url.includes("?")?"&":"?"}${n}`:this.url}getBody(){var t,s;const n=(t=this.headers.get("Content-Type"))!=null?t:A,r=(s=this.requestParams)==null?void 0:s.body;return r instanceof FormData?r:K(n)&&r&&typeof r=="object"?JSON.stringify(r):r?`${r}`:null}getHeadersInit(){var r;return this.headers.toHeadersInit((r=this.requestParams)==null?void 0:r.body)}}var Y=Object.getOwnPropertyDescriptor,P=(e,n,r,t)=>{for(var s=t>1?void 0:t?Y(n,r):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},Q=(e,n)=>(r,t)=>n(r,t,e);exports.HTTPService=class extends h.Disposable{constructor(r){super();y(this,"_interceptors",[]);y(this,"_pipe");this._http=r}registerHTTPInterceptor(r){if(this._interceptors.indexOf(r)!==-1)throw new Error("[HTTPService]: The interceptor has already been registered!");return this._interceptors.push(r),this._interceptors=this._interceptors.sort((t,s)=>{var o,i;return((o=t.priority)!=null?o:0)-((i=s.priority)!=null?i:0)}),this._pipe=null,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)}async request(r,t,s){var u,p;const o=new E(s==null?void 0:s.headers),i=new j(s==null?void 0:s.params),c=new U(r,t,{headers:o,params:i,withCredentials:(u=s==null?void 0:s.withCredentials)!=null?u:!1,responseType:(p=s==null?void 0:s.responseType)!=null?p:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body}),m=w.of(c).pipe(_.concatMap(a=>this._runInterceptorsAndImplementation(a)));return await w.firstValueFrom(m)}stream(r,t,s){return this.getSSE(r,t,s)}getSSE(r,t,s){var m,l;const o=new E(s==null?void 0:s.headers),i=new j(s==null?void 0:s.params),c=new U(r,t,{headers:o,params:i,withCredentials:(m=s==null?void 0:s.withCredentials)!=null?m:!1,reportProgress:!0,responseType:(l=s==null?void 0:s.responseType)!=null?l:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body});return w.of(c).pipe(_.concatMap(u=>this._runInterceptorsAndImplementation(u)))}_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))}};exports.HTTPService=P([Q(0,D)],exports.HTTPService);function Z(e,n){return(r,t)=>n(r,s=>e(s,t))}const H=200,S=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||{}),q=(e=>(e[e.DownloadProgress=0]="DownloadProgress",e[e.Response=1]="Response",e))(q||{});class L{constructor({body:n,headers:r,status:t,statusText:s}){y(this,"type",1);y(this,"body");y(this,"headers");y(this,"status");y(this,"statusText");this.body=n,this.headers=r,this.status=t,this.statusText=s}}class B{constructor(n,r,t){y(this,"type",0);this.total=n,this.loaded=r,this.partialText=t}}class G{constructor(n,r,t){this.headers=n,this.status=r,this.statusText=t}}class I{constructor({request:n,headers:r,status:t,statusText:s,error:o}){y(this,"request");y(this,"headers");y(this,"status");y(this,"statusText");y(this,"error");this.request=n,this.headers=r,this.status=t,this.statusText=s,this.error=o}}function X(e){return{method:e.method,headers:e.getHeadersInit(),body:e.getBody(),credentials:e.withCredentials?"include":void 0}}var C=Object.getOwnPropertyDescriptor,T=(e,n,r,t)=>{for(var s=t>1?void 0:t?C(n,r):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},ee=(e,n)=>(r,t)=>n(r,t,e);exports.FetchHTTPImplementation=class{constructor(n){this._logService=n}send(n){return new w.Observable(r=>{const t=new AbortController;return this._send(n,r,t).catch(s=>{r.error(new I({error:s,request:n}))}),()=>t.abort()})}async _send(n,r,t){var u,p;let s;try{const a=X(n),f=n.getUrlWithParams(),g=fetch(f,{signal:t.signal,...a});this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${f} with params ${a}`),s=await g}catch(a){const f=new I({request:n,error:a,status:(u=a.status)!=null?u:0,statusText:(p=a.statusText)!=null?p:"Unknown Error",headers:a.headers});this._logService.error("[FetchHTTPImplementation]: network error",f),r.error(f);return}const o=new E(s.headers),i=s.status,c=s.statusText;let m=null;if(s.body&&(m=await this._readBody(n,s,r)),i>=x.Ok&&i<x.MultipleChoices)r.next(new L({body:m,headers:o,status:i,statusText:c}));else{const a=new I({request:n,error:m,status:i,statusText:c,headers:o});this._logService.error("[FetchHTTPImplementation]: network error",a),r.error(a)}r.complete()}async _readBody(n,r,t){var f,g;const s=[],o=r.body.getReader(),i=r.headers.get("content-length");let c=0;const m=(f=n.requestParams)==null?void 0:f.reportProgress,l=n.responseType;let u,p;for(;;){const{done:v,value:d}=await o.read();if(v)break;s.push(d),c+=d.length,m&&l==="text"&&(u=(u!=null?u:"")+(p!=null?p:p=new TextDecoder).decode(d,{stream:!0}),t.next(new B(i?Number.parseInt(i,10):void 0,c,u)))}const a=re(s,c);try{const v=(g=r.headers.get("content-type"))!=null?g:"";return ne(n,a,v)}catch(v){const d=new I({request:n,error:v,status:r.status,statusText:r.statusText,headers:new E(r.headers)});return this._logService.error("[FetchHTTPImplementation]: network error",d),t.error(d),null}}};exports.FetchHTTPImplementation=T([ee(0,h.ILogService)],exports.FetchHTTPImplementation);function re(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 te=/^\)\]\}',?\n/;function ne(e,n,r){switch(e.responseType){case"json":const t=new TextDecoder().decode(n).replace(te,"");return t===""?null:JSON.parse(t);case"text":return new TextDecoder().decode(n);case"blob":return new Blob([n.buffer],{type:r});case"arraybuffer":return n.buffer;default:throw new Error(`[FetchHTTPImplementation]: unknown response type: ${e.responseType}.`)}}var se=Object.getOwnPropertyDescriptor,oe=(e,n,r,t)=>{for(var s=t>1?void 0:t?se(n,r):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},ie=(e,n)=>(r,t)=>n(r,t,e);exports.XHRHTTPImplementation=class{constructor(n){this._logService=n}send(n){return new w.Observable(r=>{const t=new XMLHttpRequest,s=n.getUrlWithParams(),o=X(n),{responseType:i}=n;t.open(n.method,s),n.withCredentials&&(t.withCredentials=!0),o.headers&&Object.entries(o.headers).forEach(([p,a])=>t.setRequestHeader(p,a));const c=()=>{const p=t.statusText||"OK",a=new E(t.getAllResponseHeaders());return new G(a,t.status,p)},m=()=>{const{headers:p,statusText:a,status:f}=c();let g=null,v=null;f!==x.NoContent&&(g=typeof t.response>"u"?t.responseText:t.response);let d=f>=H&&f<S;if(i==="json"&&typeof g=="string"){const b=g;try{g=g?JSON.parse(g):null}catch(R){d=!1,g=b,v=R}}if(i==="blob"&&!(g instanceof Blob)&&(d=!1,v=new Error("Response is not a Blob object")),d)r.next(new L({body:g,headers:p,status:f,statusText:a}));else{const b=new I({request:n,error:v,headers:p,status:f,statusText:a});this._logService.error("[XHRHTTPImplementation]: network error",b),r.error(b)}},l=p=>{const a=new I({request:n,error:p,status:t.status||0,statusText:t.statusText||"Unknown Error",headers:c().headers});this._logService.error("[XHRHTTPImplementation]: network error",a),r.error(a)};t.responseType=i||"",t.addEventListener("load",m),t.addEventListener("error",l),t.addEventListener("abort",l),t.addEventListener("timeout",l);const u=n.getBody();return t.send(u),this._logService.debug("[XHRHTTPImplementation]",`sending request to url ${s} with params ${o}`),()=>{t.readyState!==t.DONE&&t.abort(),t.removeEventListener("load",m),t.removeEventListener("error",l),t.removeEventListener("abort",l),t.removeEventListener("timeout",l)}})}};exports.XHRHTTPImplementation=oe([ie(0,h.ILogService)],exports.XHRHTTPImplementation);var ce=Object.getOwnPropertyDescriptor,ae=(e,n,r,t)=>{for(var s=t>1?void 0:t?ce(n,r):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},k=(e,n)=>(r,t)=>n(r,t,e),O;exports.UniverNetworkPlugin=(O=class extends h.Plugin{constructor(n=$,r,t,s){super(),this._config=n,this._logger=r,this._injector=t,this._configService=s;const{...o}=h.merge({},$,this._config);this._configService.setConfig(J,o)}onStarting(){var t,s,o;if(this._injector.get(exports.HTTPService,h.Quantity.OPTIONAL,h.LookUp.SKIP_SELF)&&!((t=this._config)!=null&&t.forceUseNewInstance)){this._logger.warn("[UniverNetworkPlugin]",'HTTPService is already registered in an ancestor interceptor. Skipping registration. If you want to force a new instance, set "forceUseNewInstance" to true in the plugin configuration.');return}const r=(s=this._config)!=null&&s.useFetchImpl?exports.FetchHTTPImplementation:typeof window<"u"?exports.XHRHTTPImplementation:exports.FetchHTTPImplementation;h.registerDependencies(this._injector,h.mergeOverrideWithDependencies([[exports.HTTPService],[D,{useClass:r}]],(o=this._config)==null?void 0:o.override))}},y(O,"pluginName","UNIVER_NETWORK_PLUGIN"),O);exports.UniverNetworkPlugin=ae([k(1,h.ILogService),k(2,h.Inject(h.Injector)),k(3,h.IConfigService)],exports.UniverNetworkPlugin);const le=e=>{const{errorStatusCodes:n,onAuthError:r}=e;return(s,o)=>o(s).pipe(w.catchError(i=>(i instanceof I&&n.some(c=>c===i.status)&&r(),w.throwError(()=>i))))},he=(e=300)=>{let r=()=>{};return t=>new Promise(s=>{r();const o=setTimeout(()=>{s(!0)},e);r=()=>{clearTimeout(o),s(!1)}})},pe=()=>(e,n)=>n.map(r=>({config:r,result:e})),de=(e,n={})=>{const{isMatch:r,getParamsFromRequest:t,mergeParamsToRequest:s}=e,{fetchCheck:o=he(300),distributeResult:i=pe()}=n,c=[],m=l=>l.map(u=>u.config);return(l,u)=>r(l)?new w.Observable(p=>{const a=t(l);c.push({next:g=>p.next(g),error:g=>p.error(g),config:a});const f=m(c);o(l).then(g=>{if(g){const v=[];f.forEach(d=>{const b=c.findIndex(R=>R.config===d);if(b>=0){const[R]=c.splice(b,1);v.push(R)}}),u(s(f,l)).subscribe({next:d=>{if(d.type===q.Response){const b=d.body,R=i(b,f);v.forEach(F=>{const M=R.find(N=>N.config===F.config);if(M){const N=new L({body:M.result,headers:d.headers,status:d.status,statusText:d.statusText});F.next(N)}else F.error("batch error")})}},complete:()=>p.complete(),error:d=>p.error(d)})}})}):u(l)},ue=3,ge=1e3,fe=e=>{var t,s;const n=(t=e==null?void 0:e.maxRetryAttempts)!=null?t:ue,r=(s=e==null?void 0:e.delayInterval)!=null?s:ge;return(o,i)=>i(o).pipe(_.retry({delay:r,count:n}))},me=e=>{const n=[],r=new Set,t=()=>{var s;for(;r.size<((s=e==null?void 0:e.maxParallel)!=null?s:1)&&n.length>0;){const o=n.shift();r.add(o),o()}};return(s,o)=>new w.Observable(i=>{const c=()=>o(s).subscribe({next:l=>i.next(l),error:l=>i.error(l),complete:()=>i.complete()}),m=()=>{r.delete(c),h.remove(n,c),t()};return n.push(c),t(),m})},ye=h.createIdentifier("univer.network.socket.service");class we 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 w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("open",i),t.add(h.toDisposable(()=>r.removeEventListener("open",i)))}).pipe(_.share()),close$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("close",i),t.add(h.toDisposable(()=>r.removeEventListener("close",i)))}).pipe(_.share()),error$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("error",i),t.add(h.toDisposable(()=>r.removeEventListener("error",i)))}).pipe(_.share()),message$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("message",i),t.add(h.toDisposable(()=>r.removeEventListener("message",i)))}).pipe(_.share())}}catch(r){return console.error(r),null}}}exports.AuthInterceptorFactory=le;exports.HTTPEventType=q;exports.HTTPHeaders=E;exports.HTTPProgress=B;exports.HTTPRequest=U;exports.HTTPResponse=L;exports.HTTPResponseError=I;exports.HTTPStatusCode=x;exports.IHTTPImplementation=D;exports.ISocketService=ye;exports.MergeInterceptorFactory=de;exports.ResponseHeader=G;exports.RetryInterceptorFactory=fe;exports.ThresholdInterceptorFactory=me;exports.WebSocketService=we;
|
package/lib/es/index.js
CHANGED
package/lib/index.js
CHANGED
package/lib/umd/facade.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(function(r,n){typeof exports=="object"&&typeof module<"u"?n(require("@univerjs/core/facade"),require("@univerjs/network"),require("@univerjs/core")):typeof define=="function"&&define.amd?define(["@univerjs/core/facade","@univerjs/network","@univerjs/core"],n):(r=typeof globalThis<"u"?globalThis:r||self,n(r.UniverCoreFacade,r.UniverNetwork,r.UniverCore))})(this,function(r,n,o){"use strict";var S=Object.getOwnPropertyDescriptor,a=(t,e,c,i)=>{for(var s=i>1?void 0:i?S(e,c):e,v=t.length-1,p;v>=0;v--)(p=t[v])&&(s=p(s)||s);return s},h=(t,e)=>(c,i)=>e(c,i,t);let u=class extends r.FBase{constructor(t,e){super(),this._injector=t,this._httpService=e}get(t,e){return this._httpService.get(t,e)}post(t,e){return this._httpService.post(t,e)}put(t,e){return this._httpService.put(t,e)}delete(t,e){return this._httpService.delete(t,e)}patch(t,e){return this._httpService.patch(t,e)}getSSE(t,e,c){return this._httpService.getSSE(t,e,c)}};u=a([h(0,o.Inject(o.Injector)),h(1,o.Inject(n.HTTPService))],u);class d extends r.FUniver{getNetwork(){return this._injector.createInstance(u)}createSocket(e){const i=this._injector.createInstance(n.WebSocketService).createSocket(e);if(!i)throw new Error("[WebSocketService]: failed to create socket!");return i}}r.FUniver.extend(d)});
|
|
1
|
+
(function(r,n){typeof exports=="object"&&typeof module<"u"?n(require("@univerjs/core/facade"),require("@univerjs/network"),require("@univerjs/core")):typeof define=="function"&&define.amd?define(["@univerjs/core/facade","@univerjs/network","@univerjs/core"],n):(r=typeof globalThis<"u"?globalThis:r||self,n(r.UniverCoreFacade,r.UniverNetwork,r.UniverCore))})(this,(function(r,n,o){"use strict";var S=Object.getOwnPropertyDescriptor,a=(t,e,c,i)=>{for(var s=i>1?void 0:i?S(e,c):e,v=t.length-1,p;v>=0;v--)(p=t[v])&&(s=p(s)||s);return s},h=(t,e)=>(c,i)=>e(c,i,t);let u=class extends r.FBase{constructor(t,e){super(),this._injector=t,this._httpService=e}get(t,e){return this._httpService.get(t,e)}post(t,e){return this._httpService.post(t,e)}put(t,e){return this._httpService.put(t,e)}delete(t,e){return this._httpService.delete(t,e)}patch(t,e){return this._httpService.patch(t,e)}getSSE(t,e,c){return this._httpService.getSSE(t,e,c)}};u=a([h(0,o.Inject(o.Injector)),h(1,o.Inject(n.HTTPService))],u);class d extends r.FUniver{getNetwork(){return this._injector.createInstance(u)}createSocket(e){const i=this._injector.createInstance(n.WebSocketService).createSocket(e);if(!i)throw new Error("[WebSocketService]: failed to create socket!");return i}}r.FUniver.extend(d)}));
|
package/lib/umd/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(c,a){typeof exports=="object"&&typeof module<"u"?a(exports,require("@univerjs/core"),require("rxjs"),require("rxjs/operators")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","rxjs","rxjs/operators"],a):(c=typeof globalThis<"u"?globalThis:c||self,a(c.UniverNetwork={},c.UniverCore,c.rxjs,c.rxjs.operators))})(this,function(c,a,m,_){"use strict";var we=Object.defineProperty;var ve=(c,a,m)=>a in c?we(c,a,{enumerable:!0,configurable:!0,writable:!0,value:m}):c[a]=m;var v=(c,a,m)=>ve(c,typeof a!="symbol"?a+"":a,m);var q;const V="network.config",j={},k="application/json";function J(e){return Array.isArray(e)?e.some(n=>n.includes(k)):e.includes(k)}class L{constructor(n){v(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((t,r)=>n(r,t))}has(n){return!!this._headers.has(n.toLowerCase())}get(n){const t=n.toLowerCase();return this._headers.has(t)?this._headers.get(t):null}set(n,t){this._setHeader(n,t)}toHeadersInit(n){var r,s;const t={};return this._headers.forEach((i,o)=>{t[o]=i.join(",")}),(r=t.accept)!=null||(t.accept="application/json, text/plain, */*"),n instanceof FormData||(s=t["content-type"])!=null||(t["content-type"]="application/json;charset=UTF-8"),t}_setHeader(n,t){const r=n.toLowerCase();this._headers.has(r)?this._headers.get(r).push(t.toString()):this._headers.set(r,[t.toString()])}_handleHeadersString(n){n.split(`
|
|
2
|
-
`).forEach(t=>{const[r,s]=t.split(":");r&&s&&this._setHeader(r,s)})}_handleHeadersConstructorProps(n){Object.entries(n).forEach(([t,r])=>this._setHeader(t,r))}_handleHeaders(n){n.forEach((t,r)=>this._setHeader(r,t))}}const O=a.createIdentifier("network.http-implementation");class x{constructor(n){this.params=n}toString(){return this.params?Object.keys(this.params).map(n=>{const t=this.params[n];return Array.isArray(t)?t.map(r=>`${n}=${r}`).join("&"):`${n}=${t}`}).join("&"):""}}let K=0;class A{constructor(n,t,r){v(this,"uid",K++);this.method=n,this.url=t,this.requestParams=r}get headers(){return this.requestParams.headers}get withCredentials(){return this.requestParams.withCredentials}get responseType(){return this.requestParams.responseType}getUrlWithParams(){var t,r;const n=(r=(t=this.requestParams)==null?void 0:t.params)==null?void 0:r.toString();return n?`${this.url}${this.url.includes("?")?"&":"?"}${n}`:this.url}getBody(){var r,s;const n=(r=this.headers.get("Content-Type"))!=null?r:k,t=(s=this.requestParams)==null?void 0:s.body;return t instanceof FormData?t:J(n)&&t&&typeof t=="object"?JSON.stringify(t):t?`${t}`:null}getHeadersInit(){var t;return this.headers.toHeadersInit((t=this.requestParams)==null?void 0:t.body)}}var z=Object.getOwnPropertyDescriptor,Y=(e,n,t,r)=>{for(var s=r>1?void 0:r?z(n,t):n,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=o(s)||s);return s},P=(e,n)=>(t,r)=>n(t,r,e);c.HTTPService=class extends a.Disposable{constructor(t){super();v(this,"_interceptors",[]);v(this,"_pipe");this._http=t}registerHTTPInterceptor(t){if(this._interceptors.indexOf(t)!==-1)throw new Error("[HTTPService]: The interceptor has already been registered!");return this._interceptors.push(t),this._interceptors=this._interceptors.sort((r,s)=>{var i,o;return((i=r.priority)!=null?i:0)-((o=s.priority)!=null?o:0)}),this._pipe=null,a.toDisposable(()=>a.remove(this._interceptors,t))}get(t,r){return this.request("GET",t,r)}post(t,r){return this.request("POST",t,r)}put(t,r){return this.request("PUT",t,r)}delete(t,r){return this.request("DELETE",t,r)}patch(t,r){return this.request("PATCH",t,r)}async request(t,r,s){var g,p;const i=new L(s==null?void 0:s.headers),o=new x(s==null?void 0:s.params),l=new A(t,r,{headers:i,params:o,withCredentials:(g=s==null?void 0:s.withCredentials)!=null?g:!1,responseType:(p=s==null?void 0:s.responseType)!=null?p:"json",body:["GET","DELETE"].includes(t)||s==null?void 0:s.body}),w=m.of(l).pipe(_.concatMap(h=>this._runInterceptorsAndImplementation(h)));return await m.firstValueFrom(w)}stream(t,r,s){return this.getSSE(t,r,s)}getSSE(t,r,s){var w,d;const i=new L(s==null?void 0:s.headers),o=new x(s==null?void 0:s.params),l=new A(t,r,{headers:i,params:o,withCredentials:(w=s==null?void 0:s.withCredentials)!=null?w:!1,reportProgress:!0,responseType:(d=s==null?void 0:s.responseType)!=null?d:"json",body:["GET","DELETE"].includes(t)||s==null?void 0:s.body});return m.of(l).pipe(_.concatMap(g=>this._runInterceptorsAndImplementation(g)))}_runInterceptorsAndImplementation(t){return this._pipe||(this._pipe=this._interceptors.map(r=>r.interceptor).reduceRight((r,s)=>Q(r,s),(r,s)=>s(r))),this._pipe(t,r=>this._http.send(r))}},c.HTTPService=Y([P(0,O)],c.HTTPService);function Q(e,n){return(t,r)=>n(t,s=>e(s,r))}const Z=200,H=300;var F=(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))(F||{}),U=(e=>(e[e.DownloadProgress=0]="DownloadProgress",e[e.Response=1]="Response",e))(U||{});class N{constructor({body:n,headers:t,status:r,statusText:s}){v(this,"type",1);v(this,"body");v(this,"headers");v(this,"status");v(this,"statusText");this.body=n,this.headers=t,this.status=r,this.statusText=s}}class B{constructor(n,t,r){v(this,"type",0);this.total=n,this.loaded=t,this.partialText=r}}class G{constructor(n,t,r){this.headers=n,this.status=t,this.statusText=r}}class R{constructor({request:n,headers:t,status:r,statusText:s,error:i}){v(this,"request");v(this,"headers");v(this,"status");v(this,"statusText");v(this,"error");this.request=n,this.headers=t,this.status=r,this.statusText=s,this.error=i}}function X(e){return{method:e.method,headers:e.getHeadersInit(),body:e.getBody(),credentials:e.withCredentials?"include":void 0}}var S=Object.getOwnPropertyDescriptor,C=(e,n,t,r)=>{for(var s=r>1?void 0:r?S(n,t):n,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=o(s)||s);return s},T=(e,n)=>(t,r)=>n(t,r,e);c.FetchHTTPImplementation=class{constructor(n){this._logService=n}send(n){return new m.Observable(t=>{const r=new AbortController;return this._send(n,t,r).catch(s=>{t.error(new R({error:s,request:n}))}),()=>r.abort()})}async _send(n,t,r){var g,p;let s;try{const h=X(n),y=n.getUrlWithParams(),f=fetch(y,{signal:r.signal,...h});this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${y} with params ${h}`),s=await f}catch(h){const y=new R({request:n,error:h,status:(g=h.status)!=null?g:0,statusText:(p=h.statusText)!=null?p:"Unknown Error",headers:h.headers});this._logService.error("[FetchHTTPImplementation]: network error",y),t.error(y);return}const i=new L(s.headers),o=s.status,l=s.statusText;let w=null;if(s.body&&(w=await this._readBody(n,s,t)),o>=F.Ok&&o<F.MultipleChoices)t.next(new N({body:w,headers:i,status:o,statusText:l}));else{const h=new R({request:n,error:w,status:o,statusText:l,headers:i});this._logService.error("[FetchHTTPImplementation]: network error",h),t.error(h)}t.complete()}async _readBody(n,t,r){var y,f;const s=[],i=t.body.getReader(),o=t.headers.get("content-length");let l=0;const w=(y=n.requestParams)==null?void 0:y.reportProgress,d=n.responseType;let g,p;for(;;){const{done:I,value:u}=await i.read();if(I)break;s.push(u),l+=u.length,w&&d==="text"&&(g=(g!=null?g:"")+(p!=null?p:p=new TextDecoder).decode(u,{stream:!0}),r.next(new B(o?Number.parseInt(o,10):void 0,l,g)))}const h=ee(s,l);try{const I=(f=t.headers.get("content-type"))!=null?f:"";return re(n,h,I)}catch(I){const u=new R({request:n,error:I,status:t.status,statusText:t.statusText,headers:new L(t.headers)});return this._logService.error("[FetchHTTPImplementation]: network error",u),r.error(u),null}}},c.FetchHTTPImplementation=C([T(0,a.ILogService)],c.FetchHTTPImplementation);function ee(e,n){const t=new Uint8Array(n);let r=0;for(const s of e)t.set(s,r),r+=s.length;return t}const te=/^\)\]\}',?\n/;function re(e,n,t){switch(e.responseType){case"json":const r=new TextDecoder().decode(n).replace(te,"");return r===""?null:JSON.parse(r);case"text":return new TextDecoder().decode(n);case"blob":return new Blob([n],{type:t});case"arraybuffer":return n.buffer;default:throw new Error(`[FetchHTTPImplementation]: unknown response type: ${e.responseType}.`)}}var ne=Object.getOwnPropertyDescriptor,se=(e,n,t,r)=>{for(var s=r>1?void 0:r?ne(n,t):n,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=o(s)||s);return s},ie=(e,n)=>(t,r)=>n(t,r,e);c.XHRHTTPImplementation=class{constructor(n){this._logService=n}send(n){return new m.Observable(t=>{const r=new XMLHttpRequest,s=n.getUrlWithParams(),i=X(n),{responseType:o}=n;r.open(n.method,s),n.withCredentials&&(r.withCredentials=!0),i.headers&&Object.entries(i.headers).forEach(([p,h])=>r.setRequestHeader(p,h));const l=()=>{const p=r.statusText||"OK",h=new L(r.getAllResponseHeaders());return new G(h,r.status,p)},w=()=>{const{headers:p,statusText:h,status:y}=l();let f=null,I=null;y!==F.NoContent&&(f=typeof r.response>"u"?r.responseText:r.response);let u=y>=Z&&y<H;if(o==="json"&&typeof f=="string"){const b=f;try{f=f?JSON.parse(f):null}catch(E){u=!1,f=b,I=E}}if(o==="blob"&&!(f instanceof Blob)&&(u=!1,I=new Error("Response is not a Blob object")),u)t.next(new N({body:f,headers:p,status:y,statusText:h}));else{const b=new R({request:n,error:I,headers:p,status:y,statusText:h});this._logService.error("[XHRHTTPImplementation]: network error",b),t.error(b)}},d=p=>{const h=new R({request:n,error:p,status:r.status||0,statusText:r.statusText||"Unknown Error",headers:l().headers});this._logService.error("[XHRHTTPImplementation]: network error",h),t.error(h)};r.responseType=o||"",r.addEventListener("load",w),r.addEventListener("error",d),r.addEventListener("abort",d),r.addEventListener("timeout",d);const g=n.getBody();return r.send(g),this._logService.debug("[XHRHTTPImplementation]",`sending request to url ${s} with params ${i}`),()=>{r.readyState!==r.DONE&&r.abort(),r.removeEventListener("load",w),r.removeEventListener("error",d),r.removeEventListener("abort",d),r.removeEventListener("timeout",d)}})}},c.XHRHTTPImplementation=se([ie(0,a.ILogService)],c.XHRHTTPImplementation);var oe=Object.getOwnPropertyDescriptor,ce=(e,n,t,r)=>{for(var s=r>1?void 0:r?oe(n,t):n,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=o(s)||s);return s},D=(e,n)=>(t,r)=>n(t,r,e);c.UniverNetworkPlugin=(q=class extends a.Plugin{constructor(n=j,t,r,s){super(),this._config=n,this._logger=t,this._injector=r,this._configService=s;const{...i}=a.merge({},j,this._config);this._configService.setConfig(V,i)}onStarting(){var r,s,i;if(this._injector.get(c.HTTPService,a.Quantity.OPTIONAL,a.LookUp.SKIP_SELF)&&!((r=this._config)!=null&&r.forceUseNewInstance)){this._logger.warn("[UniverNetworkPlugin]",'HTTPService is already registered in an ancestor interceptor. Skipping registration. If you want to force a new instance, set "forceUseNewInstance" to true in the plugin configuration.');return}const t=(s=this._config)!=null&&s.useFetchImpl?c.FetchHTTPImplementation:typeof window<"u"?c.XHRHTTPImplementation:c.FetchHTTPImplementation;a.registerDependencies(this._injector,a.mergeOverrideWithDependencies([[c.HTTPService],[O,{useClass:t}]],(i=this._config)==null?void 0:i.override))}},v(q,"pluginName","UNIVER_NETWORK_PLUGIN"),q),c.UniverNetworkPlugin=ce([D(1,a.ILogService),D(2,a.Inject(a.Injector)),D(3,a.IConfigService)],c.UniverNetworkPlugin);const ae=e=>{const{errorStatusCodes:n,onAuthError:t}=e;return(s,i)=>i(s).pipe(m.catchError(o=>(o instanceof R&&n.some(l=>l===o.status)&&t(),m.throwError(()=>o))))},le=(e=300)=>{let t=()=>{};return r=>new Promise(s=>{t();const i=setTimeout(()=>{s(!0)},e);t=()=>{clearTimeout(i),s(!1)}})},he=()=>(e,n)=>n.map(t=>({config:t,result:e})),de=(e,n={})=>{const{isMatch:t,getParamsFromRequest:r,mergeParamsToRequest:s}=e,{fetchCheck:i=le(300),distributeResult:o=he()}=n,l=[],w=d=>d.map(g=>g.config);return(d,g)=>t(d)?new m.Observable(p=>{const h=r(d);l.push({next:f=>p.next(f),error:f=>p.error(f),config:h});const y=w(l);i(d).then(f=>{if(f){const I=[];y.forEach(u=>{const b=l.findIndex(E=>E.config===u);if(b>=0){const[E]=l.splice(b,1);I.push(E)}}),g(s(y,d)).subscribe({next:u=>{if(u.type===U.Response){const b=u.body,E=o(b,y);I.forEach(M=>{const W=E.find($=>$.config===M.config);if(W){const $=new N({body:W.result,headers:u.headers,status:u.status,statusText:u.statusText});M.next($)}else M.error("batch error")})}},complete:()=>p.complete(),error:u=>p.error(u)})}})}):g(d)},pe=3,ue=1e3,ge=e=>{var r,s;const n=(r=e==null?void 0:e.maxRetryAttempts)!=null?r:pe,t=(s=e==null?void 0:e.delayInterval)!=null?s:ue;return(i,o)=>o(i).pipe(_.retry({delay:t,count:n}))},fe=e=>{const n=[],t=new Set,r=()=>{var s;for(;t.size<((s=e==null?void 0:e.maxParallel)!=null?s:1)&&n.length>0;){const i=n.shift();t.add(i),i()}};return(s,i)=>new m.Observable(o=>{const l=()=>i(s).subscribe({next:d=>o.next(d),error:d=>o.error(d),complete:()=>o.complete()}),w=()=>{t.delete(l),a.remove(n,l),r()};return n.push(l),r(),w})},me=a.createIdentifier("univer.network.socket.service");class ye extends a.Disposable{createSocket(n){try{const t=new WebSocket(n),r=new a.DisposableCollection;return{URL:n,close:(i,o)=>{t.close(i,o),r.dispose()},send:i=>{t.send(i)},open$:new m.Observable(i=>{const o=l=>i.next(l);t.addEventListener("open",o),r.add(a.toDisposable(()=>t.removeEventListener("open",o)))}).pipe(_.share()),close$:new m.Observable(i=>{const o=l=>i.next(l);t.addEventListener("close",o),r.add(a.toDisposable(()=>t.removeEventListener("close",o)))}).pipe(_.share()),error$:new m.Observable(i=>{const o=l=>i.next(l);t.addEventListener("error",o),r.add(a.toDisposable(()=>t.removeEventListener("error",o)))}).pipe(_.share()),message$:new m.Observable(i=>{const o=l=>i.next(l);t.addEventListener("message",o),r.add(a.toDisposable(()=>t.removeEventListener("message",o)))}).pipe(_.share())}}catch(t){return console.error(t),null}}}c.AuthInterceptorFactory=ae,c.HTTPEventType=U,c.HTTPHeaders=L,c.HTTPProgress=B,c.HTTPRequest=A,c.HTTPResponse=N,c.HTTPResponseError=R,c.HTTPStatusCode=F,c.IHTTPImplementation=O,c.ISocketService=me,c.MergeInterceptorFactory=de,c.ResponseHeader=G,c.RetryInterceptorFactory=ge,c.ThresholdInterceptorFactory=fe,c.WebSocketService=ye,Object.defineProperty(c,Symbol.toStringTag,{value:"Module"})});
|
|
1
|
+
(function(c,a){typeof exports=="object"&&typeof module<"u"?a(exports,require("@univerjs/core"),require("rxjs"),require("rxjs/operators")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","rxjs","rxjs/operators"],a):(c=typeof globalThis<"u"?globalThis:c||self,a(c.UniverNetwork={},c.UniverCore,c.rxjs,c.rxjs.operators))})(this,(function(c,a,m,_){"use strict";var we=Object.defineProperty;var ve=(c,a,m)=>a in c?we(c,a,{enumerable:!0,configurable:!0,writable:!0,value:m}):c[a]=m;var v=(c,a,m)=>ve(c,typeof a!="symbol"?a+"":a,m);var q;const V="network.config",j={},k="application/json";function J(e){return Array.isArray(e)?e.some(n=>n.includes(k)):e.includes(k)}class L{constructor(n){v(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((t,r)=>n(r,t))}has(n){return!!this._headers.has(n.toLowerCase())}get(n){const t=n.toLowerCase();return this._headers.has(t)?this._headers.get(t):null}set(n,t){this._setHeader(n,t)}toHeadersInit(n){var r,s;const t={};return this._headers.forEach((i,o)=>{t[o]=i.join(",")}),(r=t.accept)!=null||(t.accept="application/json, text/plain, */*"),n instanceof FormData||(s=t["content-type"])!=null||(t["content-type"]="application/json;charset=UTF-8"),t}_setHeader(n,t){const r=n.toLowerCase();this._headers.has(r)?this._headers.get(r).push(t.toString()):this._headers.set(r,[t.toString()])}_handleHeadersString(n){n.split(`
|
|
2
|
+
`).forEach(t=>{const[r,s]=t.split(":");r&&s&&this._setHeader(r,s)})}_handleHeadersConstructorProps(n){Object.entries(n).forEach(([t,r])=>this._setHeader(t,r))}_handleHeaders(n){n.forEach((t,r)=>this._setHeader(r,t))}}const O=a.createIdentifier("network.http-implementation");class x{constructor(n){this.params=n}toString(){return this.params?Object.keys(this.params).map(n=>{const t=this.params[n];return Array.isArray(t)?t.map(r=>`${n}=${r}`).join("&"):`${n}=${t}`}).join("&"):""}}let K=0;class A{constructor(n,t,r){v(this,"uid",K++);this.method=n,this.url=t,this.requestParams=r}get headers(){return this.requestParams.headers}get withCredentials(){return this.requestParams.withCredentials}get responseType(){return this.requestParams.responseType}getUrlWithParams(){var t,r;const n=(r=(t=this.requestParams)==null?void 0:t.params)==null?void 0:r.toString();return n?`${this.url}${this.url.includes("?")?"&":"?"}${n}`:this.url}getBody(){var r,s;const n=(r=this.headers.get("Content-Type"))!=null?r:k,t=(s=this.requestParams)==null?void 0:s.body;return t instanceof FormData?t:J(n)&&t&&typeof t=="object"?JSON.stringify(t):t?`${t}`:null}getHeadersInit(){var t;return this.headers.toHeadersInit((t=this.requestParams)==null?void 0:t.body)}}var z=Object.getOwnPropertyDescriptor,Y=(e,n,t,r)=>{for(var s=r>1?void 0:r?z(n,t):n,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=o(s)||s);return s},P=(e,n)=>(t,r)=>n(t,r,e);c.HTTPService=class extends a.Disposable{constructor(t){super();v(this,"_interceptors",[]);v(this,"_pipe");this._http=t}registerHTTPInterceptor(t){if(this._interceptors.indexOf(t)!==-1)throw new Error("[HTTPService]: The interceptor has already been registered!");return this._interceptors.push(t),this._interceptors=this._interceptors.sort((r,s)=>{var i,o;return((i=r.priority)!=null?i:0)-((o=s.priority)!=null?o:0)}),this._pipe=null,a.toDisposable(()=>a.remove(this._interceptors,t))}get(t,r){return this.request("GET",t,r)}post(t,r){return this.request("POST",t,r)}put(t,r){return this.request("PUT",t,r)}delete(t,r){return this.request("DELETE",t,r)}patch(t,r){return this.request("PATCH",t,r)}async request(t,r,s){var f,p;const i=new L(s==null?void 0:s.headers),o=new x(s==null?void 0:s.params),l=new A(t,r,{headers:i,params:o,withCredentials:(f=s==null?void 0:s.withCredentials)!=null?f:!1,responseType:(p=s==null?void 0:s.responseType)!=null?p:"json",body:["GET","DELETE"].includes(t)||s==null?void 0:s.body}),w=m.of(l).pipe(_.concatMap(h=>this._runInterceptorsAndImplementation(h)));return await m.firstValueFrom(w)}stream(t,r,s){return this.getSSE(t,r,s)}getSSE(t,r,s){var w,d;const i=new L(s==null?void 0:s.headers),o=new x(s==null?void 0:s.params),l=new A(t,r,{headers:i,params:o,withCredentials:(w=s==null?void 0:s.withCredentials)!=null?w:!1,reportProgress:!0,responseType:(d=s==null?void 0:s.responseType)!=null?d:"json",body:["GET","DELETE"].includes(t)||s==null?void 0:s.body});return m.of(l).pipe(_.concatMap(f=>this._runInterceptorsAndImplementation(f)))}_runInterceptorsAndImplementation(t){return this._pipe||(this._pipe=this._interceptors.map(r=>r.interceptor).reduceRight((r,s)=>Q(r,s),(r,s)=>s(r))),this._pipe(t,r=>this._http.send(r))}},c.HTTPService=Y([P(0,O)],c.HTTPService);function Q(e,n){return(t,r)=>n(t,s=>e(s,r))}const Z=200,H=300;var F=(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))(F||{}),U=(e=>(e[e.DownloadProgress=0]="DownloadProgress",e[e.Response=1]="Response",e))(U||{});class N{constructor({body:n,headers:t,status:r,statusText:s}){v(this,"type",1);v(this,"body");v(this,"headers");v(this,"status");v(this,"statusText");this.body=n,this.headers=t,this.status=r,this.statusText=s}}class B{constructor(n,t,r){v(this,"type",0);this.total=n,this.loaded=t,this.partialText=r}}class G{constructor(n,t,r){this.headers=n,this.status=t,this.statusText=r}}class R{constructor({request:n,headers:t,status:r,statusText:s,error:i}){v(this,"request");v(this,"headers");v(this,"status");v(this,"statusText");v(this,"error");this.request=n,this.headers=t,this.status=r,this.statusText=s,this.error=i}}function X(e){return{method:e.method,headers:e.getHeadersInit(),body:e.getBody(),credentials:e.withCredentials?"include":void 0}}var S=Object.getOwnPropertyDescriptor,C=(e,n,t,r)=>{for(var s=r>1?void 0:r?S(n,t):n,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=o(s)||s);return s},T=(e,n)=>(t,r)=>n(t,r,e);c.FetchHTTPImplementation=class{constructor(n){this._logService=n}send(n){return new m.Observable(t=>{const r=new AbortController;return this._send(n,t,r).catch(s=>{t.error(new R({error:s,request:n}))}),()=>r.abort()})}async _send(n,t,r){var f,p;let s;try{const h=X(n),y=n.getUrlWithParams(),g=fetch(y,{signal:r.signal,...h});this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${y} with params ${h}`),s=await g}catch(h){const y=new R({request:n,error:h,status:(f=h.status)!=null?f:0,statusText:(p=h.statusText)!=null?p:"Unknown Error",headers:h.headers});this._logService.error("[FetchHTTPImplementation]: network error",y),t.error(y);return}const i=new L(s.headers),o=s.status,l=s.statusText;let w=null;if(s.body&&(w=await this._readBody(n,s,t)),o>=F.Ok&&o<F.MultipleChoices)t.next(new N({body:w,headers:i,status:o,statusText:l}));else{const h=new R({request:n,error:w,status:o,statusText:l,headers:i});this._logService.error("[FetchHTTPImplementation]: network error",h),t.error(h)}t.complete()}async _readBody(n,t,r){var y,g;const s=[],i=t.body.getReader(),o=t.headers.get("content-length");let l=0;const w=(y=n.requestParams)==null?void 0:y.reportProgress,d=n.responseType;let f,p;for(;;){const{done:I,value:u}=await i.read();if(I)break;s.push(u),l+=u.length,w&&d==="text"&&(f=(f!=null?f:"")+(p!=null?p:p=new TextDecoder).decode(u,{stream:!0}),r.next(new B(o?Number.parseInt(o,10):void 0,l,f)))}const h=ee(s,l);try{const I=(g=t.headers.get("content-type"))!=null?g:"";return re(n,h,I)}catch(I){const u=new R({request:n,error:I,status:t.status,statusText:t.statusText,headers:new L(t.headers)});return this._logService.error("[FetchHTTPImplementation]: network error",u),r.error(u),null}}},c.FetchHTTPImplementation=C([T(0,a.ILogService)],c.FetchHTTPImplementation);function ee(e,n){const t=new Uint8Array(n);let r=0;for(const s of e)t.set(s,r),r+=s.length;return t}const te=/^\)\]\}',?\n/;function re(e,n,t){switch(e.responseType){case"json":const r=new TextDecoder().decode(n).replace(te,"");return r===""?null:JSON.parse(r);case"text":return new TextDecoder().decode(n);case"blob":return new Blob([n.buffer],{type:t});case"arraybuffer":return n.buffer;default:throw new Error(`[FetchHTTPImplementation]: unknown response type: ${e.responseType}.`)}}var ne=Object.getOwnPropertyDescriptor,se=(e,n,t,r)=>{for(var s=r>1?void 0:r?ne(n,t):n,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=o(s)||s);return s},ie=(e,n)=>(t,r)=>n(t,r,e);c.XHRHTTPImplementation=class{constructor(n){this._logService=n}send(n){return new m.Observable(t=>{const r=new XMLHttpRequest,s=n.getUrlWithParams(),i=X(n),{responseType:o}=n;r.open(n.method,s),n.withCredentials&&(r.withCredentials=!0),i.headers&&Object.entries(i.headers).forEach(([p,h])=>r.setRequestHeader(p,h));const l=()=>{const p=r.statusText||"OK",h=new L(r.getAllResponseHeaders());return new G(h,r.status,p)},w=()=>{const{headers:p,statusText:h,status:y}=l();let g=null,I=null;y!==F.NoContent&&(g=typeof r.response>"u"?r.responseText:r.response);let u=y>=Z&&y<H;if(o==="json"&&typeof g=="string"){const b=g;try{g=g?JSON.parse(g):null}catch(E){u=!1,g=b,I=E}}if(o==="blob"&&!(g instanceof Blob)&&(u=!1,I=new Error("Response is not a Blob object")),u)t.next(new N({body:g,headers:p,status:y,statusText:h}));else{const b=new R({request:n,error:I,headers:p,status:y,statusText:h});this._logService.error("[XHRHTTPImplementation]: network error",b),t.error(b)}},d=p=>{const h=new R({request:n,error:p,status:r.status||0,statusText:r.statusText||"Unknown Error",headers:l().headers});this._logService.error("[XHRHTTPImplementation]: network error",h),t.error(h)};r.responseType=o||"",r.addEventListener("load",w),r.addEventListener("error",d),r.addEventListener("abort",d),r.addEventListener("timeout",d);const f=n.getBody();return r.send(f),this._logService.debug("[XHRHTTPImplementation]",`sending request to url ${s} with params ${i}`),()=>{r.readyState!==r.DONE&&r.abort(),r.removeEventListener("load",w),r.removeEventListener("error",d),r.removeEventListener("abort",d),r.removeEventListener("timeout",d)}})}},c.XHRHTTPImplementation=se([ie(0,a.ILogService)],c.XHRHTTPImplementation);var oe=Object.getOwnPropertyDescriptor,ce=(e,n,t,r)=>{for(var s=r>1?void 0:r?oe(n,t):n,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=o(s)||s);return s},D=(e,n)=>(t,r)=>n(t,r,e);c.UniverNetworkPlugin=(q=class extends a.Plugin{constructor(n=j,t,r,s){super(),this._config=n,this._logger=t,this._injector=r,this._configService=s;const{...i}=a.merge({},j,this._config);this._configService.setConfig(V,i)}onStarting(){var r,s,i;if(this._injector.get(c.HTTPService,a.Quantity.OPTIONAL,a.LookUp.SKIP_SELF)&&!((r=this._config)!=null&&r.forceUseNewInstance)){this._logger.warn("[UniverNetworkPlugin]",'HTTPService is already registered in an ancestor interceptor. Skipping registration. If you want to force a new instance, set "forceUseNewInstance" to true in the plugin configuration.');return}const t=(s=this._config)!=null&&s.useFetchImpl?c.FetchHTTPImplementation:typeof window<"u"?c.XHRHTTPImplementation:c.FetchHTTPImplementation;a.registerDependencies(this._injector,a.mergeOverrideWithDependencies([[c.HTTPService],[O,{useClass:t}]],(i=this._config)==null?void 0:i.override))}},v(q,"pluginName","UNIVER_NETWORK_PLUGIN"),q),c.UniverNetworkPlugin=ce([D(1,a.ILogService),D(2,a.Inject(a.Injector)),D(3,a.IConfigService)],c.UniverNetworkPlugin);const ae=e=>{const{errorStatusCodes:n,onAuthError:t}=e;return(s,i)=>i(s).pipe(m.catchError(o=>(o instanceof R&&n.some(l=>l===o.status)&&t(),m.throwError(()=>o))))},le=(e=300)=>{let t=()=>{};return r=>new Promise(s=>{t();const i=setTimeout(()=>{s(!0)},e);t=()=>{clearTimeout(i),s(!1)}})},he=()=>(e,n)=>n.map(t=>({config:t,result:e})),de=(e,n={})=>{const{isMatch:t,getParamsFromRequest:r,mergeParamsToRequest:s}=e,{fetchCheck:i=le(300),distributeResult:o=he()}=n,l=[],w=d=>d.map(f=>f.config);return(d,f)=>t(d)?new m.Observable(p=>{const h=r(d);l.push({next:g=>p.next(g),error:g=>p.error(g),config:h});const y=w(l);i(d).then(g=>{if(g){const I=[];y.forEach(u=>{const b=l.findIndex(E=>E.config===u);if(b>=0){const[E]=l.splice(b,1);I.push(E)}}),f(s(y,d)).subscribe({next:u=>{if(u.type===U.Response){const b=u.body,E=o(b,y);I.forEach(M=>{const W=E.find($=>$.config===M.config);if(W){const $=new N({body:W.result,headers:u.headers,status:u.status,statusText:u.statusText});M.next($)}else M.error("batch error")})}},complete:()=>p.complete(),error:u=>p.error(u)})}})}):f(d)},pe=3,ue=1e3,fe=e=>{var r,s;const n=(r=e==null?void 0:e.maxRetryAttempts)!=null?r:pe,t=(s=e==null?void 0:e.delayInterval)!=null?s:ue;return(i,o)=>o(i).pipe(_.retry({delay:t,count:n}))},ge=e=>{const n=[],t=new Set,r=()=>{var s;for(;t.size<((s=e==null?void 0:e.maxParallel)!=null?s:1)&&n.length>0;){const i=n.shift();t.add(i),i()}};return(s,i)=>new m.Observable(o=>{const l=()=>i(s).subscribe({next:d=>o.next(d),error:d=>o.error(d),complete:()=>o.complete()}),w=()=>{t.delete(l),a.remove(n,l),r()};return n.push(l),r(),w})},me=a.createIdentifier("univer.network.socket.service");class ye extends a.Disposable{createSocket(n){try{const t=new WebSocket(n),r=new a.DisposableCollection;return{URL:n,close:(i,o)=>{t.close(i,o),r.dispose()},send:i=>{t.send(i)},open$:new m.Observable(i=>{const o=l=>i.next(l);t.addEventListener("open",o),r.add(a.toDisposable(()=>t.removeEventListener("open",o)))}).pipe(_.share()),close$:new m.Observable(i=>{const o=l=>i.next(l);t.addEventListener("close",o),r.add(a.toDisposable(()=>t.removeEventListener("close",o)))}).pipe(_.share()),error$:new m.Observable(i=>{const o=l=>i.next(l);t.addEventListener("error",o),r.add(a.toDisposable(()=>t.removeEventListener("error",o)))}).pipe(_.share()),message$:new m.Observable(i=>{const o=l=>i.next(l);t.addEventListener("message",o),r.add(a.toDisposable(()=>t.removeEventListener("message",o)))}).pipe(_.share())}}catch(t){return console.error(t),null}}}c.AuthInterceptorFactory=ae,c.HTTPEventType=U,c.HTTPHeaders=L,c.HTTPProgress=B,c.HTTPRequest=A,c.HTTPResponse=N,c.HTTPResponseError=R,c.HTTPStatusCode=F,c.IHTTPImplementation=O,c.ISocketService=me,c.MergeInterceptorFactory=de,c.ResponseHeader=G,c.RetryInterceptorFactory=fe,c.ThresholdInterceptorFactory=ge,c.WebSocketService=ye,Object.defineProperty(c,Symbol.toStringTag,{value:"Module"})}));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@univerjs/network",
|
|
3
|
-
"version": "0.10.
|
|
3
|
+
"version": "0.10.4-nightly.202508220605",
|
|
4
4
|
"private": false,
|
|
5
5
|
"author": "DreamNum <developer@univer.ai>",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -57,14 +57,14 @@
|
|
|
57
57
|
"rxjs": ">=7.0.0"
|
|
58
58
|
},
|
|
59
59
|
"dependencies": {
|
|
60
|
-
"@univerjs/core": "0.10.
|
|
60
|
+
"@univerjs/core": "0.10.4-nightly.202508220605"
|
|
61
61
|
},
|
|
62
62
|
"devDependencies": {
|
|
63
63
|
"rxjs": "^7.8.2",
|
|
64
|
-
"typescript": "^5.
|
|
65
|
-
"vite": "^7.
|
|
64
|
+
"typescript": "^5.9.2",
|
|
65
|
+
"vite": "^7.1.3",
|
|
66
66
|
"vitest": "^3.2.4",
|
|
67
|
-
"@univerjs-infra/shared": "0.10.
|
|
67
|
+
"@univerjs-infra/shared": "0.10.4"
|
|
68
68
|
},
|
|
69
69
|
"scripts": {
|
|
70
70
|
"test": "vitest run",
|