@univerjs/network 0.20.1 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,2 +1,881 @@
1
- import{Disposable as e,DisposableCollection as t,IConfigService as n,ILogService as r,Inject as i,Injector as a,LookUp as o,Plugin as s,Quantity as c,createIdentifier as l,merge as u,mergeOverrideWithDependencies as d,registerDependencies as f,remove as p,toDisposable as m}from"@univerjs/core";import{Observable as h,catchError as g,firstValueFrom as _,of as v,throwError as ee}from"rxjs";import{concatMap as y,retry as b,share as x}from"rxjs/operators";var S=`@univerjs/network`,C=`0.20.1`;const w=`network.config`;Symbol(w);const T={};function E(e){"@babel/helpers - typeof";return E=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},E(e)}function D(e,t){if(E(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(E(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function O(e){var t=D(e,`string`);return E(t)==`symbol`?t:t+``}function k(e,t,n){return(t=O(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const A=`application/json`;function j(e){return Array.isArray(e)?e.some(e=>e.includes(A)):e.includes(A)}var M=class{constructor(e){k(this,`_headers`,new Map),typeof e==`string`?this._handleHeadersString(e):e instanceof Headers?this._handleHeaders(e):e&&this._handleHeadersConstructorProps(e)}forEach(e){this._headers.forEach((t,n)=>e(n,t))}has(e){return!!this._headers.has(e.toLowerCase())}get(e){let t=e.toLowerCase();return this._headers.has(t)?this._headers.get(t):null}set(e,t){this._setHeader(e,t)}toHeadersInit(e){let t={};return this._headers.forEach((e,n)=>{t[n]=e.join(`,`)}),t.accept!=null||(t.accept=`application/json, text/plain, */*`),!(e instanceof FormData)&&(t[`content-type`]!=null||(t[`content-type`]=`application/json;charset=UTF-8`)),t}_setHeader(e,t){let n=e.toLowerCase();this._headers.has(n)?this._headers.get(n).push(t.toString()):this._headers.set(n,[t.toString()])}_handleHeadersString(e){e.split(`
2
- `).forEach(e=>{let[t,n]=e.split(`:`);t&&n&&this._setHeader(t,n)})}_handleHeadersConstructorProps(e){Object.entries(e).forEach(([e,t])=>this._setHeader(e,t))}_handleHeaders(e){e.forEach((e,t)=>this._setHeader(t,e))}};const N=l(`network.http-implementation`);var P=class{constructor(e){this.params=e}toString(){return this.params?Object.keys(this.params).map(e=>{let t=this.params[e];return Array.isArray(t)?t.map(t=>`${e}=${t}`).join(`&`):`${e}=${t}`}).join(`&`):``}};let F=0;var I=class{get headers(){return this.requestParams.headers}get withCredentials(){return this.requestParams.withCredentials}get responseType(){return this.requestParams.responseType}constructor(e,t,n){this.method=e,this.url=t,this.requestParams=n,k(this,`uid`,F++)}getUrlWithParams(){var e;let t=(e=this.requestParams)==null||(e=e.params)==null?void 0:e.toString();return t?`${this.url}${this.url.includes(`?`)?`&`:`?`}${t}`:this.url}getBody(){var e,t;let n=(e=this.headers.get(`Content-Type`))==null?A:e,r=(t=this.requestParams)==null?void 0:t.body;return r instanceof FormData?r:j(n)&&r&&typeof r==`object`?JSON.stringify(r):r?`${r}`:null}getHeadersInit(){var e;return this.headers.toHeadersInit((e=this.requestParams)==null?void 0:e.body)}};function L(e,t){return function(n,r){t(n,r,e)}}function R(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}let z=class extends e{constructor(e){super(),this._http=e,k(this,`_interceptors`,[]),k(this,`_pipe`,void 0)}registerHTTPInterceptor(e){if(this._interceptors.indexOf(e)!==-1)throw Error(`[HTTPService]: The interceptor has already been registered!`);return this._interceptors.push(e),this._interceptors=this._interceptors.sort((e,t)=>{var n,r;return((n=e.priority)==null?0:n)-((r=t.priority)==null?0:r)}),this._pipe=null,m(()=>p(this._interceptors,e))}get(e,t){return this.request(`GET`,e,t)}post(e,t){return this.request(`POST`,e,t)}put(e,t){return this.request(`PUT`,e,t)}delete(e,t){return this.request(`DELETE`,e,t)}patch(e,t){return this.request(`PATCH`,e,t)}async request(e,t,n){var r,i;return await _(v(new I(e,t,{headers:new M(n==null?void 0:n.headers),params:new P(n==null?void 0:n.params),withCredentials:(r=n==null?void 0:n.withCredentials)==null?!1:r,responseType:(i=n==null?void 0:n.responseType)==null?`json`:i,body:[`GET`,`DELETE`].includes(e)||n==null?void 0:n.body})).pipe(y(e=>this._runInterceptorsAndImplementation(e))))}stream(e,t,n){return this.getSSE(e,t,n)}getSSE(e,t,n){var r,i;return v(new I(e,t,{headers:new M(n==null?void 0:n.headers),params:new P(n==null?void 0:n.params),withCredentials:(r=n==null?void 0:n.withCredentials)==null?!1:r,reportProgress:!0,responseType:(i=n==null?void 0:n.responseType)==null?`json`:i,body:[`GET`,`DELETE`].includes(e)||n==null?void 0:n.body})).pipe(y(e=>this._runInterceptorsAndImplementation(e)))}_runInterceptorsAndImplementation(e){return this._pipe||(this._pipe=this._interceptors.map(e=>e.interceptor).reduceRight((e,t)=>B(e,t),(e,t)=>t(e))),this._pipe(e,e=>this._http.send(e))}};z=R([L(0,N)],z);function B(e,t){return(n,r)=>t(n,t=>e(t,r))}let V=function(e){return 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}({}),H=function(e){return e[e.DownloadProgress=0]=`DownloadProgress`,e[e.Response=1]=`Response`,e}({});var U=class{constructor({body:e,headers:t,status:n,statusText:r}){k(this,`type`,H.Response),k(this,`body`,void 0),k(this,`headers`,void 0),k(this,`status`,void 0),k(this,`statusText`,void 0),this.body=e,this.headers=t,this.status=n,this.statusText=r}},W=class{constructor(e,t,n){this.total=e,this.loaded=t,this.partialText=n,k(this,`type`,H.DownloadProgress)}},G=class{constructor(e,t,n){this.headers=e,this.status=t,this.statusText=n}},K=class{constructor({request:e,headers:t,status:n,statusText:r,error:i}){k(this,`request`,void 0),k(this,`headers`,void 0),k(this,`status`,void 0),k(this,`statusText`,void 0),k(this,`error`,void 0),this.request=e,this.headers=t,this.status=n,this.statusText=r,this.error=i}};function q(e){return{method:e.method,headers:e.getHeadersInit(),body:e.getBody(),credentials:e.withCredentials?`include`:void 0}}let J=class{constructor(e){this._logService=e}send(e){return new h(t=>{let n=new AbortController;return this._send(e,t,n).catch(n=>{t.error(new K({error:n,request:e}))}),()=>n.abort()})}async _send(e,t,n){let r;try{let t=q(e),i=e.getUrlWithParams(),a=fetch(i,{signal:n.signal,...t});this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${i} with params ${t}`),r=await a}catch(n){var i,a;let r=new K({request:e,error:n,status:(i=n.status)==null?0:i,statusText:(a=n.statusText)==null?`Unknown Error`:a,headers:n.headers});this._logService.error(`[FetchHTTPImplementation]: network error`,r),t.error(r);return}let o=new M(r.headers),s=r.status,c=r.statusText,l=null;if(r.body&&(l=await this._readBody(e,r,t)),s>=V.Ok&&s<V.MultipleChoices)t.next(new U({body:l,headers:o,status:s,statusText:c}));else{let n=new K({request:e,error:l,status:s,statusText:c,headers:o});this._logService.error(`[FetchHTTPImplementation]: network error`,n),t.error(n)}t.complete()}async _readBody(e,t,n){var r;let i=[],a=t.body.getReader(),o=t.headers.get(`content-length`),s=0,c=(r=e.requestParams)==null?void 0:r.reportProgress,l=e.responseType,u,d;for(;;){let{done:e,value:t}=await a.read();if(e)break;if(i.push(t),s+=t.length,c&&l===`text`){var f,p;u=((f=u)==null?``:f)+((p=d)==null?d=new TextDecoder:p).decode(t,{stream:!0}),n.next(new W(o?Number.parseInt(o,10):void 0,s,u))}}let m=Y(i,s);try{var h;return Z(e,m,(h=t.headers.get(`content-type`))==null?``:h)}catch(r){let i=new K({request:e,error:r,status:t.status,statusText:t.statusText,headers:new M(t.headers)});return this._logService.error(`[FetchHTTPImplementation]: network error`,i),n.error(i),null}}};J=R([L(0,r)],J);function Y(e,t){let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}const X=/^\)\]\}',?\n/;function Z(e,t,n){switch(e.responseType){case`json`:let r=new TextDecoder().decode(t).replace(X,``);return r===``?null:JSON.parse(r);case`text`:return new TextDecoder().decode(t);case`blob`:return new Blob([t.buffer],{type:n});case`arraybuffer`:return t.buffer;default:throw Error(`[FetchHTTPImplementation]: unknown response type: ${e.responseType}.`)}}let Q=class{constructor(e){this._logService=e}send(e){return new h(t=>{let n=new XMLHttpRequest,r=e.getUrlWithParams(),i=q(e),{responseType:a}=e;n.open(e.method,r),e.withCredentials&&(n.withCredentials=!0),i.headers&&Object.entries(i.headers).forEach(([e,t])=>n.setRequestHeader(e,t));let o=()=>{let e=n.statusText||`OK`;return new G(new M(n.getAllResponseHeaders()),n.status,e)},s=()=>{let{headers:r,statusText:i,status:s}=o(),c=null,l=null;s!==V.NoContent&&(c=n.response===void 0?n.responseText:n.response);let u=s>=200&&s<300;if(a===`json`&&typeof c==`string`){let e=c;try{c=c?JSON.parse(c):null}catch(t){u=!1,c=e,l=t}}if(a===`blob`&&!(c instanceof Blob)&&(u=!1,l=Error(`Response is not a Blob object`)),u)t.next(new U({body:c,headers:r,status:s,statusText:i}));else{let n=new K({request:e,error:l,headers:r,status:s,statusText:i});this._logService.error(`[XHRHTTPImplementation]: network error`,n),t.error(n)}},c=r=>{let i=new K({request:e,error:r,status:n.status||0,statusText:n.statusText||`Unknown Error`,headers:o().headers});this._logService.error(`[XHRHTTPImplementation]: network error`,i),t.error(i)};n.responseType=a||``,n.addEventListener(`load`,s),n.addEventListener(`error`,c),n.addEventListener(`abort`,c),n.addEventListener(`timeout`,c);let l=e.getBody();return n.send(l),this._logService.debug(`[XHRHTTPImplementation]`,`sending request to url ${r} with params ${i}`),()=>{n.readyState!==n.DONE&&n.abort(),n.removeEventListener(`load`,s),n.removeEventListener(`error`,c),n.removeEventListener(`abort`,c),n.removeEventListener(`timeout`,c)}})}};Q=R([L(0,r)],Q);let $=class extends s{constructor(e=T,t,n,r){super(),this._config=e,this._logger=t,this._injector=n,this._configService=r;let{...i}=u({},T,this._config);this._configService.setConfig(w,i)}onStarting(){var e,t,n;if(this._injector.get(z,c.OPTIONAL,o.SKIP_SELF)&&!((e=this._config)!=null&&e.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}let r=(t=this._config)!=null&&t.useFetchImpl?J:typeof window<`u`?Q:J;f(this._injector,d([[z],[N,{useClass:r}]],(n=this._config)==null?void 0:n.override))}};k($,`pluginName`,`UNIVER_NETWORK_PLUGIN`),k($,`packageName`,S),k($,`version`,C),$=R([L(1,r),L(2,i(a)),L(3,n)],$);const te=e=>{let{errorStatusCodes:t,onAuthError:n}=e;return(e,r)=>r(e).pipe(g(e=>(e instanceof K&&t.some(t=>t===e.status)&&n(),ee(()=>e))))},ne=(e=300)=>{let t=()=>{};return n=>new Promise(n=>{t();let r=setTimeout(()=>{n(!0)},e);t=()=>{clearTimeout(r),n(!1)}})},re=()=>(e,t)=>t.map(t=>({config:t,result:e})),ie=(e,t={})=>{let{isMatch:n,getParamsFromRequest:r,mergeParamsToRequest:i}=e,{fetchCheck:a=ne(300),distributeResult:o=re()}=t,s=[],c=e=>e.map(e=>e.config);return(e,t)=>n(e)?new h(n=>{let l=r(e);s.push({next:e=>n.next(e),error:e=>n.error(e),config:l});let u=c(s);a(e).then(r=>{if(r){let r=[];u.forEach(e=>{let t=s.findIndex(t=>t.config===e);if(t>=0){let[e]=s.splice(t,1);r.push(e)}}),t(i(u,e)).subscribe({next:e=>{if(e.type===H.Response){let t=e.body,n=o(t,u);r.forEach(t=>{let r=n.find(e=>e.config===t.config);if(r){let n=new U({body:r.result,headers:e.headers,status:e.status,statusText:e.statusText});t.next(n)}else t.error(`batch error`)})}},complete:()=>n.complete(),error:e=>n.error(e)})}})}):t(e)},ae=e=>{var t,n;let r=(t=e==null?void 0:e.maxRetryAttempts)==null?3:t,i=(n=e==null?void 0:e.delayInterval)==null?1e3:n;return(e,t)=>t(e).pipe(b({delay:i,count:r}))},oe=e=>{let t=[],n=new Set,r=()=>{for(var r;n.size<((r=e==null?void 0:e.maxParallel)==null?1:r)&&t.length>0;){let e=t.shift();n.add(e),e()}};return(e,i)=>new h(a=>{let o=()=>i(e).subscribe({next:e=>a.next(e),error:e=>a.error(e),complete:()=>a.complete()});return t.push(o),r(),()=>{n.delete(o),p(t,o),r()}})},se=l(`univer.network.socket.service`);var ce=class extends e{createSocket(e){try{let n=new WebSocket(e),r=new t;return{URL:e,close:(e,t)=>{n.close(e,t),r.dispose()},send:e=>{n.send(e)},open$:new h(e=>{let t=t=>e.next(t);n.addEventListener(`open`,t),r.add(m(()=>n.removeEventListener(`open`,t)))}).pipe(x()),close$:new h(e=>{let t=t=>e.next(t);n.addEventListener(`close`,t),r.add(m(()=>n.removeEventListener(`close`,t)))}).pipe(x()),error$:new h(e=>{let t=t=>e.next(t);n.addEventListener(`error`,t),r.add(m(()=>n.removeEventListener(`error`,t)))}).pipe(x()),message$:new h(e=>{let t=t=>e.next(t);n.addEventListener(`message`,t),r.add(m(()=>n.removeEventListener(`message`,t)))}).pipe(x())}}catch(e){return console.error(e),null}}};export{te as AuthInterceptorFactory,J as FetchHTTPImplementation,H as HTTPEventType,M as HTTPHeaders,W as HTTPProgress,I as HTTPRequest,U as HTTPResponse,K as HTTPResponseError,z as HTTPService,V as HTTPStatusCode,N as IHTTPImplementation,se as ISocketService,ie as MergeInterceptorFactory,G as ResponseHeader,ae as RetryInterceptorFactory,oe as ThresholdInterceptorFactory,$ as UniverNetworkPlugin,ce as WebSocketService,Q as XHRHTTPImplementation};
1
+ import { Disposable, DisposableCollection, IConfigService, ILogService, Inject, Injector, LookUp, Plugin, Quantity, createIdentifier, merge, mergeOverrideWithDependencies, registerDependencies, remove, toDisposable } from "@univerjs/core";
2
+ import { Observable, catchError, firstValueFrom, of, throwError } from "rxjs";
3
+ import { concatMap, retry, share } from "rxjs/operators";
4
+
5
+ //#region package.json
6
+ var name = "@univerjs/network";
7
+ var version = "0.21.0";
8
+
9
+ //#endregion
10
+ //#region src/config/config.ts
11
+ const NETWORK_PLUGIN_CONFIG_KEY = "network.config";
12
+ const configSymbol = Symbol(NETWORK_PLUGIN_CONFIG_KEY);
13
+ const defaultPluginConfig = {};
14
+
15
+ //#endregion
16
+ //#region \0@oxc-project+runtime@0.124.0/helpers/typeof.js
17
+ function _typeof(o) {
18
+ "@babel/helpers - typeof";
19
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
20
+ return typeof o;
21
+ } : function(o) {
22
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
23
+ }, _typeof(o);
24
+ }
25
+
26
+ //#endregion
27
+ //#region \0@oxc-project+runtime@0.124.0/helpers/toPrimitive.js
28
+ function toPrimitive(t, r) {
29
+ if ("object" != _typeof(t) || !t) return t;
30
+ var e = t[Symbol.toPrimitive];
31
+ if (void 0 !== e) {
32
+ var i = e.call(t, r || "default");
33
+ if ("object" != _typeof(i)) return i;
34
+ throw new TypeError("@@toPrimitive must return a primitive value.");
35
+ }
36
+ return ("string" === r ? String : Number)(t);
37
+ }
38
+
39
+ //#endregion
40
+ //#region \0@oxc-project+runtime@0.124.0/helpers/toPropertyKey.js
41
+ function toPropertyKey(t) {
42
+ var i = toPrimitive(t, "string");
43
+ return "symbol" == _typeof(i) ? i : i + "";
44
+ }
45
+
46
+ //#endregion
47
+ //#region \0@oxc-project+runtime@0.124.0/helpers/defineProperty.js
48
+ function _defineProperty(e, r, t) {
49
+ return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
50
+ value: t,
51
+ enumerable: !0,
52
+ configurable: !0,
53
+ writable: !0
54
+ }) : e[r] = t, e;
55
+ }
56
+
57
+ //#endregion
58
+ //#region src/services/http/headers.ts
59
+ const ApplicationJSONType = "application/json";
60
+ /**
61
+ * Check if the content type is application/json
62
+ * "application/json" or "application/json; charset=utf-8" or ["application/json"]
63
+ * @param contentType
64
+ */
65
+ function isApplicationJSONType(contentType) {
66
+ if (Array.isArray(contentType)) return contentType.some((type) => type.includes(ApplicationJSONType));
67
+ return contentType.includes(ApplicationJSONType);
68
+ }
69
+ /**
70
+ * It wraps headers of HTTP requests' and responses' headers.
71
+ */
72
+ var HTTPHeaders = class {
73
+ constructor(headers) {
74
+ _defineProperty(this, "_headers", /* @__PURE__ */ new Map());
75
+ if (typeof headers === "string") this._handleHeadersString(headers);
76
+ else if (headers instanceof Headers) this._handleHeaders(headers);
77
+ else if (headers) this._handleHeadersConstructorProps(headers);
78
+ }
79
+ forEach(callback) {
80
+ this._headers.forEach((v, key) => callback(key, v));
81
+ }
82
+ has(key) {
83
+ return !!this._headers.has(key.toLowerCase());
84
+ }
85
+ get(key) {
86
+ const k = key.toLowerCase();
87
+ return this._headers.has(k) ? this._headers.get(k) : null;
88
+ }
89
+ set(key, value) {
90
+ this._setHeader(key, value);
91
+ }
92
+ toHeadersInit(body) {
93
+ var _headers$accept;
94
+ const headers = {};
95
+ this._headers.forEach((values, key) => {
96
+ headers[key] = values.join(",");
97
+ });
98
+ (_headers$accept = headers.accept) !== null && _headers$accept !== void 0 || (headers.accept = "application/json, text/plain, */*");
99
+ if (!(body instanceof FormData)) {
100
+ var _headers$contentType;
101
+ (_headers$contentType = headers["content-type"]) !== null && _headers$contentType !== void 0 || (headers["content-type"] = "application/json;charset=UTF-8");
102
+ }
103
+ return headers;
104
+ }
105
+ _setHeader(name, value) {
106
+ const lowerCase = name.toLowerCase();
107
+ if (this._headers.has(lowerCase)) this._headers.get(lowerCase).push(value.toString());
108
+ else this._headers.set(lowerCase, [value.toString()]);
109
+ }
110
+ _handleHeadersString(headers) {
111
+ headers.split("\n").forEach((header) => {
112
+ const [name, value] = header.split(":");
113
+ if (name && value) this._setHeader(name, value);
114
+ });
115
+ }
116
+ _handleHeadersConstructorProps(headers) {
117
+ Object.entries(headers).forEach(([name, value]) => this._setHeader(name, value));
118
+ }
119
+ _handleHeaders(headers) {
120
+ headers.forEach((value, name) => this._setHeader(name, value));
121
+ }
122
+ };
123
+
124
+ //#endregion
125
+ //#region src/services/http/implementations/implementation.ts
126
+ const IHTTPImplementation = createIdentifier("network.http-implementation");
127
+
128
+ //#endregion
129
+ //#region src/services/http/params.ts
130
+ var HTTPParams = class {
131
+ constructor(params) {
132
+ this.params = params;
133
+ }
134
+ toString() {
135
+ if (!this.params) return "";
136
+ return Object.keys(this.params).map((key) => {
137
+ const value = this.params[key];
138
+ if (Array.isArray(value)) return value.map((v) => `${key}=${v}`).join("&");
139
+ return `${key}=${value}`;
140
+ }).join("&");
141
+ }
142
+ };
143
+
144
+ //#endregion
145
+ //#region src/services/http/request.ts
146
+ let HTTPRequestUID = 0;
147
+ var HTTPRequest = class {
148
+ get headers() {
149
+ return this.requestParams.headers;
150
+ }
151
+ get withCredentials() {
152
+ return this.requestParams.withCredentials;
153
+ }
154
+ get responseType() {
155
+ return this.requestParams.responseType;
156
+ }
157
+ constructor(method, url, requestParams) {
158
+ this.method = method;
159
+ this.url = url;
160
+ this.requestParams = requestParams;
161
+ _defineProperty(this, "uid", HTTPRequestUID++);
162
+ }
163
+ getUrlWithParams() {
164
+ var _this$requestParams;
165
+ const params = (_this$requestParams = this.requestParams) === null || _this$requestParams === void 0 || (_this$requestParams = _this$requestParams.params) === null || _this$requestParams === void 0 ? void 0 : _this$requestParams.toString();
166
+ if (!params) return this.url;
167
+ return `${this.url}${this.url.includes("?") ? "&" : "?"}${params}`;
168
+ }
169
+ getBody() {
170
+ var _this$headers$get, _this$requestParams2;
171
+ const contentType = (_this$headers$get = this.headers.get("Content-Type")) !== null && _this$headers$get !== void 0 ? _this$headers$get : ApplicationJSONType;
172
+ const body = (_this$requestParams2 = this.requestParams) === null || _this$requestParams2 === void 0 ? void 0 : _this$requestParams2.body;
173
+ if (body instanceof FormData) return body;
174
+ if (isApplicationJSONType(contentType) && body && typeof body === "object") return JSON.stringify(body);
175
+ return body ? `${body}` : null;
176
+ }
177
+ getHeadersInit() {
178
+ var _this$requestParams3;
179
+ return this.headers.toHeadersInit((_this$requestParams3 = this.requestParams) === null || _this$requestParams3 === void 0 ? void 0 : _this$requestParams3.body);
180
+ }
181
+ };
182
+
183
+ //#endregion
184
+ //#region \0@oxc-project+runtime@0.124.0/helpers/decorateParam.js
185
+ function __decorateParam(paramIndex, decorator) {
186
+ return function(target, key) {
187
+ decorator(target, key, paramIndex);
188
+ };
189
+ }
190
+
191
+ //#endregion
192
+ //#region \0@oxc-project+runtime@0.124.0/helpers/decorate.js
193
+ function __decorate(decorators, target, key, desc) {
194
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
195
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
196
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
197
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
198
+ }
199
+
200
+ //#endregion
201
+ //#region src/services/http/http.service.ts
202
+ let HTTPService = class HTTPService extends Disposable {
203
+ constructor(_http) {
204
+ super();
205
+ this._http = _http;
206
+ _defineProperty(this, "_interceptors", []);
207
+ _defineProperty(this, "_pipe", void 0);
208
+ }
209
+ /**
210
+ * Register an HTTP interceptor.
211
+ *
212
+ * @param interceptor the http interceptor
213
+ * @returns a disposable handler to remove the interceptor
214
+ */
215
+ registerHTTPInterceptor(interceptor) {
216
+ if (this._interceptors.indexOf(interceptor) !== -1) throw new Error("[HTTPService]: The interceptor has already been registered!");
217
+ this._interceptors.push(interceptor);
218
+ this._interceptors = this._interceptors.sort((a, b) => {
219
+ var _a$priority, _b$priority;
220
+ return ((_a$priority = a.priority) !== null && _a$priority !== void 0 ? _a$priority : 0) - ((_b$priority = b.priority) !== null && _b$priority !== void 0 ? _b$priority : 0);
221
+ });
222
+ this._pipe = null;
223
+ return toDisposable(() => remove(this._interceptors, interceptor));
224
+ }
225
+ get(url, params) {
226
+ return this.request("GET", url, params);
227
+ }
228
+ post(url, params) {
229
+ return this.request("POST", url, params);
230
+ }
231
+ put(url, params) {
232
+ return this.request("PUT", url, params);
233
+ }
234
+ delete(url, params) {
235
+ return this.request("DELETE", url, params);
236
+ }
237
+ patch(url, params) {
238
+ return this.request("PATCH", url, params);
239
+ }
240
+ /**
241
+ * The HTTP request implementations. Normally you should use the `get`, `post`, `put`, `delete`,
242
+ * `patch` methods instead.
243
+ * @param method HTTP request method, e.g. GET, POST, PUT, DELETE, etc.
244
+ * @param url The URL to send the request to.
245
+ * @param options Optional parameters for the request.
246
+ * @returns A promise that resolves to the HTTP response.
247
+ */
248
+ async request(method, url, options) {
249
+ var _options$withCredenti, _options$responseType;
250
+ return await firstValueFrom(of(new HTTPRequest(method, url, {
251
+ headers: new HTTPHeaders(options === null || options === void 0 ? void 0 : options.headers),
252
+ params: new HTTPParams(options === null || options === void 0 ? void 0 : options.params),
253
+ withCredentials: (_options$withCredenti = options === null || options === void 0 ? void 0 : options.withCredentials) !== null && _options$withCredenti !== void 0 ? _options$withCredenti : false,
254
+ responseType: (_options$responseType = options === null || options === void 0 ? void 0 : options.responseType) !== null && _options$responseType !== void 0 ? _options$responseType : "json",
255
+ body: ["GET", "DELETE"].includes(method) ? void 0 : options === null || options === void 0 ? void 0 : options.body
256
+ })).pipe(concatMap((request) => this._runInterceptorsAndImplementation(request))));
257
+ }
258
+ /**
259
+ * Send an HTTP request. It returns an observable that emits HTTP events. For example, it can be used to
260
+ * send Server-Sent Events (SSE) requests.
261
+ * @deprecated Please use `stream` method instead.
262
+ * @param method HTTP request method, e.g. GET, POST, PUT, DELETE, etc.
263
+ * @param url The URL to send the request to.
264
+ * @param _params Optional parameters for the request.
265
+ * @returns An observable of the HTTP event.
266
+ */
267
+ stream(method, url, _params) {
268
+ return this.getSSE(method, url, _params);
269
+ }
270
+ /**
271
+ * Send a Server-Sent Events (SSE) request. It returns an observable that emits HTTP events. It is the observable
272
+ * pair of the `request` method.
273
+ * @deprecated Please use `stream` method instead.
274
+ * @param method HTTP request method, e.g. GET, POST, PUT, DELETE, etc.
275
+ * @param url The URL to send the request to.
276
+ * @param _params Optional parameters for the request.
277
+ * @returns An observable of the HTTP event.
278
+ */
279
+ getSSE(method, url, _params) {
280
+ var _params$withCredentia, _params$responseType;
281
+ return of(new HTTPRequest(method, url, {
282
+ headers: new HTTPHeaders(_params === null || _params === void 0 ? void 0 : _params.headers),
283
+ params: new HTTPParams(_params === null || _params === void 0 ? void 0 : _params.params),
284
+ withCredentials: (_params$withCredentia = _params === null || _params === void 0 ? void 0 : _params.withCredentials) !== null && _params$withCredentia !== void 0 ? _params$withCredentia : false,
285
+ reportProgress: true,
286
+ responseType: (_params$responseType = _params === null || _params === void 0 ? void 0 : _params.responseType) !== null && _params$responseType !== void 0 ? _params$responseType : "json",
287
+ body: ["GET", "DELETE"].includes(method) ? void 0 : _params === null || _params === void 0 ? void 0 : _params.body
288
+ })).pipe(concatMap((request) => this._runInterceptorsAndImplementation(request)));
289
+ }
290
+ _runInterceptorsAndImplementation(request) {
291
+ if (!this._pipe) this._pipe = this._interceptors.map((handler) => handler.interceptor).reduceRight((nextHandlerFunction, interceptorFunction) => chainInterceptorFn(nextHandlerFunction, interceptorFunction), (requestFromPrevInterceptor, finalHandler) => finalHandler(requestFromPrevInterceptor));
292
+ return this._pipe(request, (requestToNext) => this._http.send(requestToNext));
293
+ }
294
+ };
295
+ HTTPService = __decorate([__decorateParam(0, IHTTPImplementation)], HTTPService);
296
+ function chainInterceptorFn(afterInterceptorChain, currentInterceptorFn) {
297
+ return (prevRequest, nextHandlerFn) => currentInterceptorFn(prevRequest, (nextRequest) => afterInterceptorChain(nextRequest, nextHandlerFn));
298
+ }
299
+
300
+ //#endregion
301
+ //#region src/services/http/http.ts
302
+ /**
303
+ * Http status codes.
304
+ *
305
+ * https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
306
+ */
307
+ let HTTPStatusCode = /* @__PURE__ */ function(HTTPStatusCode) {
308
+ HTTPStatusCode[HTTPStatusCode["Continue"] = 100] = "Continue";
309
+ HTTPStatusCode[HTTPStatusCode["SwitchingProtocols"] = 101] = "SwitchingProtocols";
310
+ HTTPStatusCode[HTTPStatusCode["Processing"] = 102] = "Processing";
311
+ HTTPStatusCode[HTTPStatusCode["EarlyHints"] = 103] = "EarlyHints";
312
+ HTTPStatusCode[HTTPStatusCode["Ok"] = 200] = "Ok";
313
+ HTTPStatusCode[HTTPStatusCode["Created"] = 201] = "Created";
314
+ HTTPStatusCode[HTTPStatusCode["Accepted"] = 202] = "Accepted";
315
+ HTTPStatusCode[HTTPStatusCode["NonAuthoritativeInformation"] = 203] = "NonAuthoritativeInformation";
316
+ HTTPStatusCode[HTTPStatusCode["NoContent"] = 204] = "NoContent";
317
+ HTTPStatusCode[HTTPStatusCode["ResetContent"] = 205] = "ResetContent";
318
+ HTTPStatusCode[HTTPStatusCode["PartialContent"] = 206] = "PartialContent";
319
+ HTTPStatusCode[HTTPStatusCode["MultiStatus"] = 207] = "MultiStatus";
320
+ HTTPStatusCode[HTTPStatusCode["AlreadyReported"] = 208] = "AlreadyReported";
321
+ HTTPStatusCode[HTTPStatusCode["ImUsed"] = 226] = "ImUsed";
322
+ HTTPStatusCode[HTTPStatusCode["MultipleChoices"] = 300] = "MultipleChoices";
323
+ HTTPStatusCode[HTTPStatusCode["MovedPermanently"] = 301] = "MovedPermanently";
324
+ HTTPStatusCode[HTTPStatusCode["Found"] = 302] = "Found";
325
+ HTTPStatusCode[HTTPStatusCode["SeeOther"] = 303] = "SeeOther";
326
+ HTTPStatusCode[HTTPStatusCode["NotModified"] = 304] = "NotModified";
327
+ HTTPStatusCode[HTTPStatusCode["UseProxy"] = 305] = "UseProxy";
328
+ HTTPStatusCode[HTTPStatusCode["Unused"] = 306] = "Unused";
329
+ HTTPStatusCode[HTTPStatusCode["TemporaryRedirect"] = 307] = "TemporaryRedirect";
330
+ HTTPStatusCode[HTTPStatusCode["PermanentRedirect"] = 308] = "PermanentRedirect";
331
+ HTTPStatusCode[HTTPStatusCode["BadRequest"] = 400] = "BadRequest";
332
+ HTTPStatusCode[HTTPStatusCode["Unauthorized"] = 401] = "Unauthorized";
333
+ HTTPStatusCode[HTTPStatusCode["PaymentRequired"] = 402] = "PaymentRequired";
334
+ HTTPStatusCode[HTTPStatusCode["Forbidden"] = 403] = "Forbidden";
335
+ HTTPStatusCode[HTTPStatusCode["NotFound"] = 404] = "NotFound";
336
+ HTTPStatusCode[HTTPStatusCode["MethodNotAllowed"] = 405] = "MethodNotAllowed";
337
+ HTTPStatusCode[HTTPStatusCode["NotAcceptable"] = 406] = "NotAcceptable";
338
+ HTTPStatusCode[HTTPStatusCode["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
339
+ HTTPStatusCode[HTTPStatusCode["RequestTimeout"] = 408] = "RequestTimeout";
340
+ HTTPStatusCode[HTTPStatusCode["Conflict"] = 409] = "Conflict";
341
+ HTTPStatusCode[HTTPStatusCode["Gone"] = 410] = "Gone";
342
+ HTTPStatusCode[HTTPStatusCode["LengthRequired"] = 411] = "LengthRequired";
343
+ HTTPStatusCode[HTTPStatusCode["PreconditionFailed"] = 412] = "PreconditionFailed";
344
+ HTTPStatusCode[HTTPStatusCode["PayloadTooLarge"] = 413] = "PayloadTooLarge";
345
+ HTTPStatusCode[HTTPStatusCode["UriTooLong"] = 414] = "UriTooLong";
346
+ HTTPStatusCode[HTTPStatusCode["UnsupportedMediaType"] = 415] = "UnsupportedMediaType";
347
+ HTTPStatusCode[HTTPStatusCode["RangeNotSatisfiable"] = 416] = "RangeNotSatisfiable";
348
+ HTTPStatusCode[HTTPStatusCode["ExpectationFailed"] = 417] = "ExpectationFailed";
349
+ HTTPStatusCode[HTTPStatusCode["ImATeapot"] = 418] = "ImATeapot";
350
+ HTTPStatusCode[HTTPStatusCode["MisdirectedRequest"] = 421] = "MisdirectedRequest";
351
+ HTTPStatusCode[HTTPStatusCode["UnprocessableEntity"] = 422] = "UnprocessableEntity";
352
+ HTTPStatusCode[HTTPStatusCode["Locked"] = 423] = "Locked";
353
+ HTTPStatusCode[HTTPStatusCode["FailedDependency"] = 424] = "FailedDependency";
354
+ HTTPStatusCode[HTTPStatusCode["TooEarly"] = 425] = "TooEarly";
355
+ HTTPStatusCode[HTTPStatusCode["UpgradeRequired"] = 426] = "UpgradeRequired";
356
+ HTTPStatusCode[HTTPStatusCode["PreconditionRequired"] = 428] = "PreconditionRequired";
357
+ HTTPStatusCode[HTTPStatusCode["TooManyRequests"] = 429] = "TooManyRequests";
358
+ HTTPStatusCode[HTTPStatusCode["RequestHeaderFieldsTooLarge"] = 431] = "RequestHeaderFieldsTooLarge";
359
+ HTTPStatusCode[HTTPStatusCode["UnavailableForLegalReasons"] = 451] = "UnavailableForLegalReasons";
360
+ HTTPStatusCode[HTTPStatusCode["InternalServerError"] = 500] = "InternalServerError";
361
+ HTTPStatusCode[HTTPStatusCode["NotImplemented"] = 501] = "NotImplemented";
362
+ HTTPStatusCode[HTTPStatusCode["BadGateway"] = 502] = "BadGateway";
363
+ HTTPStatusCode[HTTPStatusCode["ServiceUnavailable"] = 503] = "ServiceUnavailable";
364
+ HTTPStatusCode[HTTPStatusCode["GatewayTimeout"] = 504] = "GatewayTimeout";
365
+ HTTPStatusCode[HTTPStatusCode["HttpVersionNotSupported"] = 505] = "HttpVersionNotSupported";
366
+ HTTPStatusCode[HTTPStatusCode["VariantAlsoNegotiates"] = 506] = "VariantAlsoNegotiates";
367
+ HTTPStatusCode[HTTPStatusCode["InsufficientStorage"] = 507] = "InsufficientStorage";
368
+ HTTPStatusCode[HTTPStatusCode["LoopDetected"] = 508] = "LoopDetected";
369
+ HTTPStatusCode[HTTPStatusCode["NotExtended"] = 510] = "NotExtended";
370
+ HTTPStatusCode[HTTPStatusCode["NetworkAuthenticationRequired"] = 511] = "NetworkAuthenticationRequired";
371
+ return HTTPStatusCode;
372
+ }({});
373
+
374
+ //#endregion
375
+ //#region src/services/http/response.ts
376
+ let HTTPEventType = /* @__PURE__ */ function(HTTPEventType) {
377
+ HTTPEventType[HTTPEventType["DownloadProgress"] = 0] = "DownloadProgress";
378
+ HTTPEventType[HTTPEventType["Response"] = 1] = "Response";
379
+ return HTTPEventType;
380
+ }({});
381
+ /**
382
+ * Wraps success response info.
383
+ */
384
+ var HTTPResponse = class {
385
+ constructor({ body, headers, status, statusText }) {
386
+ _defineProperty(this, "type", HTTPEventType.Response);
387
+ _defineProperty(this, "body", void 0);
388
+ _defineProperty(this, "headers", void 0);
389
+ _defineProperty(this, "status", void 0);
390
+ _defineProperty(this, "statusText", void 0);
391
+ this.body = body;
392
+ this.headers = headers;
393
+ this.status = status;
394
+ this.statusText = statusText;
395
+ }
396
+ };
397
+ /**
398
+ * Progress event for HTTP request. Usually used for reporting download/upload progress or SSE streaming.
399
+ */
400
+ var HTTPProgress = class {
401
+ constructor(total, loaded, partialText) {
402
+ this.total = total;
403
+ this.loaded = loaded;
404
+ this.partialText = partialText;
405
+ _defineProperty(this, "type", HTTPEventType.DownloadProgress);
406
+ }
407
+ };
408
+ var ResponseHeader = class {
409
+ constructor(headers, status, statusText) {
410
+ this.headers = headers;
411
+ this.status = status;
412
+ this.statusText = statusText;
413
+ }
414
+ };
415
+ var HTTPResponseError = class {
416
+ constructor({ request, headers, status, statusText, error }) {
417
+ _defineProperty(this, "request", void 0);
418
+ _defineProperty(this, "headers", void 0);
419
+ _defineProperty(this, "status", void 0);
420
+ _defineProperty(this, "statusText", void 0);
421
+ _defineProperty(this, "error", void 0);
422
+ this.request = request;
423
+ this.headers = headers;
424
+ this.status = status;
425
+ this.statusText = statusText;
426
+ this.error = error;
427
+ }
428
+ };
429
+
430
+ //#endregion
431
+ //#region src/services/http/implementations/util.ts
432
+ function parseFetchParamsFromRequest(request) {
433
+ return {
434
+ method: request.method,
435
+ headers: request.getHeadersInit(),
436
+ body: request.getBody(),
437
+ credentials: request.withCredentials ? "include" : void 0
438
+ };
439
+ }
440
+
441
+ //#endregion
442
+ //#region src/services/http/implementations/fetch.ts
443
+ let FetchHTTPImplementation = class FetchHTTPImplementation {
444
+ constructor(_logService) {
445
+ this._logService = _logService;
446
+ }
447
+ send(request) {
448
+ return new Observable((subscriber) => {
449
+ const abortController = new AbortController();
450
+ this._send(request, subscriber, abortController).catch((error) => {
451
+ subscriber.error(new HTTPResponseError({
452
+ error,
453
+ request
454
+ }));
455
+ });
456
+ return () => abortController.abort();
457
+ });
458
+ }
459
+ async _send(request, subscriber, abortController) {
460
+ let response;
461
+ try {
462
+ const fetchParams = parseFetchParamsFromRequest(request);
463
+ const urlWithParams = request.getUrlWithParams();
464
+ const fetchPromise = fetch(urlWithParams, {
465
+ signal: abortController.signal,
466
+ ...fetchParams
467
+ });
468
+ this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${urlWithParams} with params ${fetchParams}`);
469
+ response = await fetchPromise;
470
+ } catch (error) {
471
+ var _error$status, _error$statusText;
472
+ const e = new HTTPResponseError({
473
+ request,
474
+ error,
475
+ status: (_error$status = error.status) !== null && _error$status !== void 0 ? _error$status : 0,
476
+ statusText: (_error$statusText = error.statusText) !== null && _error$statusText !== void 0 ? _error$statusText : "Unknown Error",
477
+ headers: error.headers
478
+ });
479
+ this._logService.error("[FetchHTTPImplementation]: network error", e);
480
+ subscriber.error(e);
481
+ return;
482
+ }
483
+ const responseHeaders = new HTTPHeaders(response.headers);
484
+ const status = response.status;
485
+ const statusText = response.statusText;
486
+ let body = null;
487
+ if (response.body) body = await this._readBody(request, response, subscriber);
488
+ if (status >= HTTPStatusCode.Ok && status < HTTPStatusCode.MultipleChoices) subscriber.next(new HTTPResponse({
489
+ body,
490
+ headers: responseHeaders,
491
+ status,
492
+ statusText
493
+ }));
494
+ else {
495
+ const e = new HTTPResponseError({
496
+ request,
497
+ error: body,
498
+ status,
499
+ statusText,
500
+ headers: responseHeaders
501
+ });
502
+ this._logService.error("[FetchHTTPImplementation]: network error", e);
503
+ subscriber.error(e);
504
+ }
505
+ subscriber.complete();
506
+ }
507
+ async _readBody(request, response, subscriber) {
508
+ var _request$requestParam;
509
+ const chunks = [];
510
+ const reader = response.body.getReader();
511
+ const contentLength = response.headers.get("content-length");
512
+ let receivedLength = 0;
513
+ const reportProgress = (_request$requestParam = request.requestParams) === null || _request$requestParam === void 0 ? void 0 : _request$requestParam.reportProgress;
514
+ const responseType = request.responseType;
515
+ let partialText;
516
+ let decoder;
517
+ while (true) {
518
+ const { done, value } = await reader.read();
519
+ if (done) break;
520
+ chunks.push(value);
521
+ receivedLength += value.length;
522
+ if (reportProgress && responseType === "text") {
523
+ var _partialText, _decoder;
524
+ partialText = ((_partialText = partialText) !== null && _partialText !== void 0 ? _partialText : "") + ((_decoder = decoder) !== null && _decoder !== void 0 ? _decoder : decoder = new TextDecoder()).decode(value, { stream: true });
525
+ subscriber.next(new HTTPProgress(contentLength ? Number.parseInt(contentLength, 10) : void 0, receivedLength, partialText));
526
+ }
527
+ }
528
+ const all = mergeChunks(chunks, receivedLength);
529
+ try {
530
+ var _response$headers$get;
531
+ return deserialize(request, all, (_response$headers$get = response.headers.get("content-type")) !== null && _response$headers$get !== void 0 ? _response$headers$get : "");
532
+ } catch (error) {
533
+ const e = new HTTPResponseError({
534
+ request,
535
+ error,
536
+ status: response.status,
537
+ statusText: response.statusText,
538
+ headers: new HTTPHeaders(response.headers)
539
+ });
540
+ this._logService.error("[FetchHTTPImplementation]: network error", e);
541
+ subscriber.error(e);
542
+ return null;
543
+ }
544
+ }
545
+ };
546
+ FetchHTTPImplementation = __decorate([__decorateParam(0, ILogService)], FetchHTTPImplementation);
547
+ function mergeChunks(chunks, totalLength) {
548
+ const all = new Uint8Array(totalLength);
549
+ let position = 0;
550
+ for (const chunk of chunks) {
551
+ all.set(chunk, position);
552
+ position += chunk.length;
553
+ }
554
+ return all;
555
+ }
556
+ const XSSI_PREFIX = /^\)\]\}',?\n/;
557
+ function deserialize(request, bin, contentType) {
558
+ switch (request.responseType) {
559
+ case "json":
560
+ const text = new TextDecoder().decode(bin).replace(XSSI_PREFIX, "");
561
+ return text === "" ? null : JSON.parse(text);
562
+ case "text": return new TextDecoder().decode(bin);
563
+ case "blob": return new Blob([bin.buffer], { type: contentType });
564
+ case "arraybuffer": return bin.buffer;
565
+ default: throw new Error(`[FetchHTTPImplementation]: unknown response type: ${request.responseType}.`);
566
+ }
567
+ }
568
+
569
+ //#endregion
570
+ //#region src/services/http/implementations/xhr.ts
571
+ let XHRHTTPImplementation = class XHRHTTPImplementation {
572
+ constructor(_logService) {
573
+ this._logService = _logService;
574
+ }
575
+ send(request) {
576
+ return new Observable((observer) => {
577
+ const xhr = new XMLHttpRequest();
578
+ const urlWithParams = request.getUrlWithParams();
579
+ const fetchParams = parseFetchParamsFromRequest(request);
580
+ const { responseType } = request;
581
+ xhr.open(request.method, urlWithParams);
582
+ if (request.withCredentials) xhr.withCredentials = true;
583
+ if (fetchParams.headers) Object.entries(fetchParams.headers).forEach(([key, value]) => xhr.setRequestHeader(key, value));
584
+ const buildResponseHeader = () => {
585
+ const statusText = xhr.statusText || "OK";
586
+ return new ResponseHeader(new HTTPHeaders(xhr.getAllResponseHeaders()), xhr.status, statusText);
587
+ };
588
+ const onLoadHandler = () => {
589
+ const { headers, statusText, status } = buildResponseHeader();
590
+ let body = null;
591
+ let error = null;
592
+ if (status !== HTTPStatusCode.NoContent) body = typeof xhr.response === "undefined" ? xhr.responseText : xhr.response;
593
+ let success = status >= 200 && status < 300;
594
+ if (responseType === "json" && typeof body === "string") {
595
+ const originalBody = body;
596
+ try {
597
+ body = body ? JSON.parse(body) : null;
598
+ } catch (e) {
599
+ success = false;
600
+ body = originalBody;
601
+ error = e;
602
+ }
603
+ }
604
+ if (responseType === "blob" && !(body instanceof Blob)) {
605
+ success = false;
606
+ error = /* @__PURE__ */ new Error("Response is not a Blob object");
607
+ }
608
+ if (success) observer.next(new HTTPResponse({
609
+ body,
610
+ headers,
611
+ status,
612
+ statusText
613
+ }));
614
+ else {
615
+ const e = new HTTPResponseError({
616
+ request,
617
+ error,
618
+ headers,
619
+ status,
620
+ statusText
621
+ });
622
+ this._logService.error("[XHRHTTPImplementation]: network error", e);
623
+ observer.error(e);
624
+ }
625
+ };
626
+ const onErrorHandler = (error) => {
627
+ const e = new HTTPResponseError({
628
+ request,
629
+ error,
630
+ status: xhr.status || 0,
631
+ statusText: xhr.statusText || "Unknown Error",
632
+ headers: buildResponseHeader().headers
633
+ });
634
+ this._logService.error("[XHRHTTPImplementation]: network error", e);
635
+ observer.error(e);
636
+ };
637
+ xhr.responseType = responseType || "";
638
+ xhr.addEventListener("load", onLoadHandler);
639
+ xhr.addEventListener("error", onErrorHandler);
640
+ xhr.addEventListener("abort", onErrorHandler);
641
+ xhr.addEventListener("timeout", onErrorHandler);
642
+ const body = request.getBody();
643
+ xhr.send(body);
644
+ this._logService.debug("[XHRHTTPImplementation]", `sending request to url ${urlWithParams} with params ${fetchParams}`);
645
+ return () => {
646
+ if (xhr.readyState !== xhr.DONE) xhr.abort();
647
+ xhr.removeEventListener("load", onLoadHandler);
648
+ xhr.removeEventListener("error", onErrorHandler);
649
+ xhr.removeEventListener("abort", onErrorHandler);
650
+ xhr.removeEventListener("timeout", onErrorHandler);
651
+ };
652
+ });
653
+ }
654
+ };
655
+ XHRHTTPImplementation = __decorate([__decorateParam(0, ILogService)], XHRHTTPImplementation);
656
+
657
+ //#endregion
658
+ //#region src/plugin.ts
659
+ let UniverNetworkPlugin = class UniverNetworkPlugin extends Plugin {
660
+ constructor(_config = defaultPluginConfig, _logger, _injector, _configService) {
661
+ super();
662
+ this._config = _config;
663
+ this._logger = _logger;
664
+ this._injector = _injector;
665
+ this._configService = _configService;
666
+ const { ...rest } = merge({}, defaultPluginConfig, this._config);
667
+ this._configService.setConfig(NETWORK_PLUGIN_CONFIG_KEY, rest);
668
+ }
669
+ onStarting() {
670
+ var _this$_config, _this$_config2, _this$_config3;
671
+ if (this._injector.get(HTTPService, Quantity.OPTIONAL, LookUp.SKIP_SELF) && !((_this$_config = this._config) === null || _this$_config === void 0 ? void 0 : _this$_config.forceUseNewInstance)) {
672
+ 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.");
673
+ return;
674
+ }
675
+ const impl = ((_this$_config2 = this._config) === null || _this$_config2 === void 0 ? void 0 : _this$_config2.useFetchImpl) ? FetchHTTPImplementation : typeof window !== "undefined" ? XHRHTTPImplementation : FetchHTTPImplementation;
676
+ registerDependencies(this._injector, mergeOverrideWithDependencies([[HTTPService], [IHTTPImplementation, { useClass: impl }]], (_this$_config3 = this._config) === null || _this$_config3 === void 0 ? void 0 : _this$_config3.override));
677
+ }
678
+ };
679
+ _defineProperty(UniverNetworkPlugin, "pluginName", "UNIVER_NETWORK_PLUGIN");
680
+ _defineProperty(UniverNetworkPlugin, "packageName", name);
681
+ _defineProperty(UniverNetworkPlugin, "version", version);
682
+ UniverNetworkPlugin = __decorate([
683
+ __decorateParam(1, ILogService),
684
+ __decorateParam(2, Inject(Injector)),
685
+ __decorateParam(3, IConfigService)
686
+ ], UniverNetworkPlugin);
687
+
688
+ //#endregion
689
+ //#region src/services/http/interceptors/auth-interceptor.ts
690
+ const AuthInterceptorFactory = (params) => {
691
+ const { errorStatusCodes, onAuthError } = params;
692
+ const authInterceptor = (request, next) => {
693
+ return next(request).pipe(catchError((error) => {
694
+ if (error instanceof HTTPResponseError && errorStatusCodes.some((c) => c === error.status)) onAuthError();
695
+ return throwError(() => error);
696
+ }));
697
+ };
698
+ return authInterceptor;
699
+ };
700
+
701
+ //#endregion
702
+ //#region src/services/http/interceptors/merge-interceptor.ts
703
+ const createDefaultFetchCheck = (time = 300) => {
704
+ const noop = () => {};
705
+ let cancel = noop;
706
+ return (_currentConfig) => {
707
+ return new Promise((res) => {
708
+ cancel();
709
+ const t = setTimeout(() => {
710
+ res(true);
711
+ }, time);
712
+ cancel = () => {
713
+ clearTimeout(t);
714
+ res(false);
715
+ };
716
+ });
717
+ };
718
+ };
719
+ const createDistributeResult = () => {
720
+ return (result, list) => {
721
+ return list.map((config) => ({
722
+ config,
723
+ result
724
+ }));
725
+ };
726
+ };
727
+ const MergeInterceptorFactory = (config, options = {}) => {
728
+ const { isMatch, getParamsFromRequest, mergeParamsToRequest } = config;
729
+ const { fetchCheck = createDefaultFetchCheck(300), distributeResult = createDistributeResult() } = options;
730
+ const hookList = [];
731
+ const getPlainList = (_list) => _list.map((item) => item.config);
732
+ return (requestConfig, next) => {
733
+ if (!isMatch(requestConfig)) return next(requestConfig);
734
+ return new Observable((observer) => {
735
+ const params = getParamsFromRequest(requestConfig);
736
+ hookList.push({
737
+ next: (v) => observer.next(v),
738
+ error: (error) => observer.error(error),
739
+ config: params
740
+ });
741
+ const list = getPlainList(hookList);
742
+ fetchCheck(requestConfig).then((isFetch) => {
743
+ if (isFetch) {
744
+ const currentHookList = [];
745
+ list.forEach((config) => {
746
+ const index = hookList.findIndex((item) => item.config === config);
747
+ if (index >= 0) {
748
+ const [hook] = hookList.splice(index, 1);
749
+ currentHookList.push(hook);
750
+ }
751
+ });
752
+ next(mergeParamsToRequest(list, requestConfig)).subscribe({
753
+ next: (e) => {
754
+ if (e.type === HTTPEventType.Response) {
755
+ const body = e.body;
756
+ const configList = distributeResult(body, list);
757
+ currentHookList.forEach((hookItem) => {
758
+ const res = configList.find((item) => item.config === hookItem.config);
759
+ if (res) {
760
+ const response = new HTTPResponse({
761
+ body: res.result,
762
+ headers: e.headers,
763
+ status: e.status,
764
+ statusText: e.statusText
765
+ });
766
+ hookItem.next(response);
767
+ } else hookItem.error("batch error");
768
+ });
769
+ }
770
+ },
771
+ complete: () => observer.complete(),
772
+ error: (e) => observer.error(e)
773
+ });
774
+ }
775
+ });
776
+ });
777
+ };
778
+ };
779
+
780
+ //#endregion
781
+ //#region src/services/http/interceptors/retry-interceptor.ts
782
+ const DEFAULT_MAX_RETRY_ATTEMPTS = 3;
783
+ const DELAY_INTERVAL = 1e3;
784
+ const RetryInterceptorFactory = (params) => {
785
+ var _params$maxRetryAttem, _params$delayInterval;
786
+ const maxRetryAttempts = (_params$maxRetryAttem = params === null || params === void 0 ? void 0 : params.maxRetryAttempts) !== null && _params$maxRetryAttem !== void 0 ? _params$maxRetryAttem : DEFAULT_MAX_RETRY_ATTEMPTS;
787
+ const delayInterval = (_params$delayInterval = params === null || params === void 0 ? void 0 : params.delayInterval) !== null && _params$delayInterval !== void 0 ? _params$delayInterval : DELAY_INTERVAL;
788
+ return (request, next) => next(request).pipe(retry({
789
+ delay: delayInterval,
790
+ count: maxRetryAttempts
791
+ }));
792
+ };
793
+
794
+ //#endregion
795
+ //#region src/services/http/interceptors/threshold-interceptor.ts
796
+ const ThresholdInterceptorFactory = (params) => {
797
+ /**
798
+ * The local variable to store handles.
799
+ */
800
+ const handlers = [];
801
+ const ongoingHandlers = /* @__PURE__ */ new Set();
802
+ const tick = () => {
803
+ var _params$maxParallel;
804
+ while (ongoingHandlers.size < ((_params$maxParallel = params === null || params === void 0 ? void 0 : params.maxParallel) !== null && _params$maxParallel !== void 0 ? _params$maxParallel : 1) && handlers.length > 0) {
805
+ const handler = handlers.shift();
806
+ ongoingHandlers.add(handler);
807
+ handler();
808
+ }
809
+ };
810
+ return (request, next) => {
811
+ return new Observable((observer) => {
812
+ const handler = () => next(request).subscribe({
813
+ next: (event) => observer.next(event),
814
+ error: (err) => observer.error(err),
815
+ complete: () => observer.complete()
816
+ });
817
+ const teardown = () => {
818
+ ongoingHandlers.delete(handler);
819
+ remove(handlers, handler);
820
+ tick();
821
+ };
822
+ handlers.push(handler);
823
+ tick();
824
+ return teardown;
825
+ });
826
+ };
827
+ };
828
+
829
+ //#endregion
830
+ //#region src/services/web-socket/web-socket.service.ts
831
+ /**
832
+ * This service is responsible for establishing bidi-directional connection to a remote server.
833
+ */
834
+ const ISocketService = createIdentifier("univer.network.socket.service");
835
+ /**
836
+ * This service create a WebSocket connection to a remote server.
837
+ */
838
+ var WebSocketService = class extends Disposable {
839
+ createSocket(URL) {
840
+ try {
841
+ const connection = new WebSocket(URL);
842
+ const disposables = new DisposableCollection();
843
+ return {
844
+ URL,
845
+ close: (code, reason) => {
846
+ connection.close(code, reason);
847
+ disposables.dispose();
848
+ },
849
+ send: (data) => {
850
+ connection.send(data);
851
+ },
852
+ open$: new Observable((subscriber) => {
853
+ const callback = (event) => subscriber.next(event);
854
+ connection.addEventListener("open", callback);
855
+ disposables.add(toDisposable(() => connection.removeEventListener("open", callback)));
856
+ }).pipe(share()),
857
+ close$: new Observable((subscriber) => {
858
+ const callback = (event) => subscriber.next(event);
859
+ connection.addEventListener("close", callback);
860
+ disposables.add(toDisposable(() => connection.removeEventListener("close", callback)));
861
+ }).pipe(share()),
862
+ error$: new Observable((subscriber) => {
863
+ const callback = (event) => subscriber.next(event);
864
+ connection.addEventListener("error", callback);
865
+ disposables.add(toDisposable(() => connection.removeEventListener("error", callback)));
866
+ }).pipe(share()),
867
+ message$: new Observable((subscriber) => {
868
+ const callback = (event) => subscriber.next(event);
869
+ connection.addEventListener("message", callback);
870
+ disposables.add(toDisposable(() => connection.removeEventListener("message", callback)));
871
+ }).pipe(share())
872
+ };
873
+ } catch (e) {
874
+ console.error(e);
875
+ return null;
876
+ }
877
+ }
878
+ };
879
+
880
+ //#endregion
881
+ export { AuthInterceptorFactory, FetchHTTPImplementation, HTTPEventType, HTTPHeaders, HTTPProgress, HTTPRequest, HTTPResponse, HTTPResponseError, HTTPService, HTTPStatusCode, IHTTPImplementation, ISocketService, MergeInterceptorFactory, ResponseHeader, RetryInterceptorFactory, ThresholdInterceptorFactory, UniverNetworkPlugin, WebSocketService, XHRHTTPImplementation };