@univerjs/network 0.1.14 → 0.1.15

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/README.md CHANGED
@@ -18,3 +18,7 @@ npm install @univerjs/network
18
18
  # Using pnpm
19
19
  pnpm add @univerjs/network
20
20
  ```
21
+
22
+ ## Credit
23
+
24
+ This package is inspired by [Angular's implementation](https://github.com/angular/angular/tree/main/packages/common/http). Removed zone.js dependency and features that are not necessary for Univer.
package/lib/cjs/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var N=Object.defineProperty;var U=(e,n,r)=>n in e?N(e,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[n]=r;var p=(e,n,r)=>(U(e,typeof n!="symbol"?n+"":n,r),r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("@univerjs/core"),y=require("rxjs"),f=require("rxjs/operators"),L=require("@wendellhu/redi"),I="application/json";class g{constructor(n){p(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}toHeadersInit(){var r,t;const n={};return this._headers.forEach((s,a)=>{n[a]=s.join(",")}),(r=n.accept)!=null||(n.accept="application/json, text/plain, */*"),(t=n["content-type"])!=null||(n["content-type"]="application/json;charset=UTF-8"),n}_setHeader(n,r){const t=n.toLowerCase();this._headers.has(t)?this._headers.get(t).push(r.toString()):this._headers.set(t,[r.toString()])}_handleHeadersString(n){n.split(`
2
- `).forEach(r=>{const[t,s]=r.split(":");t&&s&&this._setHeader(t,s)})}_handleHeadersConstructorProps(n){Object.entries(n).forEach(([r,t])=>this._setHeader(r,t))}_handleHeaders(n){n.forEach((r,t)=>this._setHeader(t,r))}}const A=L.createIdentifier("network.http-implementation");class x{constructor(n){this.params=n}toString(){return this.params?Object.keys(this.params).map(n=>`${n}=${this.params[n]}`).join("&"):""}}let k=0;class _{constructor(n,r,t){p(this,"uid",k++);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:I,r=(s=this.requestParams)==null?void 0:s.body;return n===I&&r&&typeof r=="object"?JSON.stringify(r):r?`${r}`:null}getHeadersInit(){return this.headers.toHeadersInit()}}class b{constructor({body:n,headers:r,status:t,statusText:s}){p(this,"body");p(this,"headers");p(this,"status");p(this,"statusText");this.body=n,this.headers=r,this.status=t,this.statusText=s}}class m{constructor({headers:n,status:r,statusText:t,error:s}){p(this,"headers");p(this,"status");p(this,"statusText");p(this,"error");this.headers=n,this.status=r,this.statusText=t,this.error=s}}class O{constructor(n,r,t){this.headers=n,this.status=r,this.statusText=t}}var M=Object.defineProperty,D=Object.getOwnPropertyDescriptor,j=(e,n,r,t)=>{for(var s=t>1?void 0:t?D(n,r):n,a=e.length-1,i;a>=0;a--)(i=e[a])&&(s=(t?i(n,r,s):i(s))||s);return t&&s&&M(n,r,s),s},B=(e,n)=>(r,t)=>n(r,t,e);exports.HTTPService=class extends u.Disposable{constructor(r){super();p(this,"_interceptors",[]);p(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 a,i;return((a=t.priority)!=null?a:0)-((i=s.priority)!=null?i:0)}),this._pipe=null,u.toDisposable(()=>u.remove(this._interceptors,r))}get(r,t){return this._request("GET",r,t)}post(r,t){return this._request("POST",r,t)}put(r,t){return this._request("PUT",r,t)}delete(r,t){return this._request("DELETE",r,t)}patch(r,t){return this._request("PATCH",r,t)}getSSE(r,t,s){var l,c;const a=new g(s==null?void 0:s.headers),i=new x(s==null?void 0:s.params),o=new _(r,t,{headers:a,params:i,withCredentials:(l=s==null?void 0:s.withCredentials)!=null?l:!1,responseType:(c=s==null?void 0:s.responseType)!=null?c:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body});return y.of(o).pipe(f.concatMap(h=>this._runInterceptorsAndImplementation(h)),f.map(h=>{if(h instanceof m)throw h;return h}))}async _request(r,t,s){var h,w;const a=new g(s==null?void 0:s.headers),i=new x(s==null?void 0:s.params),o=new _(r,t,{headers:a,params:i,withCredentials:(h=s==null?void 0:s.withCredentials)!=null?h:!1,responseType:(w=s==null?void 0:s.responseType)!=null?w:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body}),l=y.of(o).pipe(f.concatMap(d=>this._runInterceptorsAndImplementation(d))),c=await y.firstValueFrom(l);if(c instanceof b)return c;throw new Error(`${c.error}`)}_runInterceptorsAndImplementation(r){return this._pipe||(this._pipe=this._interceptors.map(t=>t.interceptor).reduceRight((t,s)=>$(t,s),(t,s)=>s(t))),this._pipe(r,t=>this._http.send(t))}};exports.HTTPService=j([B(0,A)],exports.HTTPService);function $(e,n){return(r,t)=>n(r,s=>e(s,t))}const G=200,V=300;var v=(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))(v||{});class W{send(n){return new y.Observable(r=>{const t=new AbortController;return this._send(n,r,t).then(()=>{},s=>{r.error(new m({error:s}))}),()=>t.abort()})}async _send(n,r,t){var h,w;let s;try{const d=this._parseFetchParamsFromRequest(n);s=await fetch(n.getUrlWithParams(),{signal:t.signal,...d})}catch(d){r.error(new m({error:d,status:(h=d.status)!=null?h:0,statusText:(w=d.statusText)!=null?w:"Unknown Error",headers:d.headers}));return}const a=new g(s.headers),i=s.status,o=s.statusText;let l=null;s.body&&(l=await this._readBody(n,s,r)),i>=v.Ok&&i<v.MultipleChoices?r.next(new b({body:l,headers:a,status:i,statusText:o})):r.error(new m({error:l,status:i,statusText:o,headers:a})),r.complete()}async _readBody(n,r,t){var l;const s=[],a=r.body.getReader();let i=0;for(;;){const{done:c,value:h}=await a.read();if(c)break;s.push(h),i+=h.length}const o=X(s,i);try{const c=(l=r.headers.get("content-type"))!=null?l:"";return J(n,o,c)}catch(c){return t.error(new m({error:c,status:r.status,statusText:r.statusText,headers:new g(r.headers)})),null}}_parseFetchParamsFromRequest(n){return{method:n.method,headers:n.getHeadersInit(),body:n.getBody(),credentials:n.withCredentials?"include":void 0}}}function X(e,n){const r=new Uint8Array(n);let t=0;for(const s of e)r.set(s,t),t+=s.length;return r}const z=/^\)\]\}',?\n/;function J(e,n,r){switch(e.responseType){case"json":const t=new TextDecoder().decode(n).replace(z,"");return t===""?null:JSON.parse(t);case"text":return new TextDecoder().decode(n);case"blob":return new Blob([n],{type:r});case"arraybuffer":return n.buffer;default:throw new Error(`[FetchHTTPImplementation]: unknown response type: ${e.responseType}.`)}}class Y{send(n){return new y.Observable(r=>{const t=new XMLHttpRequest;t.open(n.method,n.getUrlWithParams()),n.withCredentials&&(t.withCredentials=!0),n.headers.forEach((l,c)=>t.setRequestHeader(l,c.join(","))),n.headers.has("Accept")||t.setRequestHeader("Accept","application/json, text/plain, */*"),n.headers.has("Content-Type")||t.setRequestHeader("Content-Type","application/json;charset=UTF-8");const s=()=>{const l=t.statusText||"OK",c=new g(t.getAllResponseHeaders());return new O(c,t.status,l)},a=()=>{const{headers:l,statusText:c,status:h}=s(),{responseType:w}=n;let d=null,E=null;h!==v.NoContent&&(d=typeof t.response>"u"?t.responseText:t.response);let R=h>=G&&h<V;if(w==="json"&&typeof d=="string"){const q=d;try{d=d?JSON.parse(d):null}catch(F){R=!1,d=q,E=F}}R?r.next(new b({body:d,headers:l,status:h,statusText:c})):r.error(new m({error:E,headers:l,status:h,statusText:c}))},i=l=>{const c=new m({error:l,status:t.status||0,statusText:t.statusText||"Unknown Error",headers:s().headers});r.error(c)};t.addEventListener("load",a),t.addEventListener("error",i),t.addEventListener("abort",i),t.addEventListener("timeout",i);const o=n.getBody();return t.send(o),()=>{t.readyState!==t.DONE&&t.abort(),t.removeEventListener("load",a),t.removeEventListener("error",i),t.removeEventListener("abort",i),t.removeEventListener("timeout",i)}})}}const K=L.createIdentifier("univer.socket");class Q extends u.Disposable{createSocket(n){try{const r=new WebSocket(n),t=new u.DisposableCollection;return{URL:n,close:(a,i)=>{r.close(a,i),t.dispose()},send:a=>{r.send(a)},open$:new y.Observable(a=>{const i=o=>a.next(o);r.addEventListener("open",i),t.add(u.toDisposable(()=>r.removeEventListener("open",i)))}).pipe(f.share()),close$:new y.Observable(a=>{const i=o=>a.next(o);r.addEventListener("close",i),t.add(u.toDisposable(()=>r.removeEventListener("close",i)))}).pipe(f.share()),error$:new y.Observable(a=>{const i=o=>a.next(o);r.addEventListener("error",i),t.add(u.toDisposable(()=>r.removeEventListener("error",i)))}).pipe(f.share()),message$:new y.Observable(a=>{const i=o=>a.next(o);r.addEventListener("message",i),t.add(u.toDisposable(()=>r.removeEventListener("message",i)))}).pipe(f.share())}}catch(r){return console.error(r),null}}}const Z=3,P=1e3,H=(e,n)=>{var s,a;const r=(s=n==null?void 0:n.maxRetryAttempts)!=null?s:Z,t=(a=n==null?void 0:n.delayInterval)!=null?a:P;return(i,o)=>o(i).pipe(f.retry({delay:t,count:r}))},S=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 a=n.shift();r.add(a),a()}};return(s,a)=>new y.Observable(i=>{const o=()=>a(s).subscribe({next:c=>i.next(c),error:c=>i.next(c),complete:()=>i.complete()}),l=()=>{r.delete(o),u.remove(n,o),t()};return n.push(o),t(),l})},C=e=>{const{errorStatusCodes:n,onAuthError:r}=e;return(s,a)=>a(s).pipe(y.catchError(i=>(i instanceof m&&n.some(o=>o===i.status)&&r(),y.throwError(()=>i))))};exports.AuthInterceptorFactory=C;exports.FetchHTTPImplementation=W;exports.HTTPHeaders=g;exports.HTTPRequest=_;exports.HTTPResponse=b;exports.HTTPResponseError=m;exports.HTTPStatusCode=v;exports.IHTTPImplementation=A;exports.ISocketService=K;exports.RetryInterceptorFactory=H;exports.ThresholdInterceptorFactory=S;exports.WebSocketService=Q;exports.XHRHTTPImplementation=Y;
1
+ "use strict";var O=Object.defineProperty;var D=(e,t,r)=>t in e?O(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var p=(e,t,r)=>(D(e,typeof t!="symbol"?t+"":t,r),r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const m=require("@univerjs/core"),y=require("rxjs"),g=require("rxjs/operators"),q=require("@wendellhu/redi"),L="application/json";class E{constructor(t){p(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}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 F=q.createIdentifier("network.http-implementation");class A{constructor(t){this.params=t}toString(){return this.params?Object.keys(this.params).map(t=>`${t}=${this.params[t]}`).join("&"):""}}let M=0;class I{constructor(t,r,n){p(this,"uid",M++);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:L,r=(s=this.requestParams)==null?void 0:s.body;return t===L&&r&&typeof r=="object"?JSON.stringify(r):r?`${r}`:null}getHeadersInit(){return this.headers.toHeadersInit()}}var j=Object.defineProperty,B=Object.getOwnPropertyDescriptor,$=(e,t,r,n)=>{for(var s=n>1?void 0:n?B(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&&j(t,r,s),s},G=(e,t)=>(r,n)=>t(r,n,e);exports.HTTPService=class extends m.Disposable{constructor(r){super();p(this,"_interceptors",[]);p(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,m.toDisposable(()=>m.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 c,l;const i=new E(s==null?void 0:s.headers),o=new A(s==null?void 0:s.params),a=new I(r,n,{headers:i,params:o,withCredentials:(c=s==null?void 0:s.withCredentials)!=null?c:!1,reportProgress:!0,responseType:(l=s==null?void 0:s.responseType)!=null?l:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body});return y.of(a).pipe(g.concatMap(h=>this._runInterceptorsAndImplementation(h)))}async _request(r,n,s){var h,u;const i=new E(s==null?void 0:s.headers),o=new A(s==null?void 0:s.params),a=new I(r,n,{headers:i,params:o,withCredentials:(h=s==null?void 0:s.withCredentials)!=null?h:!1,responseType:(u=s==null?void 0:s.responseType)!=null?u:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body}),c=y.of(a).pipe(g.concatMap(d=>this._runInterceptorsAndImplementation(d)));return await y.firstValueFrom(c)}_runInterceptorsAndImplementation(r){return this._pipe||(this._pipe=this._interceptors.map(n=>n.interceptor).reduceRight((n,s)=>V(n,s),(n,s)=>s(n))),this._pipe(r,n=>this._http.send(n))}};exports.HTTPService=$([G(0,F)],exports.HTTPService);function V(e,t){return(r,n)=>t(r,s=>e(s,n))}var N=(e=>(e[e.DownloadProgress=0]="DownloadProgress",e[e.Response=1]="Response",e))(N||{});class x{constructor({body:t,headers:r,status:n,statusText:s}){p(this,"type",1);p(this,"body");p(this,"headers");p(this,"status");p(this,"statusText");this.body=t,this.headers=r,this.status=n,this.statusText=s}}class U{constructor(t,r,n){p(this,"type",0);this.total=t,this.loaded=r,this.partialText=n}}class k{constructor(t,r,n){this.headers=t,this.status=r,this.statusText=n}}class w{constructor({headers:t,status:r,statusText:n,error:s}){p(this,"headers");p(this,"status");p(this,"statusText");p(this,"error");this.headers=t,this.status=r,this.statusText=n,this.error=s}}const W=200,X=300;var _=(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))(_||{});class z{send(t){return new y.Observable(r=>{const n=new AbortController;return this._send(t,r,n).then(()=>{},s=>{r.error(new w({error:s}))}),()=>n.abort()})}async _send(t,r,n){var h,u;let s;try{const d=this._parseFetchParamsFromRequest(t);s=await fetch(t.getUrlWithParams(),{signal:n.signal,...d})}catch(d){r.error(new w({error:d,status:(h=d.status)!=null?h:0,statusText:(u=d.statusText)!=null?u:"Unknown Error",headers:d.headers}));return}const i=new E(s.headers),o=s.status,a=s.statusText;let c=null;s.body&&(c=await this._readBody(t,s,r)),o>=_.Ok&&o<_.MultipleChoices?r.next(new x({body:c,headers:i,status:o,statusText:a})):r.error(new w({error:c,status:o,statusText:a,headers:i})),r.complete()}async _readBody(t,r,n){var v,R;const s=[],i=r.body.getReader(),o=r.headers.get("content-length");let a=0;const c=(v=t.requestParams)==null?void 0:v.reportProgress,l=t.responseType;let h,u;for(;;){const{done:f,value:b}=await i.read();if(f)break;s.push(b),a+=b.length,c&&l==="text"&&(h=(h!=null?h:"")+(u!=null?u:u=new TextDecoder).decode(b,{stream:!0}),n.next(new U(o?Number.parseInt(o,10):void 0,a,h)))}const d=J(s,a);try{const f=(R=r.headers.get("content-type"))!=null?R:"";return K(t,d,f)}catch(f){return n.error(new w({error:f,status:r.status,statusText:r.statusText,headers:new E(r.headers)})),null}}_parseFetchParamsFromRequest(t){return{method:t.method,headers:t.getHeadersInit(),body:t.getBody(),credentials:t.withCredentials?"include":void 0}}}function J(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 Y=/^\)\]\}',?\n/;function K(e,t,r){switch(e.responseType){case"json":const n=new TextDecoder().decode(t).replace(Y,"");return n===""?null:JSON.parse(n);case"text":return new TextDecoder().decode(t);case"blob":return new Blob([t],{type:r});case"arraybuffer":return t.buffer;default:throw new Error(`[FetchHTTPImplementation]: unknown response type: ${e.responseType}.`)}}class Q{send(t){return new y.Observable(r=>{const n=new XMLHttpRequest;n.open(t.method,t.getUrlWithParams()),t.withCredentials&&(n.withCredentials=!0),t.headers.forEach((c,l)=>n.setRequestHeader(c,l.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 c=n.statusText||"OK",l=new E(n.getAllResponseHeaders());return new k(l,n.status,c)},i=()=>{const{headers:c,statusText:l,status:h}=s(),{responseType:u}=t;let d=null,v=null;h!==_.NoContent&&(d=typeof n.response>"u"?n.responseText:n.response);let R=h>=W&&h<X;if(u==="json"&&typeof d=="string"){const f=d;try{d=d?JSON.parse(d):null}catch(b){R=!1,d=f,v=b}}R?r.next(new x({body:d,headers:c,status:h,statusText:l})):r.error(new w({error:v,headers:c,status:h,statusText:l}))},o=c=>{const l=new w({error:c,status:n.status||0,statusText:n.statusText||"Unknown Error",headers:s().headers});r.error(l)};n.addEventListener("load",i),n.addEventListener("error",o),n.addEventListener("abort",o),n.addEventListener("timeout",o);const a=t.getBody();return n.send(a),()=>{n.readyState!==n.DONE&&n.abort(),n.removeEventListener("load",i),n.removeEventListener("error",o),n.removeEventListener("abort",o),n.removeEventListener("timeout",o)}})}}const Z=q.createIdentifier("univer.socket");class P extends m.Disposable{createSocket(t){try{const r=new WebSocket(t),n=new m.DisposableCollection;return{URL:t,close:(i,o)=>{r.close(i,o),n.dispose()},send:i=>{r.send(i)},open$:new y.Observable(i=>{const o=a=>i.next(a);r.addEventListener("open",o),n.add(m.toDisposable(()=>r.removeEventListener("open",o)))}).pipe(g.share()),close$:new y.Observable(i=>{const o=a=>i.next(a);r.addEventListener("close",o),n.add(m.toDisposable(()=>r.removeEventListener("close",o)))}).pipe(g.share()),error$:new y.Observable(i=>{const o=a=>i.next(a);r.addEventListener("error",o),n.add(m.toDisposable(()=>r.removeEventListener("error",o)))}).pipe(g.share()),message$:new y.Observable(i=>{const o=a=>i.next(a);r.addEventListener("message",o),n.add(m.toDisposable(()=>r.removeEventListener("message",o)))}).pipe(g.share())}}catch(r){return console.error(r),null}}}const H=3,S=1e3,C=(e,t)=>{var s,i;const r=(s=t==null?void 0:t.maxRetryAttempts)!=null?s:H,n=(i=t==null?void 0:t.delayInterval)!=null?i:S;return(o,a)=>a(o).pipe(g.retry({delay:n,count:r}))},T=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 y.Observable(o=>{const a=()=>i(s).subscribe({next:l=>o.next(l),error:l=>o.next(l),complete:()=>o.complete()}),c=()=>{r.delete(a),m.remove(t,a),n()};return t.push(a),n(),c})},ee=e=>{const{errorStatusCodes:t,onAuthError:r}=e;return(s,i)=>i(s).pipe(y.catchError(o=>(o instanceof w&&t.some(a=>a===o.status)&&r(),y.throwError(()=>o))))};exports.AuthInterceptorFactory=ee;exports.FetchHTTPImplementation=z;exports.HTTPEventType=N;exports.HTTPHeaders=E;exports.HTTPProgress=U;exports.HTTPRequest=I;exports.HTTPResponse=x;exports.HTTPResponseError=w;exports.HTTPStatusCode=_;exports.IHTTPImplementation=F;exports.ISocketService=Z;exports.ResponseHeader=k;exports.RetryInterceptorFactory=C;exports.ThresholdInterceptorFactory=T;exports.WebSocketService=P;exports.XHRHTTPImplementation=Q;
package/lib/es/index.js CHANGED
@@ -1,12 +1,12 @@
1
- var O = Object.defineProperty;
2
- var D = (e, r, n) => r in e ? O(e, r, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[r] = n;
3
- var p = (e, r, n) => (D(e, typeof r != "symbol" ? r + "" : r, n), n);
4
- import { Disposable as F, toDisposable as f, remove as N, DisposableCollection as j } from "@univerjs/core";
5
- import { of as x, firstValueFrom as B, Observable as m, catchError as $, throwError as G } from "rxjs";
6
- import { concatMap as b, map as V, share as g, retry as W } from "rxjs/operators";
7
- import { createIdentifier as U } from "@wendellhu/redi";
8
- const I = "application/json";
9
- class w {
1
+ var D = Object.defineProperty;
2
+ var O = (e, r, n) => r in e ? D(e, r, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[r] = n;
3
+ var p = (e, r, n) => (O(e, typeof r != "symbol" ? r + "" : r, n), n);
4
+ import { Disposable as q, toDisposable as _, remove as U, DisposableCollection as j } from "@univerjs/core";
5
+ import { of as b, firstValueFrom as B, Observable as u, catchError as $, throwError as G } from "rxjs";
6
+ import { concatMap as I, share as v, retry as V } from "rxjs/operators";
7
+ import { createIdentifier as k } from "@wendellhu/redi";
8
+ const L = "application/json";
9
+ class R {
10
10
  constructor(r) {
11
11
  p(this, "_headers", /* @__PURE__ */ new Map());
12
12
  typeof r == "string" ? this._handleHeadersString(r) : r instanceof Headers ? this._handleHeaders(r) : r && this._handleHeadersConstructorProps(r);
@@ -24,8 +24,8 @@ class w {
24
24
  toHeadersInit() {
25
25
  var n, t;
26
26
  const r = {};
27
- return this._headers.forEach((s, a) => {
28
- r[a] = s.join(",");
27
+ return this._headers.forEach((s, o) => {
28
+ r[o] = s.join(",");
29
29
  }), (n = r.accept) != null || (r.accept = "application/json, text/plain, */*"), (t = r["content-type"]) != null || (r["content-type"] = "application/json;charset=UTF-8"), r;
30
30
  }
31
31
  _setHeader(r, n) {
@@ -46,8 +46,8 @@ class w {
46
46
  r.forEach((n, t) => this._setHeader(t, n));
47
47
  }
48
48
  }
49
- const X = U("network.http-implementation");
50
- class L {
49
+ const W = k("network.http-implementation");
50
+ class A {
51
51
  constructor(r) {
52
52
  this.params = r;
53
53
  }
@@ -55,10 +55,10 @@ class L {
55
55
  return this.params ? Object.keys(this.params).map((r) => `${r}=${this.params[r]}`).join("&") : "";
56
56
  }
57
57
  }
58
- let z = 0;
59
- class A {
58
+ let X = 0;
59
+ class N {
60
60
  constructor(r, n, t) {
61
- p(this, "uid", z++);
61
+ p(this, "uid", X++);
62
62
  this.method = r, this.url = n, this.requestParams = t;
63
63
  }
64
64
  get headers() {
@@ -77,52 +77,19 @@ class A {
77
77
  }
78
78
  getBody() {
79
79
  var t, s;
80
- const r = (t = this.headers.get("Content-Type")) != null ? t : I, n = (s = this.requestParams) == null ? void 0 : s.body;
81
- return r === I && n && typeof n == "object" ? JSON.stringify(n) : n ? `${n}` : null;
80
+ const r = (t = this.headers.get("Content-Type")) != null ? t : L, n = (s = this.requestParams) == null ? void 0 : s.body;
81
+ return r === L && n && typeof n == "object" ? JSON.stringify(n) : n ? `${n}` : null;
82
82
  }
83
83
  getHeadersInit() {
84
84
  return this.headers.toHeadersInit();
85
85
  }
86
86
  }
87
- class R {
88
- constructor({
89
- body: r,
90
- headers: n,
91
- status: t,
92
- statusText: s
93
- }) {
94
- p(this, "body");
95
- p(this, "headers");
96
- p(this, "status");
97
- p(this, "statusText");
98
- this.body = r, this.headers = n, this.status = t, this.statusText = s;
99
- }
100
- }
101
- class y {
102
- constructor({
103
- headers: r,
104
- status: n,
105
- statusText: t,
106
- error: s
107
- }) {
108
- p(this, "headers");
109
- p(this, "status");
110
- p(this, "statusText");
111
- p(this, "error");
112
- this.headers = r, this.status = n, this.statusText = t, this.error = s;
113
- }
114
- }
115
- class J {
116
- constructor(r, n, t) {
117
- this.headers = r, this.status = n, this.statusText = t;
118
- }
119
- }
120
- var Y = Object.defineProperty, K = Object.getOwnPropertyDescriptor, Q = (e, r, n, t) => {
121
- for (var s = t > 1 ? void 0 : t ? K(r, n) : r, a = e.length - 1, i; a >= 0; a--)
122
- (i = e[a]) && (s = (t ? i(r, n, s) : i(s)) || s);
123
- return t && s && Y(r, n, s), s;
124
- }, Z = (e, r) => (n, t) => r(n, t, e);
125
- let q = class extends F {
87
+ var z = Object.defineProperty, J = Object.getOwnPropertyDescriptor, Y = (e, r, n, t) => {
88
+ for (var s = t > 1 ? void 0 : t ? J(r, n) : r, o = e.length - 1, i; o >= 0; o--)
89
+ (i = e[o]) && (s = (t ? i(r, n, s) : i(s)) || s);
90
+ return t && s && z(r, n, s), s;
91
+ }, K = (e, r) => (n, t) => r(n, t, e);
92
+ let F = class extends q {
126
93
  constructor(r) {
127
94
  super();
128
95
  p(this, "_interceptors", []);
@@ -140,9 +107,9 @@ let q = class extends F {
140
107
  if (this._interceptors.indexOf(r) !== -1)
141
108
  throw new Error("[HTTPService]: The interceptor has already been registered!");
142
109
  return this._interceptors.push(r), this._interceptors = this._interceptors.sort((n, t) => {
143
- var s, a;
144
- return ((s = n.priority) != null ? s : 0) - ((a = t.priority) != null ? a : 0);
145
- }), this._pipe = null, f(() => N(this._interceptors, r));
110
+ var s, o;
111
+ return ((s = n.priority) != null ? s : 0) - ((o = t.priority) != null ? o : 0);
112
+ }), this._pipe = null, _(() => U(this._interceptors, r));
146
113
  }
147
114
  get(r, n) {
148
115
  return this._request("GET", r, n);
@@ -160,45 +127,36 @@ let q = class extends F {
160
127
  return this._request("PATCH", r, n);
161
128
  }
162
129
  getSSE(r, n, t) {
163
- var c, l;
164
- const s = new w(t == null ? void 0 : t.headers), a = new L(t == null ? void 0 : t.params), i = new A(r, n, {
130
+ var a, c;
131
+ const s = new R(t == null ? void 0 : t.headers), o = new A(t == null ? void 0 : t.params), i = new N(r, n, {
165
132
  headers: s,
166
- params: a,
167
- withCredentials: (c = t == null ? void 0 : t.withCredentials) != null ? c : !1,
168
- // default value for withCredentials is false by MDN
169
- responseType: (l = t == null ? void 0 : t.responseType) != null ? l : "json",
133
+ params: o,
134
+ withCredentials: (a = t == null ? void 0 : t.withCredentials) != null ? a : !1,
135
+ reportProgress: !0,
136
+ responseType: (c = t == null ? void 0 : t.responseType) != null ? c : "json",
170
137
  body: ["GET", "DELETE"].includes(r) || t == null ? void 0 : t.body
171
138
  });
172
- return x(i).pipe(
173
- b((o) => this._runInterceptorsAndImplementation(o)),
174
- V((o) => {
175
- if (o instanceof y)
176
- throw o;
177
- return o;
178
- })
179
- );
139
+ return b(i).pipe(I((l) => this._runInterceptorsAndImplementation(l)));
180
140
  }
181
141
  /** The HTTP request implementations */
182
142
  async _request(r, n, t) {
183
- var o, h;
184
- const s = new w(t == null ? void 0 : t.headers), a = new L(t == null ? void 0 : t.params), i = new A(r, n, {
143
+ var l, h;
144
+ const s = new R(t == null ? void 0 : t.headers), o = new A(t == null ? void 0 : t.params), i = new N(r, n, {
185
145
  headers: s,
186
- params: a,
187
- withCredentials: (o = t == null ? void 0 : t.withCredentials) != null ? o : !1,
146
+ params: o,
147
+ withCredentials: (l = t == null ? void 0 : t.withCredentials) != null ? l : !1,
188
148
  // default value for withCredentials is false by MDN
189
149
  responseType: (h = t == null ? void 0 : t.responseType) != null ? h : "json",
190
150
  body: ["GET", "DELETE"].includes(r) || t == null ? void 0 : t.body
191
- }), c = x(i).pipe(
192
- b((u) => this._runInterceptorsAndImplementation(u))
193
- ), l = await B(c);
194
- if (l instanceof R)
195
- return l;
196
- throw new Error(`${l.error}`);
151
+ }), a = b(i).pipe(
152
+ I((y) => this._runInterceptorsAndImplementation(y))
153
+ );
154
+ return await B(a);
197
155
  }
198
156
  // eslint-disable-next-line ts/no-explicit-any
199
157
  _runInterceptorsAndImplementation(r) {
200
158
  return this._pipe || (this._pipe = this._interceptors.map((n) => n.interceptor).reduceRight(
201
- (n, t) => P(n, t),
159
+ (n, t) => Q(n, t),
202
160
  (n, t) => t(n)
203
161
  )), this._pipe(
204
162
  r,
@@ -207,28 +165,69 @@ let q = class extends F {
207
165
  );
208
166
  }
209
167
  };
210
- q = Q([
211
- Z(0, X)
212
- ], q);
213
- function P(e, r) {
168
+ F = Y([
169
+ K(0, W)
170
+ ], F);
171
+ function Q(e, r) {
214
172
  return (n, t) => r(n, (s) => e(s, t));
215
173
  }
216
- const H = 200, S = 300;
217
- var E = /* @__PURE__ */ ((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))(E || {});
218
- class ce {
174
+ var Z = /* @__PURE__ */ ((e) => (e[e.DownloadProgress = 0] = "DownloadProgress", e[e.Response = 1] = "Response", e))(Z || {});
175
+ class M {
176
+ constructor({
177
+ body: r,
178
+ headers: n,
179
+ status: t,
180
+ statusText: s
181
+ }) {
182
+ p(this, "type", 1);
183
+ p(this, "body");
184
+ p(this, "headers");
185
+ p(this, "status");
186
+ p(this, "statusText");
187
+ this.body = r, this.headers = n, this.status = t, this.statusText = s;
188
+ }
189
+ }
190
+ class P {
191
+ constructor(r, n, t) {
192
+ p(this, "type", 0);
193
+ this.total = r, this.loaded = n, this.partialText = t;
194
+ }
195
+ }
196
+ class S {
197
+ constructor(r, n, t) {
198
+ this.headers = r, this.status = n, this.statusText = t;
199
+ }
200
+ }
201
+ class w {
202
+ constructor({
203
+ headers: r,
204
+ status: n,
205
+ statusText: t,
206
+ error: s
207
+ }) {
208
+ p(this, "headers");
209
+ p(this, "status");
210
+ p(this, "statusText");
211
+ p(this, "error");
212
+ this.headers = r, this.status = n, this.statusText = t, this.error = s;
213
+ }
214
+ }
215
+ const H = 200, C = 300;
216
+ var x = /* @__PURE__ */ ((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 || {});
217
+ class le {
219
218
  send(r) {
220
- return new m((n) => {
219
+ return new u((n) => {
221
220
  const t = new AbortController();
222
221
  return this._send(r, n, t).then(() => {
223
222
  }, (s) => {
224
- n.error(new y({
223
+ n.error(new w({
225
224
  error: s
226
225
  }));
227
226
  }), () => t.abort();
228
227
  });
229
228
  }
230
229
  async _send(r, n, t) {
231
- var h, u;
230
+ var h, y;
232
231
  let s;
233
232
  try {
234
233
  const d = this._parseFetchParamsFromRequest(r);
@@ -237,48 +236,54 @@ class ce {
237
236
  ...d
238
237
  });
239
238
  } catch (d) {
240
- n.error(new y({
239
+ n.error(new w({
241
240
  error: d,
242
241
  status: (h = d.status) != null ? h : 0,
243
- statusText: (u = d.statusText) != null ? u : "Unknown Error",
242
+ statusText: (y = d.statusText) != null ? y : "Unknown Error",
244
243
  headers: d.headers
245
244
  }));
246
245
  return;
247
246
  }
248
- const a = new w(s.headers), i = s.status, c = s.statusText;
249
- let l = null;
250
- s.body && (l = await this._readBody(r, s, n)), i >= E.Ok && i < E.MultipleChoices ? n.next(new R({
251
- body: l,
252
- headers: a,
247
+ const o = new R(s.headers), i = s.status, a = s.statusText;
248
+ let c = null;
249
+ s.body && (c = await this._readBody(r, s, n)), i >= x.Ok && i < x.MultipleChoices ? n.next(new M({
250
+ body: c,
251
+ headers: o,
253
252
  status: i,
254
- statusText: c
255
- })) : n.error(new y({
256
- error: l,
253
+ statusText: a
254
+ })) : n.error(new w({
255
+ error: c,
257
256
  status: i,
258
- statusText: c,
259
- headers: a
257
+ statusText: a,
258
+ headers: o
260
259
  })), n.complete();
261
260
  }
262
261
  async _readBody(r, n, t) {
263
- var l;
264
- const s = [], a = n.body.getReader();
265
- let i = 0;
262
+ var f, E;
263
+ const s = [], o = n.body.getReader(), i = n.headers.get("content-length");
264
+ let a = 0;
265
+ const c = (f = r.requestParams) == null ? void 0 : f.reportProgress, l = r.responseType;
266
+ let h, y;
266
267
  for (; ; ) {
267
- const { done: o, value: h } = await a.read();
268
- if (o)
268
+ const { done: m, value: g } = await o.read();
269
+ if (m)
269
270
  break;
270
- s.push(h), i += h.length;
271
+ s.push(g), a += g.length, c && l === "text" && (h = (h != null ? h : "") + (y != null ? y : y = new TextDecoder()).decode(g, { stream: !0 }), t.next(new P(
272
+ i ? Number.parseInt(i, 10) : void 0,
273
+ a,
274
+ h
275
+ )));
271
276
  }
272
- const c = C(s, i);
277
+ const d = T(s, a);
273
278
  try {
274
- const o = (l = n.headers.get("content-type")) != null ? l : "";
275
- return ee(r, c, o);
276
- } catch (o) {
277
- return t.error(new y({
278
- error: o,
279
+ const m = (E = n.headers.get("content-type")) != null ? E : "";
280
+ return re(r, d, m);
281
+ } catch (m) {
282
+ return t.error(new w({
283
+ error: m,
279
284
  status: n.status,
280
285
  statusText: n.statusText,
281
- headers: new w(n.headers)
286
+ headers: new R(n.headers)
282
287
  })), null;
283
288
  }
284
289
  }
@@ -291,18 +296,18 @@ class ce {
291
296
  };
292
297
  }
293
298
  }
294
- function C(e, r) {
299
+ function T(e, r) {
295
300
  const n = new Uint8Array(r);
296
301
  let t = 0;
297
302
  for (const s of e)
298
303
  n.set(s, t), t += s.length;
299
304
  return n;
300
305
  }
301
- const T = /^\)\]\}',?\n/;
302
- function ee(e, r, n) {
306
+ const ee = /^\)\]\}',?\n/;
307
+ function re(e, r, n) {
303
308
  switch (e.responseType) {
304
309
  case "json":
305
- const t = new TextDecoder().decode(r).replace(T, "");
310
+ const t = new TextDecoder().decode(r).replace(ee, "");
306
311
  return t === "" ? null : JSON.parse(t);
307
312
  case "text":
308
313
  return new TextDecoder().decode(r);
@@ -314,135 +319,138 @@ function ee(e, r, n) {
314
319
  throw new Error(`[FetchHTTPImplementation]: unknown response type: ${e.responseType}.`);
315
320
  }
316
321
  }
317
- class le {
322
+ class he {
318
323
  send(r) {
319
- return new m((n) => {
324
+ return new u((n) => {
320
325
  const t = new XMLHttpRequest();
321
- t.open(r.method, r.getUrlWithParams()), r.withCredentials && (t.withCredentials = !0), r.headers.forEach((l, o) => t.setRequestHeader(l, o.join(","))), r.headers.has("Accept") || t.setRequestHeader("Accept", "application/json, text/plain, */*"), r.headers.has("Content-Type") || t.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
326
+ t.open(r.method, r.getUrlWithParams()), r.withCredentials && (t.withCredentials = !0), r.headers.forEach((c, l) => t.setRequestHeader(c, l.join(","))), r.headers.has("Accept") || t.setRequestHeader("Accept", "application/json, text/plain, */*"), r.headers.has("Content-Type") || t.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
322
327
  const s = () => {
323
- const l = t.statusText || "OK", o = new w(t.getAllResponseHeaders());
324
- return new J(o, t.status, l);
325
- }, a = () => {
326
- const { headers: l, statusText: o, status: h } = s(), { responseType: u } = r;
327
- let d = null, _ = null;
328
- h !== E.NoContent && (d = typeof t.response > "u" ? t.responseText : t.response);
329
- let v = h >= H && h < S;
330
- if (u === "json" && typeof d == "string") {
331
- const k = d;
328
+ const c = t.statusText || "OK", l = new R(t.getAllResponseHeaders());
329
+ return new S(l, t.status, c);
330
+ }, o = () => {
331
+ const { headers: c, statusText: l, status: h } = s(), { responseType: y } = r;
332
+ let d = null, f = null;
333
+ h !== x.NoContent && (d = typeof t.response > "u" ? t.responseText : t.response);
334
+ let E = h >= H && h < C;
335
+ if (y === "json" && typeof d == "string") {
336
+ const m = d;
332
337
  try {
333
338
  d = d ? JSON.parse(d) : null;
334
- } catch (M) {
335
- v = !1, d = k, _ = M;
339
+ } catch (g) {
340
+ E = !1, d = m, f = g;
336
341
  }
337
342
  }
338
- v ? n.next(
339
- new R({
343
+ E ? n.next(
344
+ new M({
340
345
  body: d,
341
- headers: l,
346
+ headers: c,
342
347
  status: h,
343
- statusText: o
348
+ statusText: l
344
349
  })
345
350
  ) : n.error(
346
- new y({
347
- error: _,
348
- headers: l,
351
+ new w({
352
+ error: f,
353
+ headers: c,
349
354
  status: h,
350
- statusText: o
355
+ statusText: l
351
356
  })
352
357
  );
353
- }, i = (l) => {
354
- const o = new y({
355
- error: l,
358
+ }, i = (c) => {
359
+ const l = new w({
360
+ error: c,
356
361
  status: t.status || 0,
357
362
  statusText: t.statusText || "Unknown Error",
358
363
  headers: s().headers
359
364
  });
360
- n.error(o);
365
+ n.error(l);
361
366
  };
362
- t.addEventListener("load", a), t.addEventListener("error", i), t.addEventListener("abort", i), t.addEventListener("timeout", i);
363
- const c = r.getBody();
364
- return t.send(c), () => {
365
- t.readyState !== t.DONE && t.abort(), t.removeEventListener("load", a), t.removeEventListener("error", i), t.removeEventListener("abort", i), t.removeEventListener("timeout", i);
367
+ t.addEventListener("load", o), t.addEventListener("error", i), t.addEventListener("abort", i), t.addEventListener("timeout", i);
368
+ const a = r.getBody();
369
+ return t.send(a), () => {
370
+ t.readyState !== t.DONE && t.abort(), t.removeEventListener("load", o), t.removeEventListener("error", i), t.removeEventListener("abort", i), t.removeEventListener("timeout", i);
366
371
  };
367
372
  });
368
373
  }
369
374
  }
370
- const he = U("univer.socket");
371
- class de extends F {
375
+ const de = k("univer.socket");
376
+ class pe extends q {
372
377
  createSocket(r) {
373
378
  try {
374
379
  const n = new WebSocket(r), t = new j();
375
380
  return {
376
381
  URL: r,
377
- close: (a, i) => {
378
- n.close(a, i), t.dispose();
382
+ close: (o, i) => {
383
+ n.close(o, i), t.dispose();
379
384
  },
380
- send: (a) => {
381
- n.send(a);
385
+ send: (o) => {
386
+ n.send(o);
382
387
  },
383
- open$: new m((a) => {
384
- const i = (c) => a.next(c);
385
- n.addEventListener("open", i), t.add(f(() => n.removeEventListener("open", i)));
386
- }).pipe(g()),
387
- close$: new m((a) => {
388
- const i = (c) => a.next(c);
389
- n.addEventListener("close", i), t.add(f(() => n.removeEventListener("close", i)));
390
- }).pipe(g()),
391
- error$: new m((a) => {
392
- const i = (c) => a.next(c);
393
- n.addEventListener("error", i), t.add(f(() => n.removeEventListener("error", i)));
394
- }).pipe(g()),
395
- message$: new m((a) => {
396
- const i = (c) => a.next(c);
397
- n.addEventListener("message", i), t.add(f(() => n.removeEventListener("message", i)));
398
- }).pipe(g())
388
+ open$: new u((o) => {
389
+ const i = (a) => o.next(a);
390
+ n.addEventListener("open", i), t.add(_(() => n.removeEventListener("open", i)));
391
+ }).pipe(v()),
392
+ close$: new u((o) => {
393
+ const i = (a) => o.next(a);
394
+ n.addEventListener("close", i), t.add(_(() => n.removeEventListener("close", i)));
395
+ }).pipe(v()),
396
+ error$: new u((o) => {
397
+ const i = (a) => o.next(a);
398
+ n.addEventListener("error", i), t.add(_(() => n.removeEventListener("error", i)));
399
+ }).pipe(v()),
400
+ message$: new u((o) => {
401
+ const i = (a) => o.next(a);
402
+ n.addEventListener("message", i), t.add(_(() => n.removeEventListener("message", i)));
403
+ }).pipe(v())
399
404
  };
400
405
  } catch (n) {
401
406
  return console.error(n), null;
402
407
  }
403
408
  }
404
409
  }
405
- const re = 3, te = 1e3, pe = (e, r) => {
406
- var s, a;
407
- const n = (s = r == null ? void 0 : r.maxRetryAttempts) != null ? s : re, t = (a = r == null ? void 0 : r.delayInterval) != null ? a : te;
408
- return (i, c) => c(i).pipe(W({ delay: t, count: n }));
409
- }, ye = (e) => {
410
+ const te = 3, ne = 1e3, ye = (e, r) => {
411
+ var s, o;
412
+ const n = (s = r == null ? void 0 : r.maxRetryAttempts) != null ? s : te, t = (o = r == null ? void 0 : r.delayInterval) != null ? o : ne;
413
+ return (i, a) => a(i).pipe(V({ delay: t, count: n }));
414
+ }, me = (e) => {
410
415
  const r = [], n = /* @__PURE__ */ new Set(), t = () => {
411
416
  var s;
412
417
  for (; n.size < ((s = e == null ? void 0 : e.maxParallel) != null ? s : 1) && r.length > 0; ) {
413
- const a = r.shift();
414
- n.add(a), a();
418
+ const o = r.shift();
419
+ n.add(o), o();
415
420
  }
416
421
  };
417
- return (s, a) => new m((i) => {
418
- const c = () => a(s).subscribe({
419
- next: (o) => i.next(o),
420
- error: (o) => i.next(o),
422
+ return (s, o) => new u((i) => {
423
+ const a = () => o(s).subscribe({
424
+ next: (l) => i.next(l),
425
+ error: (l) => i.next(l),
421
426
  complete: () => i.complete()
422
- }), l = () => {
423
- n.delete(c), N(r, c), t();
427
+ }), c = () => {
428
+ n.delete(a), U(r, a), t();
424
429
  };
425
- return r.push(c), t(), l;
430
+ return r.push(a), t(), c;
426
431
  });
427
- }, me = (e) => {
432
+ }, ue = (e) => {
428
433
  const { errorStatusCodes: r, onAuthError: n } = e;
429
- return (s, a) => a(s).pipe(
430
- $((i) => (i instanceof y && r.some((c) => c === i.status) && n(), G(() => i)))
434
+ return (s, o) => o(s).pipe(
435
+ $((i) => (i instanceof w && r.some((a) => a === i.status) && n(), G(() => i)))
431
436
  );
432
437
  };
433
438
  export {
434
- me as AuthInterceptorFactory,
435
- ce as FetchHTTPImplementation,
436
- w as HTTPHeaders,
437
- A as HTTPRequest,
438
- R as HTTPResponse,
439
- y as HTTPResponseError,
440
- q as HTTPService,
441
- E as HTTPStatusCode,
442
- X as IHTTPImplementation,
443
- he as ISocketService,
444
- pe as RetryInterceptorFactory,
445
- ye as ThresholdInterceptorFactory,
446
- de as WebSocketService,
447
- le as XHRHTTPImplementation
439
+ ue as AuthInterceptorFactory,
440
+ le as FetchHTTPImplementation,
441
+ Z as HTTPEventType,
442
+ R as HTTPHeaders,
443
+ P as HTTPProgress,
444
+ N as HTTPRequest,
445
+ M as HTTPResponse,
446
+ w as HTTPResponseError,
447
+ F as HTTPService,
448
+ x as HTTPStatusCode,
449
+ W as IHTTPImplementation,
450
+ de as ISocketService,
451
+ S as ResponseHeader,
452
+ ye as RetryInterceptorFactory,
453
+ me as ThresholdInterceptorFactory,
454
+ pe as WebSocketService,
455
+ he as XHRHTTPImplementation
448
456
  };
@@ -20,7 +20,7 @@ export { FetchHTTPImplementation } from './services/http/implementations/fetch';
20
20
  export { XHRHTTPImplementation } from './services/http/implementations/xhr';
21
21
  export { HTTPRequest, type HTTPRequestMethod } from './services/http/request';
22
22
  export { type HTTPResponseType, HTTPStatusCode } from './services/http/http';
23
- export { HTTPResponse, type HTTPEvent, HTTPResponseError } from './services/http/response';
23
+ export { HTTPResponse, type HTTPEvent, HTTPResponseError, HTTPEventType, HTTPProgress, ResponseHeader, type HTTPResponseBody } from './services/http/response';
24
24
  export { type ISocket, ISocketService, type SocketBodyType, WebSocketService, } from './services/web-socket/web-socket.service';
25
25
  export type { IRequestParams, IPostRequestParams } from './services/http/http.service';
26
26
  export type { HTTPHandlerFn, HTTPInterceptorFn, HTTPInterceptorFnFactory } from './services/http/interceptor';
@@ -4,7 +4,7 @@ import { Observable } from 'rxjs';
4
4
  import { HTTPResponseType } from './http';
5
5
  import { IHTTPImplementation } from './implementations/implementation';
6
6
  import { HTTPRequestMethod } from './request';
7
- import { HTTPResponse } from './response';
7
+ import { HTTPEvent } from './response';
8
8
  import { HTTPInterceptorFn } from './interceptor';
9
9
 
10
10
  export interface IRequestParams {
@@ -19,6 +19,10 @@ export interface IRequestParams {
19
19
  /** Expected types of the response data. */
20
20
  responseType?: HTTPResponseType;
21
21
  withCredentials?: boolean;
22
+ /**
23
+ * Should report progress.
24
+ */
25
+ reportProgress?: boolean;
22
26
  }
23
27
  export interface IPostRequestParams extends IRequestParams {
24
28
  body?: unknown;
@@ -37,8 +41,9 @@ export interface IHTTPInterceptor {
37
41
  *
38
42
  * You can use interceptors to:
39
43
  *
40
- * 1. modify requests (headers included) before they are sent, or modify responses before they are returned to the caller.
41
- * 2. thresholding, logging, caching, etc.
44
+ * 1. modify requests (headers included) before they are sent, or modify responses
45
+ * before they are returned to the caller.
46
+ * 2. threshold, logging, caching, etc.
42
47
  * 3. authentication, authorization, etc.
43
48
  */
44
49
  export declare class HTTPService extends Disposable {
@@ -53,12 +58,12 @@ export declare class HTTPService extends Disposable {
53
58
  * @returns a disposable handler to remove the interceptor
54
59
  */
55
60
  registerHTTPInterceptor(interceptor: IHTTPInterceptor): IDisposable;
56
- get<T>(url: string, options?: IRequestParams): Promise<HTTPResponse<T>>;
57
- post<T>(url: string, options?: IPostRequestParams): Promise<HTTPResponse<T>>;
58
- put<T>(url: string, options?: IPostRequestParams): Promise<HTTPResponse<T>>;
59
- delete<T>(url: string, options?: IRequestParams): Promise<HTTPResponse<T>>;
60
- patch<T>(url: string, options?: IPostRequestParams): Promise<HTTPResponse<T>>;
61
- getSSE<T>(method: HTTPRequestMethod, url: string, options?: IPostRequestParams): Observable<HTTPResponse<T>>;
61
+ get<T>(url: string, params?: IRequestParams): Promise<HTTPEvent<T>>;
62
+ post<T>(url: string, params?: IPostRequestParams): Promise<HTTPEvent<T>>;
63
+ put<T>(url: string, params?: IPostRequestParams): Promise<HTTPEvent<T>>;
64
+ delete<T>(url: string, params?: IRequestParams): Promise<HTTPEvent<T>>;
65
+ patch<T>(url: string, options?: IPostRequestParams): Promise<HTTPEvent<T>>;
66
+ getSSE<T>(method: HTTPRequestMethod, url: string, options?: IPostRequestParams): Observable<HTTPEvent<T>>;
62
67
  /** The HTTP request implementations */
63
68
  private _request;
64
69
  private _runInterceptorsAndImplementation;
@@ -3,12 +3,16 @@ import { HTTPResponseType } from './http';
3
3
  import { HTTPParams } from './params';
4
4
 
5
5
  export type HTTPRequestMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
6
+ /**
7
+ * @internal
8
+ */
6
9
  export interface IHTTPRequestParams {
7
10
  body?: any;
8
11
  headers: HTTPHeaders;
9
12
  params?: HTTPParams;
10
13
  responseType: HTTPResponseType;
11
14
  withCredentials: boolean;
15
+ reportProgress?: boolean;
12
16
  }
13
17
  export declare function __TEST_ONLY_RESET_REQUEST_UID_DO_NOT_USE_IN_PRODUCTION(): void;
14
18
  export declare class HTTPRequest {
@@ -1,12 +1,19 @@
1
1
  import { HTTPHeaders } from './headers';
2
2
 
3
+ export type HTTPEvent<T> = HTTPResponse<T> | HTTPProgress;
4
+ export declare enum HTTPEventType {
5
+ DownloadProgress = 0,
6
+ Response = 1
7
+ }
8
+ interface IHTTPEvent {
9
+ type: HTTPEventType;
10
+ }
11
+ export type HTTPResponseBody = string | ArrayBuffer | Blob | object | null;
3
12
  /**
4
- * There are multiple events could be resolved from the HTTP server.
13
+ * Wraps success response info.
5
14
  */
6
- export type HTTPEvent<T> = HTTPResponse<T> | HTTPResponseError;
7
- export type HTTPResponseBody = string | ArrayBuffer | Blob | object | null;
8
- /** Wraps (success) response info. */
9
- export declare class HTTPResponse<T> {
15
+ export declare class HTTPResponse<T> implements IHTTPEvent {
16
+ readonly type = HTTPEventType.Response;
10
17
  readonly body: T;
11
18
  readonly headers: HTTPHeaders;
12
19
  readonly status: number;
@@ -18,6 +25,49 @@ export declare class HTTPResponse<T> {
18
25
  statusText: string;
19
26
  });
20
27
  }
28
+ /**
29
+ * Progress event for HTTP request. Usually used for reporting download/upload progress or SSE streaming.
30
+ */
31
+ export declare class HTTPProgress implements IHTTPEvent {
32
+ /**
33
+ * Total number of bytes to download. Depending on the request or
34
+ * response, this may not be computable and thus may not be present.
35
+ */
36
+ readonly total: number | undefined;
37
+ /**
38
+ * Number of bytes downloaded.
39
+ */
40
+ readonly loaded: number;
41
+ /**
42
+ * The partial response body as downloaded so far.
43
+ *
44
+ * Only present if the responseType was `text`.
45
+ */
46
+ readonly partialText?: string | undefined;
47
+ readonly type = HTTPEventType.DownloadProgress;
48
+ constructor(
49
+ /**
50
+ * Total number of bytes to download. Depending on the request or
51
+ * response, this may not be computable and thus may not be present.
52
+ */
53
+ total: number | undefined,
54
+ /**
55
+ * Number of bytes downloaded.
56
+ */
57
+ loaded: number,
58
+ /**
59
+ * The partial response body as downloaded so far.
60
+ *
61
+ * Only present if the responseType was `text`.
62
+ */
63
+ partialText?: string | undefined);
64
+ }
65
+ export declare class ResponseHeader {
66
+ readonly headers: HTTPHeaders;
67
+ readonly status: number;
68
+ readonly statusText: string;
69
+ constructor(headers: HTTPHeaders, status: number, statusText: string);
70
+ }
21
71
  export declare class HTTPResponseError {
22
72
  readonly headers?: HTTPHeaders;
23
73
  readonly status?: number;
@@ -30,9 +80,4 @@ export declare class HTTPResponseError {
30
80
  error: any;
31
81
  });
32
82
  }
33
- export declare class ResponseHeader {
34
- readonly headers: HTTPHeaders;
35
- readonly status: number;
36
- readonly statusText: string;
37
- constructor(headers: HTTPHeaders, status: number, statusText: string);
38
- }
83
+ export {};
package/lib/umd/index.js CHANGED
@@ -1,2 +1,2 @@
1
- (function(c,h){typeof exports=="object"&&typeof module<"u"?h(exports,require("@univerjs/core"),require("rxjs"),require("rxjs/operators"),require("@wendellhu/redi")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","rxjs","rxjs/operators","@wendellhu/redi"],h):(c=typeof globalThis<"u"?globalThis:c||self,h(c.UniverNetwork={},c.UniverCore,c.rxjs,c.rxjs.operators,c["@wendellhu/redi"]))})(this,function(c,h,u,w,I){"use strict";var C=Object.defineProperty;var T=(c,h,u)=>h in c?C(c,h,{enumerable:!0,configurable:!0,writable:!0,value:u}):c[h]=u;var m=(c,h,u)=>(T(c,typeof h!="symbol"?h+"":h,u),u);const L="application/json";class E{constructor(n){m(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}toHeadersInit(){var t,r;const n={};return this._headers.forEach((s,a)=>{n[a]=s.join(",")}),(t=n.accept)!=null||(n.accept="application/json, text/plain, */*"),(r=n["content-type"])!=null||(n["content-type"]="application/json;charset=UTF-8"),n}_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 A=I.createIdentifier("network.http-implementation");class q{constructor(n){this.params=n}toString(){return this.params?Object.keys(this.params).map(n=>`${n}=${this.params[n]}`).join("&"):""}}let N=0;class _{constructor(n,t,r){m(this,"uid",N++);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:L,t=(s=this.requestParams)==null?void 0:s.body;return n===L&&t&&typeof t=="object"?JSON.stringify(t):t?`${t}`:null}getHeadersInit(){return this.headers.toHeadersInit()}}class b{constructor({body:n,headers:t,status:r,statusText:s}){m(this,"body");m(this,"headers");m(this,"status");m(this,"statusText");this.body=n,this.headers=t,this.status=r,this.statusText=s}}class f{constructor({headers:n,status:t,statusText:r,error:s}){m(this,"headers");m(this,"status");m(this,"statusText");m(this,"error");this.headers=n,this.status=t,this.statusText=r,this.error=s}}class U{constructor(n,t,r){this.headers=n,this.status=t,this.statusText=r}}var x=Object.defineProperty,k=Object.getOwnPropertyDescriptor,O=(e,n,t,r)=>{for(var s=r>1?void 0:r?k(n,t):n,a=e.length-1,i;a>=0;a--)(i=e[a])&&(s=(r?i(n,t,s):i(s))||s);return r&&s&&x(n,t,s),s},M=(e,n)=>(t,r)=>n(t,r,e);c.HTTPService=class extends h.Disposable{constructor(t){super();m(this,"_interceptors",[]);m(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 a,i;return((a=r.priority)!=null?a:0)-((i=s.priority)!=null?i:0)}),this._pipe=null,h.toDisposable(()=>h.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)}getSSE(t,r,s){var d,l;const a=new E(s==null?void 0:s.headers),i=new q(s==null?void 0:s.params),o=new _(t,r,{headers:a,params:i,withCredentials:(d=s==null?void 0:s.withCredentials)!=null?d:!1,responseType:(l=s==null?void 0:s.responseType)!=null?l:"json",body:["GET","DELETE"].includes(t)||s==null?void 0:s.body});return u.of(o).pipe(w.concatMap(p=>this._runInterceptorsAndImplementation(p)),w.map(p=>{if(p instanceof f)throw p;return p}))}async _request(t,r,s){var p,v;const a=new E(s==null?void 0:s.headers),i=new q(s==null?void 0:s.params),o=new _(t,r,{headers:a,params:i,withCredentials:(p=s==null?void 0:s.withCredentials)!=null?p:!1,responseType:(v=s==null?void 0:s.responseType)!=null?v:"json",body:["GET","DELETE"].includes(t)||s==null?void 0:s.body}),d=u.of(o).pipe(w.concatMap(y=>this._runInterceptorsAndImplementation(y))),l=await u.firstValueFrom(d);if(l instanceof b)return l;throw new Error(`${l.error}`)}_runInterceptorsAndImplementation(t){return this._pipe||(this._pipe=this._interceptors.map(r=>r.interceptor).reduceRight((r,s)=>D(r,s),(r,s)=>s(r))),this._pipe(t,r=>this._http.send(r))}},c.HTTPService=O([M(0,A)],c.HTTPService);function D(e,n){return(t,r)=>n(t,s=>e(s,r))}const j=200,B=300;var g=(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))(g||{});class ${send(n){return new u.Observable(t=>{const r=new AbortController;return this._send(n,t,r).then(()=>{},s=>{t.error(new f({error:s}))}),()=>r.abort()})}async _send(n,t,r){var p,v;let s;try{const y=this._parseFetchParamsFromRequest(n);s=await fetch(n.getUrlWithParams(),{signal:r.signal,...y})}catch(y){t.error(new f({error:y,status:(p=y.status)!=null?p:0,statusText:(v=y.statusText)!=null?v:"Unknown Error",headers:y.headers}));return}const a=new E(s.headers),i=s.status,o=s.statusText;let d=null;s.body&&(d=await this._readBody(n,s,t)),i>=g.Ok&&i<g.MultipleChoices?t.next(new b({body:d,headers:a,status:i,statusText:o})):t.error(new f({error:d,status:i,statusText:o,headers:a})),t.complete()}async _readBody(n,t,r){var d;const s=[],a=t.body.getReader();let i=0;for(;;){const{done:l,value:p}=await a.read();if(l)break;s.push(p),i+=p.length}const o=G(s,i);try{const l=(d=t.headers.get("content-type"))!=null?d:"";return W(n,o,l)}catch(l){return r.error(new f({error:l,status:t.status,statusText:t.statusText,headers:new E(t.headers)})),null}}_parseFetchParamsFromRequest(n){return{method:n.method,headers:n.getHeadersInit(),body:n.getBody(),credentials:n.withCredentials?"include":void 0}}}function G(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 V=/^\)\]\}',?\n/;function W(e,n,t){switch(e.responseType){case"json":const r=new TextDecoder().decode(n).replace(V,"");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}.`)}}class X{send(n){return new u.Observable(t=>{const r=new XMLHttpRequest;r.open(n.method,n.getUrlWithParams()),n.withCredentials&&(r.withCredentials=!0),n.headers.forEach((d,l)=>r.setRequestHeader(d,l.join(","))),n.headers.has("Accept")||r.setRequestHeader("Accept","application/json, text/plain, */*"),n.headers.has("Content-Type")||r.setRequestHeader("Content-Type","application/json;charset=UTF-8");const s=()=>{const d=r.statusText||"OK",l=new E(r.getAllResponseHeaders());return new U(l,r.status,d)},a=()=>{const{headers:d,statusText:l,status:p}=s(),{responseType:v}=n;let y=null,R=null;p!==g.NoContent&&(y=typeof r.response>"u"?r.responseText:r.response);let F=p>=j&&p<B;if(v==="json"&&typeof y=="string"){const H=y;try{y=y?JSON.parse(y):null}catch(S){F=!1,y=H,R=S}}F?t.next(new b({body:y,headers:d,status:p,statusText:l})):t.error(new f({error:R,headers:d,status:p,statusText:l}))},i=d=>{const l=new f({error:d,status:r.status||0,statusText:r.statusText||"Unknown Error",headers:s().headers});t.error(l)};r.addEventListener("load",a),r.addEventListener("error",i),r.addEventListener("abort",i),r.addEventListener("timeout",i);const o=n.getBody();return r.send(o),()=>{r.readyState!==r.DONE&&r.abort(),r.removeEventListener("load",a),r.removeEventListener("error",i),r.removeEventListener("abort",i),r.removeEventListener("timeout",i)}})}}const z=I.createIdentifier("univer.socket");class J extends h.Disposable{createSocket(n){try{const t=new WebSocket(n),r=new h.DisposableCollection;return{URL:n,close:(a,i)=>{t.close(a,i),r.dispose()},send:a=>{t.send(a)},open$:new u.Observable(a=>{const i=o=>a.next(o);t.addEventListener("open",i),r.add(h.toDisposable(()=>t.removeEventListener("open",i)))}).pipe(w.share()),close$:new u.Observable(a=>{const i=o=>a.next(o);t.addEventListener("close",i),r.add(h.toDisposable(()=>t.removeEventListener("close",i)))}).pipe(w.share()),error$:new u.Observable(a=>{const i=o=>a.next(o);t.addEventListener("error",i),r.add(h.toDisposable(()=>t.removeEventListener("error",i)))}).pipe(w.share()),message$:new u.Observable(a=>{const i=o=>a.next(o);t.addEventListener("message",i),r.add(h.toDisposable(()=>t.removeEventListener("message",i)))}).pipe(w.share())}}catch(t){return console.error(t),null}}}const Y=3,K=1e3,Q=(e,n)=>{var s,a;const t=(s=n==null?void 0:n.maxRetryAttempts)!=null?s:Y,r=(a=n==null?void 0:n.delayInterval)!=null?a:K;return(i,o)=>o(i).pipe(w.retry({delay:r,count:t}))},Z=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 a=n.shift();t.add(a),a()}};return(s,a)=>new u.Observable(i=>{const o=()=>a(s).subscribe({next:l=>i.next(l),error:l=>i.next(l),complete:()=>i.complete()}),d=()=>{t.delete(o),h.remove(n,o),r()};return n.push(o),r(),d})},P=e=>{const{errorStatusCodes:n,onAuthError:t}=e;return(s,a)=>a(s).pipe(u.catchError(i=>(i instanceof f&&n.some(o=>o===i.status)&&t(),u.throwError(()=>i))))};c.AuthInterceptorFactory=P,c.FetchHTTPImplementation=$,c.HTTPHeaders=E,c.HTTPRequest=_,c.HTTPResponse=b,c.HTTPResponseError=f,c.HTTPStatusCode=g,c.IHTTPImplementation=A,c.ISocketService=z,c.RetryInterceptorFactory=Q,c.ThresholdInterceptorFactory=Z,c.WebSocketService=J,c.XHRHTTPImplementation=X,Object.defineProperty(c,Symbol.toStringTag,{value:"Module"})});
1
+ (function(o,l){typeof exports=="object"&&typeof module<"u"?l(exports,require("@univerjs/core"),require("rxjs"),require("rxjs/operators"),require("@wendellhu/redi")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","rxjs","rxjs/operators","@wendellhu/redi"],l):(o=typeof globalThis<"u"?globalThis:o||self,l(o.UniverNetwork={},o.UniverCore,o.rxjs,o.rxjs.operators,o["@wendellhu/redi"]))})(this,function(o,l,y,g,q){"use strict";var ee=Object.defineProperty;var re=(o,l,y)=>l in o?ee(o,l,{enumerable:!0,configurable:!0,writable:!0,value:y}):o[l]=y;var m=(o,l,y)=>(re(o,typeof l!="symbol"?l+"":l,y),y);const F="application/json";class E{constructor(n){m(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}toHeadersInit(){var t,r;const n={};return this._headers.forEach((s,a)=>{n[a]=s.join(",")}),(t=n.accept)!=null||(n.accept="application/json, text/plain, */*"),(r=n["content-type"])!=null||(n["content-type"]="application/json;charset=UTF-8"),n}_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 N=q.createIdentifier("network.http-implementation");class U{constructor(n){this.params=n}toString(){return this.params?Object.keys(this.params).map(n=>`${n}=${this.params[n]}`).join("&"):""}}let D=0;class L{constructor(n,t,r){m(this,"uid",D++);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:F,t=(s=this.requestParams)==null?void 0:s.body;return n===F&&t&&typeof t=="object"?JSON.stringify(t):t?`${t}`:null}getHeadersInit(){return this.headers.toHeadersInit()}}var M=Object.defineProperty,j=Object.getOwnPropertyDescriptor,B=(e,n,t,r)=>{for(var s=r>1?void 0:r?j(n,t):n,a=e.length-1,i;a>=0;a--)(i=e[a])&&(s=(r?i(n,t,s):i(s))||s);return r&&s&&M(n,t,s),s},$=(e,n)=>(t,r)=>n(t,r,e);o.HTTPService=class extends l.Disposable{constructor(t){super();m(this,"_interceptors",[]);m(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 a,i;return((a=r.priority)!=null?a:0)-((i=s.priority)!=null?i:0)}),this._pipe=null,l.toDisposable(()=>l.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)}getSSE(t,r,s){var h,d;const a=new E(s==null?void 0:s.headers),i=new U(s==null?void 0:s.params),c=new L(t,r,{headers:a,params:i,withCredentials:(h=s==null?void 0:s.withCredentials)!=null?h:!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 y.of(c).pipe(g.concatMap(p=>this._runInterceptorsAndImplementation(p)))}async _request(t,r,s){var p,f;const a=new E(s==null?void 0:s.headers),i=new U(s==null?void 0:s.params),c=new L(t,r,{headers:a,params:i,withCredentials:(p=s==null?void 0:s.withCredentials)!=null?p:!1,responseType:(f=s==null?void 0:s.responseType)!=null?f:"json",body:["GET","DELETE"].includes(t)||s==null?void 0:s.body}),h=y.of(c).pipe(g.concatMap(u=>this._runInterceptorsAndImplementation(u)));return await y.firstValueFrom(h)}_runInterceptorsAndImplementation(t){return this._pipe||(this._pipe=this._interceptors.map(r=>r.interceptor).reduceRight((r,s)=>G(r,s),(r,s)=>s(r))),this._pipe(t,r=>this._http.send(r))}},o.HTTPService=B([$(0,N)],o.HTTPService);function G(e,n){return(t,r)=>n(t,s=>e(s,r))}var x=(e=>(e[e.DownloadProgress=0]="DownloadProgress",e[e.Response=1]="Response",e))(x||{});class A{constructor({body:n,headers:t,status:r,statusText:s}){m(this,"type",1);m(this,"body");m(this,"headers");m(this,"status");m(this,"statusText");this.body=n,this.headers=t,this.status=r,this.statusText=s}}class k{constructor(n,t,r){m(this,"type",0);this.total=n,this.loaded=t,this.partialText=r}}class O{constructor(n,t,r){this.headers=n,this.status=t,this.statusText=r}}class w{constructor({headers:n,status:t,statusText:r,error:s}){m(this,"headers");m(this,"status");m(this,"statusText");m(this,"error");this.headers=n,this.status=t,this.statusText=r,this.error=s}}const V=200,W=300;var _=(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))(_||{});class X{send(n){return new y.Observable(t=>{const r=new AbortController;return this._send(n,t,r).then(()=>{},s=>{t.error(new w({error:s}))}),()=>r.abort()})}async _send(n,t,r){var p,f;let s;try{const u=this._parseFetchParamsFromRequest(n);s=await fetch(n.getUrlWithParams(),{signal:r.signal,...u})}catch(u){t.error(new w({error:u,status:(p=u.status)!=null?p:0,statusText:(f=u.statusText)!=null?f:"Unknown Error",headers:u.headers}));return}const a=new E(s.headers),i=s.status,c=s.statusText;let h=null;s.body&&(h=await this._readBody(n,s,t)),i>=_.Ok&&i<_.MultipleChoices?t.next(new A({body:h,headers:a,status:i,statusText:c})):t.error(new w({error:h,status:i,statusText:c,headers:a})),t.complete()}async _readBody(n,t,r){var R,I;const s=[],a=t.body.getReader(),i=t.headers.get("content-length");let c=0;const h=(R=n.requestParams)==null?void 0:R.reportProgress,d=n.responseType;let p,f;for(;;){const{done:v,value:b}=await a.read();if(v)break;s.push(b),c+=b.length,h&&d==="text"&&(p=(p!=null?p:"")+(f!=null?f:f=new TextDecoder).decode(b,{stream:!0}),r.next(new k(i?Number.parseInt(i,10):void 0,c,p)))}const u=z(s,c);try{const v=(I=t.headers.get("content-type"))!=null?I:"";return Y(n,u,v)}catch(v){return r.error(new w({error:v,status:t.status,statusText:t.statusText,headers:new E(t.headers)})),null}}_parseFetchParamsFromRequest(n){return{method:n.method,headers:n.getHeadersInit(),body:n.getBody(),credentials:n.withCredentials?"include":void 0}}}function z(e,n){const t=new Uint8Array(n);let r=0;for(const s of e)t.set(s,r),r+=s.length;return t}const J=/^\)\]\}',?\n/;function Y(e,n,t){switch(e.responseType){case"json":const r=new TextDecoder().decode(n).replace(J,"");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}.`)}}class K{send(n){return new y.Observable(t=>{const r=new XMLHttpRequest;r.open(n.method,n.getUrlWithParams()),n.withCredentials&&(r.withCredentials=!0),n.headers.forEach((h,d)=>r.setRequestHeader(h,d.join(","))),n.headers.has("Accept")||r.setRequestHeader("Accept","application/json, text/plain, */*"),n.headers.has("Content-Type")||r.setRequestHeader("Content-Type","application/json;charset=UTF-8");const s=()=>{const h=r.statusText||"OK",d=new E(r.getAllResponseHeaders());return new O(d,r.status,h)},a=()=>{const{headers:h,statusText:d,status:p}=s(),{responseType:f}=n;let u=null,R=null;p!==_.NoContent&&(u=typeof r.response>"u"?r.responseText:r.response);let I=p>=V&&p<W;if(f==="json"&&typeof u=="string"){const v=u;try{u=u?JSON.parse(u):null}catch(b){I=!1,u=v,R=b}}I?t.next(new A({body:u,headers:h,status:p,statusText:d})):t.error(new w({error:R,headers:h,status:p,statusText:d}))},i=h=>{const d=new w({error:h,status:r.status||0,statusText:r.statusText||"Unknown Error",headers:s().headers});t.error(d)};r.addEventListener("load",a),r.addEventListener("error",i),r.addEventListener("abort",i),r.addEventListener("timeout",i);const c=n.getBody();return r.send(c),()=>{r.readyState!==r.DONE&&r.abort(),r.removeEventListener("load",a),r.removeEventListener("error",i),r.removeEventListener("abort",i),r.removeEventListener("timeout",i)}})}}const Q=q.createIdentifier("univer.socket");class Z extends l.Disposable{createSocket(n){try{const t=new WebSocket(n),r=new l.DisposableCollection;return{URL:n,close:(a,i)=>{t.close(a,i),r.dispose()},send:a=>{t.send(a)},open$:new y.Observable(a=>{const i=c=>a.next(c);t.addEventListener("open",i),r.add(l.toDisposable(()=>t.removeEventListener("open",i)))}).pipe(g.share()),close$:new y.Observable(a=>{const i=c=>a.next(c);t.addEventListener("close",i),r.add(l.toDisposable(()=>t.removeEventListener("close",i)))}).pipe(g.share()),error$:new y.Observable(a=>{const i=c=>a.next(c);t.addEventListener("error",i),r.add(l.toDisposable(()=>t.removeEventListener("error",i)))}).pipe(g.share()),message$:new y.Observable(a=>{const i=c=>a.next(c);t.addEventListener("message",i),r.add(l.toDisposable(()=>t.removeEventListener("message",i)))}).pipe(g.share())}}catch(t){return console.error(t),null}}}const P=3,H=1e3,S=(e,n)=>{var s,a;const t=(s=n==null?void 0:n.maxRetryAttempts)!=null?s:P,r=(a=n==null?void 0:n.delayInterval)!=null?a:H;return(i,c)=>c(i).pipe(g.retry({delay:r,count:t}))},C=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 a=n.shift();t.add(a),a()}};return(s,a)=>new y.Observable(i=>{const c=()=>a(s).subscribe({next:d=>i.next(d),error:d=>i.next(d),complete:()=>i.complete()}),h=()=>{t.delete(c),l.remove(n,c),r()};return n.push(c),r(),h})},T=e=>{const{errorStatusCodes:n,onAuthError:t}=e;return(s,a)=>a(s).pipe(y.catchError(i=>(i instanceof w&&n.some(c=>c===i.status)&&t(),y.throwError(()=>i))))};o.AuthInterceptorFactory=T,o.FetchHTTPImplementation=X,o.HTTPEventType=x,o.HTTPHeaders=E,o.HTTPProgress=k,o.HTTPRequest=L,o.HTTPResponse=A,o.HTTPResponseError=w,o.HTTPStatusCode=_,o.IHTTPImplementation=N,o.ISocketService=Q,o.ResponseHeader=O,o.RetryInterceptorFactory=S,o.ThresholdInterceptorFactory=C,o.WebSocketService=Z,o.XHRHTTPImplementation=K,Object.defineProperty(o,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@univerjs/network",
3
- "version": "0.1.14",
3
+ "version": "0.1.15",
4
4
  "private": false,
5
5
  "author": "DreamNum <developer@univer.ai>",
6
6
  "license": "Apache-2.0",
@@ -45,18 +45,18 @@
45
45
  "lib"
46
46
  ],
47
47
  "peerDependencies": {
48
- "@wendellhu/redi": "0.15.2",
48
+ "@wendellhu/redi": "0.15.4",
49
49
  "rxjs": ">=7.0.0",
50
- "@univerjs/core": "0.1.14"
50
+ "@univerjs/core": "0.1.15"
51
51
  },
52
52
  "devDependencies": {
53
- "@wendellhu/redi": "0.15.2",
53
+ "@wendellhu/redi": "0.15.4",
54
54
  "rxjs": "^7.8.1",
55
55
  "typescript": "^5.4.5",
56
- "vite": "^5.2.12",
56
+ "vite": "^5.2.13",
57
57
  "vitest": "^1.6.0",
58
- "@univerjs/shared": "0.1.14",
59
- "@univerjs/core": "0.1.14"
58
+ "@univerjs/core": "0.1.15",
59
+ "@univerjs/shared": "0.1.15"
60
60
  },
61
61
  "univerSpace": {
62
62
  ".": {
@@ -76,6 +76,7 @@
76
76
  "test:watch": "vitest",
77
77
  "coverage": "vitest run --coverage",
78
78
  "lint:types": "tsc --noEmit",
79
- "build": "tsc && vite build"
79
+ "build": "tsc && vite build",
80
+ "sync:cnpm": "cnpm sync"
80
81
  }
81
82
  }