@univerjs/network 0.5.1 → 0.5.2

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.
@@ -0,0 +1 @@
1
+ "use strict";const i=require("@univerjs/core"),o=require("@univerjs/network");var _=Object.defineProperty,u=Object.getOwnPropertyDescriptor,a=(t,e,r,c)=>{for(var s=c>1?void 0:c?u(e,r):e,n=t.length-1,h;n>=0;n--)(h=t[n])&&(s=(c?h(e,r,s):h(s))||s);return c&&s&&_(e,r,s),s},v=(t,e)=>(r,c)=>e(r,c,t);let p=class extends i.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,r){return this._httpService.getSSE(t,e,r)}};p=a([v(0,i.Inject(i.Injector)),v(1,i.Inject(o.HTTPService))],p);class S extends i.FUniver{getNetwork(){return this._injector.createInstance(p)}}i.FUniver.extend(S);
package/lib/cjs/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var G=Object.defineProperty;var W=(e,t,r)=>t in e?G(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var m=(e,t,r)=>W(e,typeof t!="symbol"?t+"":t,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("@univerjs/core"),f=require("rxjs"),b=require("rxjs/operators"),k="application/json";class R{constructor(t){m(this,"_headers",new Map);typeof t=="string"?this._handleHeadersString(t):t instanceof Headers?this._handleHeaders(t):t&&this._handleHeadersConstructorProps(t)}forEach(t){this._headers.forEach((r,n)=>t(n,r))}has(t){return!!this._headers.has(t.toLowerCase())}get(t){const r=t.toLowerCase();return this._headers.has(r)?this._headers.get(r):null}set(t,r){this._setHeader(t,r)}toHeadersInit(){var r,n;const t={};return this._headers.forEach((s,i)=>{t[i]=s.join(",")}),(r=t.accept)!=null||(t.accept="application/json, text/plain, */*"),(n=t["content-type"])!=null||(t["content-type"]="application/json;charset=UTF-8"),t}_setHeader(t,r){const n=t.toLowerCase();this._headers.has(n)?this._headers.get(n).push(r.toString()):this._headers.set(n,[r.toString()])}_handleHeadersString(t){t.split(`
2
- `).forEach(r=>{const[n,s]=r.split(":");n&&s&&this._setHeader(n,s)})}_handleHeadersConstructorProps(t){Object.entries(t).forEach(([r,n])=>this._setHeader(r,n))}_handleHeaders(t){t.forEach((r,n)=>this._setHeader(n,r))}}const O=d.createIdentifier("network.http-implementation");class M{constructor(t){this.params=t}toString(){return this.params?Object.keys(this.params).map(t=>`${t}=${this.params[t]}`).join("&"):""}}let V=0;class U{constructor(t,r,n){m(this,"uid",V++);this.method=t,this.url=r,this.requestParams=n}get headers(){return this.requestParams.headers}get withCredentials(){return this.requestParams.withCredentials}get responseType(){return this.requestParams.responseType}getUrlWithParams(){var r,n;const t=(n=(r=this.requestParams)==null?void 0:r.params)==null?void 0:n.toString();return t?`${this.url}${this.url.includes("?")?"&":"?"}${t}`:this.url}getBody(){var n,s;const t=(n=this.headers.get("Content-Type"))!=null?n:k,r=(s=this.requestParams)==null?void 0:s.body;return t===k&&r&&typeof r=="object"?JSON.stringify(r):r?`${r}`:null}getHeadersInit(){return this.headers.toHeadersInit()}}var X=Object.defineProperty,z=Object.getOwnPropertyDescriptor,J=(e,t,r,n)=>{for(var s=n>1?void 0:n?z(t,r):t,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=(n?o(t,r,s):o(s))||s);return n&&s&&X(t,r,s),s},K=(e,t)=>(r,n)=>t(r,n,e);exports.HTTPService=class extends d.Disposable{constructor(r){super();m(this,"_interceptors",[]);m(this,"_pipe");this._http=r}registerHTTPInterceptor(r){if(this._interceptors.indexOf(r)!==-1)throw new Error("[HTTPService]: The interceptor has already been registered!");return this._interceptors.push(r),this._interceptors=this._interceptors.sort((n,s)=>{var i,o;return((i=n.priority)!=null?i:0)-((o=s.priority)!=null?o:0)}),this._pipe=null,d.toDisposable(()=>d.remove(this._interceptors,r))}get(r,n){return this._request("GET",r,n)}post(r,n){return this._request("POST",r,n)}put(r,n){return this._request("PUT",r,n)}delete(r,n){return this._request("DELETE",r,n)}patch(r,n){return this._request("PATCH",r,n)}getSSE(r,n,s){var h,a;const i=new R(s==null?void 0:s.headers),o=new M(s==null?void 0:s.params),c=new U(r,n,{headers:i,params:o,withCredentials:(h=s==null?void 0:s.withCredentials)!=null?h:!1,reportProgress:!0,responseType:(a=s==null?void 0:s.responseType)!=null?a:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body});return f.of(c).pipe(b.concatMap(l=>this._runInterceptorsAndImplementation(l)))}async _request(r,n,s){var l,u;const i=new R(s==null?void 0:s.headers),o=new M(s==null?void 0:s.params),c=new U(r,n,{headers:i,params:o,withCredentials:(l=s==null?void 0:s.withCredentials)!=null?l:!1,responseType:(u=s==null?void 0:s.responseType)!=null?u:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body}),h=f.of(c).pipe(b.concatMap(p=>this._runInterceptorsAndImplementation(p)));return await f.firstValueFrom(h)}_runInterceptorsAndImplementation(r){return this._pipe||(this._pipe=this._interceptors.map(n=>n.interceptor).reduceRight((n,s)=>Y(n,s),(n,s)=>s(n))),this._pipe(r,n=>this._http.send(n))}};exports.HTTPService=J([K(0,O)],exports.HTTPService);function Y(e,t){return(r,n)=>t(r,s=>e(s,n))}const Q=200,Z=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||{}),q=(e=>(e[e.DownloadProgress=0]="DownloadProgress",e[e.Response=1]="Response",e))(q||{});class L{constructor({body:t,headers:r,status:n,statusText:s}){m(this,"type",1);m(this,"body");m(this,"headers");m(this,"status");m(this,"statusText");this.body=t,this.headers=r,this.status=n,this.statusText=s}}class j{constructor(t,r,n){m(this,"type",0);this.total=t,this.loaded=r,this.partialText=n}}class ${constructor(t,r,n){this.headers=t,this.status=r,this.statusText=n}}class _{constructor({headers:t,status:r,statusText:n,error:s}){m(this,"headers");m(this,"status");m(this,"statusText");m(this,"error");this.headers=t,this.status=r,this.statusText=n,this.error=s}}class B{send(t){return new f.Observable(r=>{const n=new XMLHttpRequest;n.open(t.method,t.getUrlWithParams()),t.withCredentials&&(n.withCredentials=!0),t.headers.forEach((h,a)=>n.setRequestHeader(h,a.join(","))),t.headers.has("Accept")||n.setRequestHeader("Accept","application/json, text/plain, */*"),t.headers.has("Content-Type")||n.setRequestHeader("Content-Type","application/json;charset=UTF-8");const s=()=>{const h=n.statusText||"OK",a=new R(n.getAllResponseHeaders());return new $(a,n.status,h)},i=()=>{const{headers:h,statusText:a,status:l}=s(),{responseType:u}=t;let p=null,w=null;l!==I.NoContent&&(p=typeof n.response>"u"?n.responseText:n.response);let g=l>=Q&&l<Z;if(u==="json"&&typeof p=="string"){const v=p;try{p=p?JSON.parse(p):null}catch(y){g=!1,p=v,w=y}}g?r.next(new L({body:p,headers:h,status:l,statusText:a})):r.error(new _({error:w,headers:h,status:l,statusText:a}))},o=h=>{const a=new _({error:h,status:n.status||0,statusText:n.statusText||"Unknown Error",headers:s().headers});r.error(a)};n.addEventListener("load",i),n.addEventListener("error",o),n.addEventListener("abort",o),n.addEventListener("timeout",o);const c=t.getBody();return n.send(c),()=>{n.readyState!==n.DONE&&n.abort(),n.removeEventListener("load",i),n.removeEventListener("error",o),n.removeEventListener("abort",o),n.removeEventListener("timeout",o)}})}}var P=Object.defineProperty,H=Object.getOwnPropertyDescriptor,S=(e,t,r,n)=>{for(var s=n>1?void 0:n?H(t,r):t,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=(n?o(t,r,s):o(s))||s);return n&&s&&P(t,r,s),s},C=(e,t)=>(r,n)=>t(r,n,e),A;exports.UniverNetworkPlugin=(A=class extends d.Plugin{constructor(t=void 0,r){super(),this._config=t,this._injector=r}onStarting(){var t;d.registerDependencies(this._injector,d.mergeOverrideWithDependencies([[exports.HTTPService],[O,{useClass:B}]],(t=this._config)==null?void 0:t.override))}},m(A,"pluginName","UNIVER_NETWORK_PLUGIN"),A);exports.UniverNetworkPlugin=S([C(1,d.Inject(d.Injector))],exports.UniverNetworkPlugin);class T{send(t){return new f.Observable(r=>{const n=new AbortController;return this._send(t,r,n).then(()=>{},s=>{r.error(new _({error:s}))}),()=>n.abort()})}async _send(t,r,n){var l,u;let s;try{const p=this._parseFetchParamsFromRequest(t);s=await fetch(t.getUrlWithParams(),{signal:n.signal,...p})}catch(p){r.error(new _({error:p,status:(l=p.status)!=null?l:0,statusText:(u=p.statusText)!=null?u:"Unknown Error",headers:p.headers}));return}const i=new R(s.headers),o=s.status,c=s.statusText;let h=null;s.body&&(h=await this._readBody(t,s,r)),o>=I.Ok&&o<I.MultipleChoices?r.next(new L({body:h,headers:i,status:o,statusText:c})):r.error(new _({error:h,status:o,statusText:c,headers:i})),r.complete()}async _readBody(t,r,n){var w,g;const s=[],i=r.body.getReader(),o=r.headers.get("content-length");let c=0;const h=(w=t.requestParams)==null?void 0:w.reportProgress,a=t.responseType;let l,u;for(;;){const{done:v,value:y}=await i.read();if(v)break;s.push(y),c+=y.length,h&&a==="text"&&(l=(l!=null?l:"")+(u!=null?u:u=new TextDecoder).decode(y,{stream:!0}),n.next(new j(o?Number.parseInt(o,10):void 0,c,l)))}const p=ee(s,c);try{const v=(g=r.headers.get("content-type"))!=null?g:"";return te(t,p,v)}catch(v){return n.error(new _({error:v,status:r.status,statusText:r.statusText,headers:new R(r.headers)})),null}}_parseFetchParamsFromRequest(t){return{method:t.method,headers:t.getHeadersInit(),body:t.getBody(),credentials:t.withCredentials?"include":void 0}}}function ee(e,t){const r=new Uint8Array(t);let n=0;for(const s of e)r.set(s,n),n+=s.length;return r}const re=/^\)\]\}',?\n/;function te(e,t,r){switch(e.responseType){case"json":const n=new TextDecoder().decode(t).replace(re,"");return n===""?null:JSON.parse(n);case"text":return new TextDecoder().decode(t);case"blob":return new Blob([t],{type:r});case"arraybuffer":return t.buffer;default:throw new Error(`[FetchHTTPImplementation]: unknown response type: ${e.responseType}.`)}}const ne=d.createIdentifier("univer.socket");class se extends d.Disposable{createSocket(t){try{const r=new WebSocket(t),n=new d.DisposableCollection;return{URL:t,close:(i,o)=>{r.close(i,o),n.dispose()},send:i=>{r.send(i)},open$:new f.Observable(i=>{const o=c=>i.next(c);r.addEventListener("open",o),n.add(d.toDisposable(()=>r.removeEventListener("open",o)))}).pipe(b.share()),close$:new f.Observable(i=>{const o=c=>i.next(c);r.addEventListener("close",o),n.add(d.toDisposable(()=>r.removeEventListener("close",o)))}).pipe(b.share()),error$:new f.Observable(i=>{const o=c=>i.next(c);r.addEventListener("error",o),n.add(d.toDisposable(()=>r.removeEventListener("error",o)))}).pipe(b.share()),message$:new f.Observable(i=>{const o=c=>i.next(c);r.addEventListener("message",o),n.add(d.toDisposable(()=>r.removeEventListener("message",o)))}).pipe(b.share())}}catch(r){return console.error(r),null}}}const oe=3,ie=1e3,ce=e=>{var n,s;const t=(n=e==null?void 0:e.maxRetryAttempts)!=null?n:oe,r=(s=e==null?void 0:e.delayInterval)!=null?s:ie;return(i,o)=>o(i).pipe(b.retry({delay:r,count:t}))},ae=e=>{const t=[],r=new Set,n=()=>{var s;for(;r.size<((s=e==null?void 0:e.maxParallel)!=null?s:1)&&t.length>0;){const i=t.shift();r.add(i),i()}};return(s,i)=>new f.Observable(o=>{const c=()=>i(s).subscribe({next:a=>o.next(a),error:a=>o.error(a),complete:()=>o.complete()}),h=()=>{r.delete(c),d.remove(t,c),n()};return t.push(c),n(),h})},le=e=>{const{errorStatusCodes:t,onAuthError:r}=e;return(s,i)=>i(s).pipe(f.catchError(o=>(o instanceof _&&t.some(c=>c===o.status)&&r(),f.throwError(()=>o))))},he=(e=300)=>{let r=()=>{};return n=>new Promise(s=>{r();const i=setTimeout(()=>{s(!0)},e);r=()=>{clearTimeout(i),s(!1)}})},pe=()=>(e,t)=>t.map(r=>({config:r,result:e})),de=(e,t={})=>{const{isMatch:r,getParamsFromRequest:n,mergeParamsToRequest:s}=e,{fetchCheck:i=he(300),distributeResult:o=pe()}=t,c=[],h=a=>a.map(l=>l.config);return(a,l)=>r(a)?new f.Observable(u=>{const p=n(a);c.push({next:g=>u.next(g),error:g=>u.error(g),config:p});const w=h(c);i(a).then(g=>{if(g){const v=[];w.forEach(y=>{const x=c.findIndex(E=>E.config===y);if(x>=0){const[E]=c.splice(x,1);v.push(E)}}),l(s(w,a)).subscribe({next:y=>{if(y.type===q.Response){const x=y.body,E=o(x,w);v.forEach(N=>{const D=E.find(F=>F.config===N.config);if(D){const F=new L({body:D.result,headers:y.headers,status:y.status,statusText:y.statusText});N.next(F)}else N.error("batch error")})}},complete:()=>u.complete(),error:y=>u.error(y)})}})}):l(a)};exports.AuthInterceptorFactory=le;exports.FetchHTTPImplementation=T;exports.HTTPEventType=q;exports.HTTPHeaders=R;exports.HTTPProgress=j;exports.HTTPRequest=U;exports.HTTPResponse=L;exports.HTTPResponseError=_;exports.HTTPStatusCode=I;exports.IHTTPImplementation=O;exports.ISocketService=ne;exports.MergeInterceptorFactory=de;exports.ResponseHeader=$;exports.RetryInterceptorFactory=ce;exports.ThresholdInterceptorFactory=ae;exports.WebSocketService=se;exports.XHRHTTPImplementation=B;
1
+ "use strict";var G=Object.defineProperty;var W=(e,t,r)=>t in e?G(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var m=(e,t,r)=>W(e,typeof t!="symbol"?t+"":t,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("@univerjs/core"),w=require("rxjs"),R=require("rxjs/operators"),j="application/json";class E{constructor(t){m(this,"_headers",new Map);typeof t=="string"?this._handleHeadersString(t):t instanceof Headers?this._handleHeaders(t):t&&this._handleHeadersConstructorProps(t)}forEach(t){this._headers.forEach((r,n)=>t(n,r))}has(t){return!!this._headers.has(t.toLowerCase())}get(t){const r=t.toLowerCase();return this._headers.has(r)?this._headers.get(r):null}set(t,r){this._setHeader(t,r)}toHeadersInit(){var r,n;const t={};return this._headers.forEach((s,o)=>{t[o]=s.join(",")}),(r=t.accept)!=null||(t.accept="application/json, text/plain, */*"),(n=t["content-type"])!=null||(t["content-type"]="application/json;charset=UTF-8"),t}_setHeader(t,r){const n=t.toLowerCase();this._headers.has(n)?this._headers.get(n).push(r.toString()):this._headers.set(n,[r.toString()])}_handleHeadersString(t){t.split(`
2
+ `).forEach(r=>{const[n,s]=r.split(":");n&&s&&this._setHeader(n,s)})}_handleHeadersConstructorProps(t){Object.entries(t).forEach(([r,n])=>this._setHeader(r,n))}_handleHeaders(t){t.forEach((r,n)=>this._setHeader(n,r))}}const A=p.createIdentifier("network.http-implementation");class k{constructor(t){this.params=t}toString(){return this.params?Object.keys(this.params).map(t=>`${t}=${this.params[t]}`).join("&"):""}}let V=0;class U{constructor(t,r,n){m(this,"uid",V++);this.method=t,this.url=r,this.requestParams=n}get headers(){return this.requestParams.headers}get withCredentials(){return this.requestParams.withCredentials}get responseType(){return this.requestParams.responseType}getUrlWithParams(){var r,n;const t=(n=(r=this.requestParams)==null?void 0:r.params)==null?void 0:n.toString();return t?`${this.url}${this.url.includes("?")?"&":"?"}${t}`:this.url}getBody(){var n,s;const t=(n=this.headers.get("Content-Type"))!=null?n:j,r=(s=this.requestParams)==null?void 0:s.body;return t===j&&r&&typeof r=="object"?JSON.stringify(r):r?`${r}`:null}getHeadersInit(){return this.headers.toHeadersInit()}}var P=Object.defineProperty,z=Object.getOwnPropertyDescriptor,J=(e,t,r,n)=>{for(var s=n>1?void 0:n?z(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(n?i(t,r,s):i(s))||s);return n&&s&&P(t,r,s),s},K=(e,t)=>(r,n)=>t(r,n,e);exports.HTTPService=class extends p.Disposable{constructor(r){super();m(this,"_interceptors",[]);m(this,"_pipe");this._http=r}registerHTTPInterceptor(r){if(this._interceptors.indexOf(r)!==-1)throw new Error("[HTTPService]: The interceptor has already been registered!");return this._interceptors.push(r),this._interceptors=this._interceptors.sort((n,s)=>{var o,i;return((o=n.priority)!=null?o:0)-((i=s.priority)!=null?i:0)}),this._pipe=null,p.toDisposable(()=>p.remove(this._interceptors,r))}get(r,n){return this._request("GET",r,n)}post(r,n){return this._request("POST",r,n)}put(r,n){return this._request("PUT",r,n)}delete(r,n){return this._request("DELETE",r,n)}patch(r,n){return this._request("PATCH",r,n)}getSSE(r,n,s){var d,u;const o=new E(s==null?void 0:s.headers),i=new k(s==null?void 0:s.params),c=new U(r,n,{headers:o,params:i,withCredentials:(d=s==null?void 0:s.withCredentials)!=null?d:!1,reportProgress:!0,responseType:(u=s==null?void 0:s.responseType)!=null?u:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body});return w.of(c).pipe(R.concatMap(a=>this._runInterceptorsAndImplementation(a)))}async _request(r,n,s){var a,l;const o=new E(s==null?void 0:s.headers),i=new k(s==null?void 0:s.params),c=new U(r,n,{headers:o,params:i,withCredentials:(a=s==null?void 0:s.withCredentials)!=null?a:!1,responseType:(l=s==null?void 0:s.responseType)!=null?l:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body}),d=w.of(c).pipe(R.concatMap(h=>this._runInterceptorsAndImplementation(h)));return await w.firstValueFrom(d)}_runInterceptorsAndImplementation(r){return this._pipe||(this._pipe=this._interceptors.map(n=>n.interceptor).reduceRight((n,s)=>Y(n,s),(n,s)=>s(n))),this._pipe(r,n=>this._http.send(n))}};exports.HTTPService=J([K(0,A)],exports.HTTPService);function Y(e,t){return(r,n)=>t(r,s=>e(s,n))}const Q=200,Z=300;var x=(e=>(e[e.Continue=100]="Continue",e[e.SwitchingProtocols=101]="SwitchingProtocols",e[e.Processing=102]="Processing",e[e.EarlyHints=103]="EarlyHints",e[e.Ok=200]="Ok",e[e.Created=201]="Created",e[e.Accepted=202]="Accepted",e[e.NonAuthoritativeInformation=203]="NonAuthoritativeInformation",e[e.NoContent=204]="NoContent",e[e.ResetContent=205]="ResetContent",e[e.PartialContent=206]="PartialContent",e[e.MultiStatus=207]="MultiStatus",e[e.AlreadyReported=208]="AlreadyReported",e[e.ImUsed=226]="ImUsed",e[e.MultipleChoices=300]="MultipleChoices",e[e.MovedPermanently=301]="MovedPermanently",e[e.Found=302]="Found",e[e.SeeOther=303]="SeeOther",e[e.NotModified=304]="NotModified",e[e.UseProxy=305]="UseProxy",e[e.Unused=306]="Unused",e[e.TemporaryRedirect=307]="TemporaryRedirect",e[e.PermanentRedirect=308]="PermanentRedirect",e[e.BadRequest=400]="BadRequest",e[e.Unauthorized=401]="Unauthorized",e[e.PaymentRequired=402]="PaymentRequired",e[e.Forbidden=403]="Forbidden",e[e.NotFound=404]="NotFound",e[e.MethodNotAllowed=405]="MethodNotAllowed",e[e.NotAcceptable=406]="NotAcceptable",e[e.ProxyAuthenticationRequired=407]="ProxyAuthenticationRequired",e[e.RequestTimeout=408]="RequestTimeout",e[e.Conflict=409]="Conflict",e[e.Gone=410]="Gone",e[e.LengthRequired=411]="LengthRequired",e[e.PreconditionFailed=412]="PreconditionFailed",e[e.PayloadTooLarge=413]="PayloadTooLarge",e[e.UriTooLong=414]="UriTooLong",e[e.UnsupportedMediaType=415]="UnsupportedMediaType",e[e.RangeNotSatisfiable=416]="RangeNotSatisfiable",e[e.ExpectationFailed=417]="ExpectationFailed",e[e.ImATeapot=418]="ImATeapot",e[e.MisdirectedRequest=421]="MisdirectedRequest",e[e.UnprocessableEntity=422]="UnprocessableEntity",e[e.Locked=423]="Locked",e[e.FailedDependency=424]="FailedDependency",e[e.TooEarly=425]="TooEarly",e[e.UpgradeRequired=426]="UpgradeRequired",e[e.PreconditionRequired=428]="PreconditionRequired",e[e.TooManyRequests=429]="TooManyRequests",e[e.RequestHeaderFieldsTooLarge=431]="RequestHeaderFieldsTooLarge",e[e.UnavailableForLegalReasons=451]="UnavailableForLegalReasons",e[e.InternalServerError=500]="InternalServerError",e[e.NotImplemented=501]="NotImplemented",e[e.BadGateway=502]="BadGateway",e[e.ServiceUnavailable=503]="ServiceUnavailable",e[e.GatewayTimeout=504]="GatewayTimeout",e[e.HttpVersionNotSupported=505]="HttpVersionNotSupported",e[e.VariantAlsoNegotiates=506]="VariantAlsoNegotiates",e[e.InsufficientStorage=507]="InsufficientStorage",e[e.LoopDetected=508]="LoopDetected",e[e.NotExtended=510]="NotExtended",e[e.NetworkAuthenticationRequired=511]="NetworkAuthenticationRequired",e))(x||{}),D=(e=>(e[e.DownloadProgress=0]="DownloadProgress",e[e.Response=1]="Response",e))(D||{});class L{constructor({body:t,headers:r,status:n,statusText:s}){m(this,"type",1);m(this,"body");m(this,"headers");m(this,"status");m(this,"statusText");this.body=t,this.headers=r,this.status=n,this.statusText=s}}class M{constructor(t,r,n){m(this,"type",0);this.total=t,this.loaded=r,this.partialText=n}}class B{constructor(t,r,n){this.headers=t,this.status=r,this.statusText=n}}class I{constructor({request:t,headers:r,status:n,statusText:s,error:o}){m(this,"request");m(this,"headers");m(this,"status");m(this,"statusText");m(this,"error");this.request=t,this.headers=r,this.status=n,this.statusText=s,this.error=o}}function X(e){return{method:e.method,headers:e.getHeadersInit(),body:e.getBody(),credentials:e.withCredentials?"include":void 0}}var H=Object.defineProperty,S=Object.getOwnPropertyDescriptor,C=(e,t,r,n)=>{for(var s=n>1?void 0:n?S(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(n?i(t,r,s):i(s))||s);return n&&s&&H(t,r,s),s},T=(e,t)=>(r,n)=>t(r,n,e);exports.FetchHTTPImplementation=class{constructor(t){this._logService=t}send(t){return new w.Observable(r=>{const n=new AbortController;return this._send(t,r,n).catch(s=>{r.error(new I({error:s,request:t}))}),()=>n.abort()})}async _send(t,r,n){var a,l;let s;try{const h=X(t),y=t.getUrlWithParams(),f=fetch(y,{signal:n.signal,...h});this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${y} with params ${h}`),s=await f}catch(h){const y=new I({request:t,error:h,status:(a=h.status)!=null?a:0,statusText:(l=h.statusText)!=null?l:"Unknown Error",headers:h.headers});this._logService.error("[FetchHTTPImplementation]: network error",y),r.error(y);return}const o=new E(s.headers),i=s.status,c=s.statusText;let d=null;if(s.body&&(d=await this._readBody(t,s,r)),i>=x.Ok&&i<x.MultipleChoices)r.next(new L({body:d,headers:o,status:i,statusText:c}));else{const h=new I({request:t,error:d,status:i,statusText:c,headers:o});this._logService.error("[FetchHTTPImplementation]: network error",h),r.error(h)}r.complete()}async _readBody(t,r,n){var y,f;const s=[],o=r.body.getReader(),i=r.headers.get("content-length");let c=0;const d=(y=t.requestParams)==null?void 0:y.reportProgress,u=t.responseType;let a,l;for(;;){const{done:v,value:g}=await o.read();if(v)break;s.push(g),c+=g.length,d&&u==="text"&&(a=(a!=null?a:"")+(l!=null?l:l=new TextDecoder).decode(g,{stream:!0}),n.next(new M(i?Number.parseInt(i,10):void 0,c,a)))}const h=ee(s,c);try{const v=(f=r.headers.get("content-type"))!=null?f:"";return te(t,h,v)}catch(v){const g=new I({request:t,error:v,status:r.status,statusText:r.statusText,headers:new E(r.headers)});return this._logService.error("[FetchHTTPImplementation]: network error",g),n.error(g),null}}};exports.FetchHTTPImplementation=C([T(0,p.ILogService)],exports.FetchHTTPImplementation);function ee(e,t){const r=new Uint8Array(t);let n=0;for(const s of e)r.set(s,n),n+=s.length;return r}const re=/^\)\]\}',?\n/;function te(e,t,r){switch(e.responseType){case"json":const n=new TextDecoder().decode(t).replace(re,"");return n===""?null:JSON.parse(n);case"text":return new TextDecoder().decode(t);case"blob":return new Blob([t],{type:r});case"arraybuffer":return t.buffer;default:throw new Error(`[FetchHTTPImplementation]: unknown response type: ${e.responseType}.`)}}var ne=Object.defineProperty,se=Object.getOwnPropertyDescriptor,oe=(e,t,r,n)=>{for(var s=n>1?void 0:n?se(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(n?i(t,r,s):i(s))||s);return n&&s&&ne(t,r,s),s},ie=(e,t)=>(r,n)=>t(r,n,e);exports.XHRHTTPImplementation=class{constructor(t){this._logService=t}send(t){return new w.Observable(r=>{const n=new XMLHttpRequest,s=t.getUrlWithParams(),o=X(t);n.open(t.method,s),t.withCredentials&&(n.withCredentials=!0),o.headers&&Object.entries(o.headers).forEach(([a,l])=>n.setRequestHeader(a,l));const i=()=>{const a=n.statusText||"OK",l=new E(n.getAllResponseHeaders());return new B(l,n.status,a)},c=()=>{const{headers:a,statusText:l,status:h}=i(),{responseType:y}=t;let f=null,v=null;h!==x.NoContent&&(f=typeof n.response>"u"?n.responseText:n.response);let g=h>=Q&&h<Z;if(y==="json"&&typeof f=="string"){const b=f;try{f=f?JSON.parse(f):null}catch(_){g=!1,f=b,v=_}}if(g)r.next(new L({body:f,headers:a,status:h,statusText:l}));else{const b=new I({request:t,error:v,headers:a,status:h,statusText:l});this._logService.error("[XHRHTTPImplementation]: network error",b),r.error(b)}},d=a=>{const l=new I({request:t,error:a,status:n.status||0,statusText:n.statusText||"Unknown Error",headers:i().headers});this._logService.error("[XHRHTTPImplementation]: network error",l),r.error(l)};n.addEventListener("load",c),n.addEventListener("error",d),n.addEventListener("abort",d),n.addEventListener("timeout",d);const u=t.getBody();return n.send(u),this._logService.debug(`[XHRHTTPImplementation]: sending request to url ${s} with params ${o}`),()=>{n.readyState!==n.DONE&&n.abort(),n.removeEventListener("load",c),n.removeEventListener("error",d),n.removeEventListener("abort",d),n.removeEventListener("timeout",d)}})}};exports.XHRHTTPImplementation=oe([ie(0,p.ILogService)],exports.XHRHTTPImplementation);var ce=Object.defineProperty,ae=Object.getOwnPropertyDescriptor,le=(e,t,r,n)=>{for(var s=n>1?void 0:n?ae(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(n?i(t,r,s):i(s))||s);return n&&s&&ce(t,r,s),s},$=(e,t)=>(r,n)=>t(r,n,e),N;exports.UniverNetworkPlugin=(N=class extends p.Plugin{constructor(t=void 0,r,n){super(),this._config=t,this._logger=r,this._injector=n}onStarting(){var n,s,o;if(this._injector.get(exports.HTTPService,p.Quantity.OPTIONAL,p.LookUp.SKIP_SELF)&&!((n=this._config)!=null&&n.forceUseNewInstance)){this._logger.warn("[UniverNetworkPlugin]",'HTTPService is already registered in an ancestor interceptor. Skipping registration. If you want to force a new instance, set "forceUseNewInstance" to true in the plugin configuration.');return}const r=(s=this._config)!=null&&s.useFetchImpl?exports.FetchHTTPImplementation:typeof window<"u"?exports.XHRHTTPImplementation:exports.FetchHTTPImplementation;p.registerDependencies(this._injector,p.mergeOverrideWithDependencies([[exports.HTTPService],[A,{useClass:r}]],(o=this._config)==null?void 0:o.override))}},m(N,"pluginName","UNIVER_NETWORK_PLUGIN"),N);exports.UniverNetworkPlugin=le([$(1,p.ILogService),$(2,p.Inject(p.Injector))],exports.UniverNetworkPlugin);const he=p.createIdentifier("univer.network.socket.service");class pe extends p.Disposable{createSocket(t){try{const r=new WebSocket(t),n=new p.DisposableCollection;return{URL:t,close:(o,i)=>{r.close(o,i),n.dispose()},send:o=>{r.send(o)},open$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("open",i),n.add(p.toDisposable(()=>r.removeEventListener("open",i)))}).pipe(R.share()),close$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("close",i),n.add(p.toDisposable(()=>r.removeEventListener("close",i)))}).pipe(R.share()),error$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("error",i),n.add(p.toDisposable(()=>r.removeEventListener("error",i)))}).pipe(R.share()),message$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("message",i),n.add(p.toDisposable(()=>r.removeEventListener("message",i)))}).pipe(R.share())}}catch(r){return console.error(r),null}}}const de=3,ue=1e3,ge=e=>{var n,s;const t=(n=e==null?void 0:e.maxRetryAttempts)!=null?n:de,r=(s=e==null?void 0:e.delayInterval)!=null?s:ue;return(o,i)=>i(o).pipe(R.retry({delay:r,count:t}))},fe=e=>{const t=[],r=new Set,n=()=>{var s;for(;r.size<((s=e==null?void 0:e.maxParallel)!=null?s:1)&&t.length>0;){const o=t.shift();r.add(o),o()}};return(s,o)=>new w.Observable(i=>{const c=()=>o(s).subscribe({next:u=>i.next(u),error:u=>i.error(u),complete:()=>i.complete()}),d=()=>{r.delete(c),p.remove(t,c),n()};return t.push(c),n(),d})},me=e=>{const{errorStatusCodes:t,onAuthError:r}=e;return(s,o)=>o(s).pipe(w.catchError(i=>(i instanceof I&&t.some(c=>c===i.status)&&r(),w.throwError(()=>i))))},ye=(e=300)=>{let r=()=>{};return n=>new Promise(s=>{r();const o=setTimeout(()=>{s(!0)},e);r=()=>{clearTimeout(o),s(!1)}})},we=()=>(e,t)=>t.map(r=>({config:r,result:e})),ve=(e,t={})=>{const{isMatch:r,getParamsFromRequest:n,mergeParamsToRequest:s}=e,{fetchCheck:o=ye(300),distributeResult:i=we()}=t,c=[],d=u=>u.map(a=>a.config);return(u,a)=>r(u)?new w.Observable(l=>{const h=n(u);c.push({next:f=>l.next(f),error:f=>l.error(f),config:h});const y=d(c);o(u).then(f=>{if(f){const v=[];y.forEach(g=>{const b=c.findIndex(_=>_.config===g);if(b>=0){const[_]=c.splice(b,1);v.push(_)}}),a(s(y,u)).subscribe({next:g=>{if(g.type===D.Response){const b=g.body,_=i(b,y);v.forEach(F=>{const q=_.find(O=>O.config===F.config);if(q){const O=new L({body:q.result,headers:g.headers,status:g.status,statusText:g.statusText});F.next(O)}else F.error("batch error")})}},complete:()=>l.complete(),error:g=>l.error(g)})}})}):a(u)};exports.AuthInterceptorFactory=me;exports.HTTPEventType=D;exports.HTTPHeaders=E;exports.HTTPProgress=M;exports.HTTPRequest=U;exports.HTTPResponse=L;exports.HTTPResponseError=I;exports.HTTPStatusCode=x;exports.IHTTPImplementation=A;exports.ISocketService=he;exports.MergeInterceptorFactory=ve;exports.ResponseHeader=B;exports.RetryInterceptorFactory=ge;exports.ThresholdInterceptorFactory=fe;exports.WebSocketService=pe;
@@ -0,0 +1,78 @@
1
+ import { Inject as h, Injector as _, FBase as u, FUniver as v } from "@univerjs/core";
2
+ import { HTTPService as a } from "@univerjs/network";
3
+ var S = Object.defineProperty, l = Object.getOwnPropertyDescriptor, f = (t, e, r, s) => {
4
+ for (var i = s > 1 ? void 0 : s ? l(e, r) : e, c = t.length - 1, n; c >= 0; c--)
5
+ (n = t[c]) && (i = (s ? n(e, r, i) : n(i)) || i);
6
+ return s && i && S(e, r, i), i;
7
+ }, o = (t, e) => (r, s) => e(r, s, t);
8
+ let p = class extends u {
9
+ constructor(t, e) {
10
+ super(), this._injector = t, this._httpService = e;
11
+ }
12
+ /**
13
+ * Send GET request to the server.
14
+ * @param url The requested URL
15
+ * @param params Query parameters
16
+ * @returns Network response
17
+ */
18
+ get(t, e) {
19
+ return this._httpService.get(t, e);
20
+ }
21
+ /**
22
+ * Send POST request to the server.
23
+ * @param url The requested URL
24
+ * @param params Query parameters
25
+ * @returns Network response
26
+ */
27
+ post(t, e) {
28
+ return this._httpService.post(t, e);
29
+ }
30
+ /**
31
+ * Send PUT request to the server.
32
+ * @param url The requested URL
33
+ * @param params Query parameters
34
+ * @returns Network response
35
+ */
36
+ put(t, e) {
37
+ return this._httpService.put(t, e);
38
+ }
39
+ /**
40
+ * Send DELETE request to the server.
41
+ * @param url The requested URL
42
+ * @param params Query parameters
43
+ * @returns Network response
44
+ */
45
+ delete(t, e) {
46
+ return this._httpService.delete(t, e);
47
+ }
48
+ /**
49
+ * Send PATCH request to the server.
50
+ * @param url The requested URL
51
+ * @param params Query parameters
52
+ * @returns Network response
53
+ */
54
+ patch(t, e) {
55
+ return this._httpService.patch(t, e);
56
+ }
57
+ /**
58
+ * Request for a stream of server-sent events. Instead of a single response, the server sends a stream of responses,
59
+ * Univer wraps the stream in an [`Observable`](https://rxjs.dev/guide/observable) which you can call `subscribe` on.
60
+ * @param method HTTP request method
61
+ * @param url The requested URL
62
+ * @param params Query parameters
63
+ * @returns An observable that emits the network response
64
+ */
65
+ getSSE(t, e, r) {
66
+ return this._httpService.getSSE(t, e, r);
67
+ }
68
+ };
69
+ p = f([
70
+ o(0, h(_)),
71
+ o(1, h(a))
72
+ ], p);
73
+ class j extends v {
74
+ getNetwork() {
75
+ return this._injector.createInstance(p);
76
+ }
77
+ }
78
+ v.extend(j);