@univerjs/network 1.0.0-alpha.7 → 1.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/cjs/facade.js CHANGED
@@ -2,7 +2,7 @@ let _univerjs_core_facade = require("@univerjs/core/facade");
2
2
  let _univerjs_network = require("@univerjs/network");
3
3
  let _univerjs_core = require("@univerjs/core");
4
4
 
5
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/decorateParam.js
5
+ //#region \0@oxc-project+runtime@0.140.0/helpers/esm/decorateParam.js
6
6
  function __decorateParam(paramIndex, decorator) {
7
7
  return function(target, key) {
8
8
  decorator(target, key, paramIndex);
@@ -10,7 +10,7 @@ function __decorateParam(paramIndex, decorator) {
10
10
  }
11
11
 
12
12
  //#endregion
13
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/decorate.js
13
+ //#region \0@oxc-project+runtime@0.140.0/helpers/esm/decorate.js
14
14
  function __decorate(decorators, target, key, desc) {
15
15
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
16
16
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
@@ -80,7 +80,7 @@ let FNetwork = class FNetwork extends _univerjs_core_facade.FBase {
80
80
  * @returns {Observable<HTTPEvent>} An observable that emits the network response.
81
81
  */
82
82
  getSSE(method, url, params) {
83
- return this._httpService.getSSE(method, url, params);
83
+ return this._httpService.stream(method, url, params);
84
84
  }
85
85
  };
86
86
  FNetwork = __decorate([__decorateParam(0, (0, _univerjs_core.Inject)(_univerjs_core.Injector)), __decorateParam(1, (0, _univerjs_core.Inject)(_univerjs_network.HTTPService))], FNetwork);
package/lib/cjs/index.js CHANGED
@@ -5,7 +5,7 @@ let rxjs_operators = require("rxjs/operators");
5
5
 
6
6
  //#region package.json
7
7
  var name = "@univerjs/network";
8
- var version = "1.0.0-alpha.7";
8
+ var version = "1.0.0-beta.0";
9
9
 
10
10
  //#endregion
11
11
  //#region src/config/config.ts
@@ -14,7 +14,7 @@ const configSymbol = Symbol(NETWORK_PLUGIN_CONFIG_KEY);
14
14
  const defaultPluginConfig = {};
15
15
 
16
16
  //#endregion
17
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/typeof.js
17
+ //#region \0@oxc-project+runtime@0.140.0/helpers/esm/typeof.js
18
18
  function _typeof(o) {
19
19
  "@babel/helpers - typeof";
20
20
  return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
@@ -25,7 +25,7 @@ function _typeof(o) {
25
25
  }
26
26
 
27
27
  //#endregion
28
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/toPrimitive.js
28
+ //#region \0@oxc-project+runtime@0.140.0/helpers/esm/toPrimitive.js
29
29
  function toPrimitive(t, r) {
30
30
  if ("object" != _typeof(t) || !t) return t;
31
31
  var e = t[Symbol.toPrimitive];
@@ -38,14 +38,14 @@ function toPrimitive(t, r) {
38
38
  }
39
39
 
40
40
  //#endregion
41
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/toPropertyKey.js
41
+ //#region \0@oxc-project+runtime@0.140.0/helpers/esm/toPropertyKey.js
42
42
  function toPropertyKey(t) {
43
43
  var i = toPrimitive(t, "string");
44
44
  return "symbol" == _typeof(i) ? i : i + "";
45
45
  }
46
46
 
47
47
  //#endregion
48
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/defineProperty.js
48
+ //#region \0@oxc-project+runtime@0.140.0/helpers/esm/defineProperty.js
49
49
  function _defineProperty(e, r, t) {
50
50
  return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
51
51
  value: t,
@@ -91,16 +91,12 @@ var HTTPHeaders = class {
91
91
  this._setHeader(key, value);
92
92
  }
93
93
  toHeadersInit(body) {
94
- var _headers$accept;
95
94
  const headers = {};
96
95
  this._headers.forEach((values, key) => {
97
96
  headers[key] = values.join(",");
98
97
  });
99
- (_headers$accept = headers.accept) !== null && _headers$accept !== void 0 || (headers.accept = "application/json, text/plain, */*");
100
- if (!(body instanceof FormData)) {
101
- var _headers$contentType;
102
- (_headers$contentType = headers["content-type"]) !== null && _headers$contentType !== void 0 || (headers["content-type"] = "application/json;charset=UTF-8");
103
- }
98
+ headers.accept ??= "application/json, text/plain, */*";
99
+ if (!(body instanceof FormData)) headers["content-type"] ??= "application/json;charset=UTF-8";
104
100
  return headers;
105
101
  }
106
102
  _setHeader(name, value) {
@@ -168,8 +164,8 @@ var HTTPRequest = class {
168
164
  return `${this.url}${this.url.includes("?") ? "&" : "?"}${params}`;
169
165
  }
170
166
  getBody() {
171
- var _this$headers$get, _this$requestParams2;
172
- const contentType = (_this$headers$get = this.headers.get("Content-Type")) !== null && _this$headers$get !== void 0 ? _this$headers$get : ApplicationJSONType;
167
+ var _this$requestParams2;
168
+ const contentType = this.headers.get("Content-Type") ?? "application/json";
173
169
  const body = (_this$requestParams2 = this.requestParams) === null || _this$requestParams2 === void 0 ? void 0 : _this$requestParams2.body;
174
170
  if (body instanceof FormData) return body;
175
171
  if (isApplicationJSONType(contentType) && body && typeof body === "object") return JSON.stringify(body);
@@ -182,7 +178,7 @@ var HTTPRequest = class {
182
178
  };
183
179
 
184
180
  //#endregion
185
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/decorateParam.js
181
+ //#region \0@oxc-project+runtime@0.140.0/helpers/esm/decorateParam.js
186
182
  function __decorateParam(paramIndex, decorator) {
187
183
  return function(target, key) {
188
184
  decorator(target, key, paramIndex);
@@ -190,7 +186,7 @@ function __decorateParam(paramIndex, decorator) {
190
186
  }
191
187
 
192
188
  //#endregion
193
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/decorate.js
189
+ //#region \0@oxc-project+runtime@0.140.0/helpers/esm/decorate.js
194
190
  function __decorate(decorators, target, key, desc) {
195
191
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
196
192
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
@@ -216,10 +212,7 @@ let HTTPService = class HTTPService extends _univerjs_core.Disposable {
216
212
  registerHTTPInterceptor(interceptor) {
217
213
  if (this._interceptors.indexOf(interceptor) !== -1) throw new Error("[HTTPService]: The interceptor has already been registered!");
218
214
  this._interceptors.push(interceptor);
219
- this._interceptors = this._interceptors.sort((a, b) => {
220
- var _a$priority, _b$priority;
221
- 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);
222
- });
215
+ this._interceptors = this._interceptors.sort((a, b) => (a.priority ?? 0) - (b.priority ?? 0));
223
216
  this._pipe = null;
224
217
  return (0, _univerjs_core.toDisposable)(() => (0, _univerjs_core.remove)(this._interceptors, interceptor));
225
218
  }
@@ -247,44 +240,29 @@ let HTTPService = class HTTPService extends _univerjs_core.Disposable {
247
240
  * @returns A promise that resolves to the HTTP response.
248
241
  */
249
242
  async request(method, url, options) {
250
- var _options$withCredenti, _options$responseType;
251
243
  return await (0, rxjs.firstValueFrom)((0, rxjs.of)(new HTTPRequest(method, url, {
252
244
  headers: new HTTPHeaders(options === null || options === void 0 ? void 0 : options.headers),
253
245
  params: new HTTPParams(options === null || options === void 0 ? void 0 : options.params),
254
- withCredentials: (_options$withCredenti = options === null || options === void 0 ? void 0 : options.withCredentials) !== null && _options$withCredenti !== void 0 ? _options$withCredenti : false,
255
- responseType: (_options$responseType = options === null || options === void 0 ? void 0 : options.responseType) !== null && _options$responseType !== void 0 ? _options$responseType : "json",
246
+ withCredentials: (options === null || options === void 0 ? void 0 : options.withCredentials) ?? false,
247
+ responseType: (options === null || options === void 0 ? void 0 : options.responseType) ?? "json",
256
248
  body: ["GET", "DELETE"].includes(method) ? void 0 : options === null || options === void 0 ? void 0 : options.body
257
249
  })).pipe((0, rxjs_operators.concatMap)((request) => this._runInterceptorsAndImplementation(request))));
258
250
  }
259
251
  /**
260
252
  * Send an HTTP request. It returns an observable that emits HTTP events. For example, it can be used to
261
253
  * send Server-Sent Events (SSE) requests.
262
- * @deprecated Please use `stream` method instead.
263
254
  * @param method HTTP request method, e.g. GET, POST, PUT, DELETE, etc.
264
255
  * @param url The URL to send the request to.
265
256
  * @param _params Optional parameters for the request.
266
257
  * @returns An observable of the HTTP event.
267
258
  */
268
259
  stream(method, url, _params) {
269
- return this.getSSE(method, url, _params);
270
- }
271
- /**
272
- * Send a Server-Sent Events (SSE) request. It returns an observable that emits HTTP events. It is the observable
273
- * pair of the `request` method.
274
- * @deprecated Please use `stream` method instead.
275
- * @param method HTTP request method, e.g. GET, POST, PUT, DELETE, etc.
276
- * @param url The URL to send the request to.
277
- * @param _params Optional parameters for the request.
278
- * @returns An observable of the HTTP event.
279
- */
280
- getSSE(method, url, _params) {
281
- var _params$withCredentia, _params$responseType;
282
260
  return (0, rxjs.of)(new HTTPRequest(method, url, {
283
261
  headers: new HTTPHeaders(_params === null || _params === void 0 ? void 0 : _params.headers),
284
262
  params: new HTTPParams(_params === null || _params === void 0 ? void 0 : _params.params),
285
- withCredentials: (_params$withCredentia = _params === null || _params === void 0 ? void 0 : _params.withCredentials) !== null && _params$withCredentia !== void 0 ? _params$withCredentia : false,
263
+ withCredentials: (_params === null || _params === void 0 ? void 0 : _params.withCredentials) ?? false,
286
264
  reportProgress: true,
287
- responseType: (_params$responseType = _params === null || _params === void 0 ? void 0 : _params.responseType) !== null && _params$responseType !== void 0 ? _params$responseType : "json",
265
+ responseType: (_params === null || _params === void 0 ? void 0 : _params.responseType) ?? "json",
288
266
  body: ["GET", "DELETE"].includes(method) ? void 0 : _params === null || _params === void 0 ? void 0 : _params.body
289
267
  })).pipe((0, rxjs_operators.concatMap)((request) => this._runInterceptorsAndImplementation(request)));
290
268
  }
@@ -469,12 +447,11 @@ let FetchHTTPImplementation = class FetchHTTPImplementation {
469
447
  this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${urlWithParams} with params ${fetchParams}`);
470
448
  response = await fetchPromise;
471
449
  } catch (error) {
472
- var _error$status, _error$statusText;
473
450
  const e = new HTTPResponseError({
474
451
  request,
475
452
  error,
476
- status: (_error$status = error.status) !== null && _error$status !== void 0 ? _error$status : 0,
477
- statusText: (_error$statusText = error.statusText) !== null && _error$statusText !== void 0 ? _error$statusText : "Unknown Error",
453
+ status: error.status ?? 0,
454
+ statusText: error.statusText ?? "Unknown Error",
478
455
  headers: error.headers
479
456
  });
480
457
  this._logService.error("[FetchHTTPImplementation]: network error", e);
@@ -521,15 +498,13 @@ let FetchHTTPImplementation = class FetchHTTPImplementation {
521
498
  chunks.push(value);
522
499
  receivedLength += value.length;
523
500
  if (reportProgress && responseType === "text") {
524
- var _partialText, _decoder;
525
- partialText = ((_partialText = partialText) !== null && _partialText !== void 0 ? _partialText : "") + ((_decoder = decoder) !== null && _decoder !== void 0 ? _decoder : decoder = new TextDecoder()).decode(value, { stream: true });
501
+ partialText = (partialText ?? "") + (decoder ??= new TextDecoder()).decode(value, { stream: true });
526
502
  subscriber.next(new HTTPProgress(contentLength ? Number.parseInt(contentLength, 10) : void 0, receivedLength, partialText));
527
503
  }
528
504
  }
529
505
  const all = mergeChunks(chunks, receivedLength);
530
506
  try {
531
- var _response$headers$get;
532
- return deserialize(request, all, (_response$headers$get = response.headers.get("content-type")) !== null && _response$headers$get !== void 0 ? _response$headers$get : "");
507
+ return deserialize(request, all, response.headers.get("content-type") ?? "");
533
508
  } catch (error) {
534
509
  const e = new HTTPResponseError({
535
510
  request,
@@ -796,9 +771,8 @@ const MergeInterceptorFactory = (config, options = {}) => {
796
771
  const DEFAULT_MAX_RETRY_ATTEMPTS = 3;
797
772
  const DELAY_INTERVAL = 1e3;
798
773
  const RetryInterceptorFactory = (params) => {
799
- var _params$maxRetryAttem, _params$delayInterval;
800
- const maxRetryAttempts = (_params$maxRetryAttem = params === null || params === void 0 ? void 0 : params.maxRetryAttempts) !== null && _params$maxRetryAttem !== void 0 ? _params$maxRetryAttem : DEFAULT_MAX_RETRY_ATTEMPTS;
801
- const delayInterval = (_params$delayInterval = params === null || params === void 0 ? void 0 : params.delayInterval) !== null && _params$delayInterval !== void 0 ? _params$delayInterval : DELAY_INTERVAL;
774
+ const maxRetryAttempts = (params === null || params === void 0 ? void 0 : params.maxRetryAttempts) ?? DEFAULT_MAX_RETRY_ATTEMPTS;
775
+ const delayInterval = (params === null || params === void 0 ? void 0 : params.delayInterval) ?? DELAY_INTERVAL;
802
776
  return (request, next) => next(request).pipe((0, rxjs_operators.retry)({
803
777
  delay: delayInterval,
804
778
  count: maxRetryAttempts
@@ -814,8 +788,7 @@ const ThresholdInterceptorFactory = (params) => {
814
788
  const handlers = [];
815
789
  const ongoingHandlers = /* @__PURE__ */ new Set();
816
790
  const tick = () => {
817
- var _params$maxParallel;
818
- 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) {
791
+ while (ongoingHandlers.size < ((params === null || params === void 0 ? void 0 : params.maxParallel) ?? 1) && handlers.length > 0) {
819
792
  const handler = handlers.shift();
820
793
  ongoingHandlers.add(handler);
821
794
  handler();
package/lib/es/facade.js CHANGED
@@ -2,7 +2,7 @@ import { FBase, FUniver } from "@univerjs/core/facade";
2
2
  import { HTTPService, WebSocketService } from "@univerjs/network";
3
3
  import { Inject, Injector } from "@univerjs/core";
4
4
 
5
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/decorateParam.js
5
+ //#region \0@oxc-project+runtime@0.140.0/helpers/esm/decorateParam.js
6
6
  function __decorateParam(paramIndex, decorator) {
7
7
  return function(target, key) {
8
8
  decorator(target, key, paramIndex);
@@ -10,7 +10,7 @@ function __decorateParam(paramIndex, decorator) {
10
10
  }
11
11
 
12
12
  //#endregion
13
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/decorate.js
13
+ //#region \0@oxc-project+runtime@0.140.0/helpers/esm/decorate.js
14
14
  function __decorate(decorators, target, key, desc) {
15
15
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
16
16
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
@@ -80,7 +80,7 @@ let FNetwork = class FNetwork extends FBase {
80
80
  * @returns {Observable<HTTPEvent>} An observable that emits the network response.
81
81
  */
82
82
  getSSE(method, url, params) {
83
- return this._httpService.getSSE(method, url, params);
83
+ return this._httpService.stream(method, url, params);
84
84
  }
85
85
  };
86
86
  FNetwork = __decorate([__decorateParam(0, Inject(Injector)), __decorateParam(1, Inject(HTTPService))], FNetwork);
package/lib/es/index.js CHANGED
@@ -4,7 +4,7 @@ import { concatMap, retry, share } from "rxjs/operators";
4
4
 
5
5
  //#region package.json
6
6
  var name = "@univerjs/network";
7
- var version = "1.0.0-alpha.7";
7
+ var version = "1.0.0-beta.0";
8
8
 
9
9
  //#endregion
10
10
  //#region src/config/config.ts
@@ -13,7 +13,7 @@ const configSymbol = Symbol(NETWORK_PLUGIN_CONFIG_KEY);
13
13
  const defaultPluginConfig = {};
14
14
 
15
15
  //#endregion
16
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/typeof.js
16
+ //#region \0@oxc-project+runtime@0.140.0/helpers/esm/typeof.js
17
17
  function _typeof(o) {
18
18
  "@babel/helpers - typeof";
19
19
  return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
@@ -24,7 +24,7 @@ function _typeof(o) {
24
24
  }
25
25
 
26
26
  //#endregion
27
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/toPrimitive.js
27
+ //#region \0@oxc-project+runtime@0.140.0/helpers/esm/toPrimitive.js
28
28
  function toPrimitive(t, r) {
29
29
  if ("object" != _typeof(t) || !t) return t;
30
30
  var e = t[Symbol.toPrimitive];
@@ -37,14 +37,14 @@ function toPrimitive(t, r) {
37
37
  }
38
38
 
39
39
  //#endregion
40
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/toPropertyKey.js
40
+ //#region \0@oxc-project+runtime@0.140.0/helpers/esm/toPropertyKey.js
41
41
  function toPropertyKey(t) {
42
42
  var i = toPrimitive(t, "string");
43
43
  return "symbol" == _typeof(i) ? i : i + "";
44
44
  }
45
45
 
46
46
  //#endregion
47
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/defineProperty.js
47
+ //#region \0@oxc-project+runtime@0.140.0/helpers/esm/defineProperty.js
48
48
  function _defineProperty(e, r, t) {
49
49
  return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
50
50
  value: t,
@@ -90,16 +90,12 @@ var HTTPHeaders = class {
90
90
  this._setHeader(key, value);
91
91
  }
92
92
  toHeadersInit(body) {
93
- var _headers$accept;
94
93
  const headers = {};
95
94
  this._headers.forEach((values, key) => {
96
95
  headers[key] = values.join(",");
97
96
  });
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
- }
97
+ headers.accept ??= "application/json, text/plain, */*";
98
+ if (!(body instanceof FormData)) headers["content-type"] ??= "application/json;charset=UTF-8";
103
99
  return headers;
104
100
  }
105
101
  _setHeader(name, value) {
@@ -167,8 +163,8 @@ var HTTPRequest = class {
167
163
  return `${this.url}${this.url.includes("?") ? "&" : "?"}${params}`;
168
164
  }
169
165
  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;
166
+ var _this$requestParams2;
167
+ const contentType = this.headers.get("Content-Type") ?? "application/json";
172
168
  const body = (_this$requestParams2 = this.requestParams) === null || _this$requestParams2 === void 0 ? void 0 : _this$requestParams2.body;
173
169
  if (body instanceof FormData) return body;
174
170
  if (isApplicationJSONType(contentType) && body && typeof body === "object") return JSON.stringify(body);
@@ -181,7 +177,7 @@ var HTTPRequest = class {
181
177
  };
182
178
 
183
179
  //#endregion
184
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/decorateParam.js
180
+ //#region \0@oxc-project+runtime@0.140.0/helpers/esm/decorateParam.js
185
181
  function __decorateParam(paramIndex, decorator) {
186
182
  return function(target, key) {
187
183
  decorator(target, key, paramIndex);
@@ -189,7 +185,7 @@ function __decorateParam(paramIndex, decorator) {
189
185
  }
190
186
 
191
187
  //#endregion
192
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/decorate.js
188
+ //#region \0@oxc-project+runtime@0.140.0/helpers/esm/decorate.js
193
189
  function __decorate(decorators, target, key, desc) {
194
190
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
195
191
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
@@ -215,10 +211,7 @@ let HTTPService = class HTTPService extends Disposable {
215
211
  registerHTTPInterceptor(interceptor) {
216
212
  if (this._interceptors.indexOf(interceptor) !== -1) throw new Error("[HTTPService]: The interceptor has already been registered!");
217
213
  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
- });
214
+ this._interceptors = this._interceptors.sort((a, b) => (a.priority ?? 0) - (b.priority ?? 0));
222
215
  this._pipe = null;
223
216
  return toDisposable(() => remove(this._interceptors, interceptor));
224
217
  }
@@ -246,44 +239,29 @@ let HTTPService = class HTTPService extends Disposable {
246
239
  * @returns A promise that resolves to the HTTP response.
247
240
  */
248
241
  async request(method, url, options) {
249
- var _options$withCredenti, _options$responseType;
250
242
  return await firstValueFrom(of(new HTTPRequest(method, url, {
251
243
  headers: new HTTPHeaders(options === null || options === void 0 ? void 0 : options.headers),
252
244
  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",
245
+ withCredentials: (options === null || options === void 0 ? void 0 : options.withCredentials) ?? false,
246
+ responseType: (options === null || options === void 0 ? void 0 : options.responseType) ?? "json",
255
247
  body: ["GET", "DELETE"].includes(method) ? void 0 : options === null || options === void 0 ? void 0 : options.body
256
248
  })).pipe(concatMap((request) => this._runInterceptorsAndImplementation(request))));
257
249
  }
258
250
  /**
259
251
  * Send an HTTP request. It returns an observable that emits HTTP events. For example, it can be used to
260
252
  * send Server-Sent Events (SSE) requests.
261
- * @deprecated Please use `stream` method instead.
262
253
  * @param method HTTP request method, e.g. GET, POST, PUT, DELETE, etc.
263
254
  * @param url The URL to send the request to.
264
255
  * @param _params Optional parameters for the request.
265
256
  * @returns An observable of the HTTP event.
266
257
  */
267
258
  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
259
  return of(new HTTPRequest(method, url, {
282
260
  headers: new HTTPHeaders(_params === null || _params === void 0 ? void 0 : _params.headers),
283
261
  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,
262
+ withCredentials: (_params === null || _params === void 0 ? void 0 : _params.withCredentials) ?? false,
285
263
  reportProgress: true,
286
- responseType: (_params$responseType = _params === null || _params === void 0 ? void 0 : _params.responseType) !== null && _params$responseType !== void 0 ? _params$responseType : "json",
264
+ responseType: (_params === null || _params === void 0 ? void 0 : _params.responseType) ?? "json",
287
265
  body: ["GET", "DELETE"].includes(method) ? void 0 : _params === null || _params === void 0 ? void 0 : _params.body
288
266
  })).pipe(concatMap((request) => this._runInterceptorsAndImplementation(request)));
289
267
  }
@@ -468,12 +446,11 @@ let FetchHTTPImplementation = class FetchHTTPImplementation {
468
446
  this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${urlWithParams} with params ${fetchParams}`);
469
447
  response = await fetchPromise;
470
448
  } catch (error) {
471
- var _error$status, _error$statusText;
472
449
  const e = new HTTPResponseError({
473
450
  request,
474
451
  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",
452
+ status: error.status ?? 0,
453
+ statusText: error.statusText ?? "Unknown Error",
477
454
  headers: error.headers
478
455
  });
479
456
  this._logService.error("[FetchHTTPImplementation]: network error", e);
@@ -520,15 +497,13 @@ let FetchHTTPImplementation = class FetchHTTPImplementation {
520
497
  chunks.push(value);
521
498
  receivedLength += value.length;
522
499
  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 });
500
+ partialText = (partialText ?? "") + (decoder ??= new TextDecoder()).decode(value, { stream: true });
525
501
  subscriber.next(new HTTPProgress(contentLength ? Number.parseInt(contentLength, 10) : void 0, receivedLength, partialText));
526
502
  }
527
503
  }
528
504
  const all = mergeChunks(chunks, receivedLength);
529
505
  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 : "");
506
+ return deserialize(request, all, response.headers.get("content-type") ?? "");
532
507
  } catch (error) {
533
508
  const e = new HTTPResponseError({
534
509
  request,
@@ -795,9 +770,8 @@ const MergeInterceptorFactory = (config, options = {}) => {
795
770
  const DEFAULT_MAX_RETRY_ATTEMPTS = 3;
796
771
  const DELAY_INTERVAL = 1e3;
797
772
  const RetryInterceptorFactory = (params) => {
798
- var _params$maxRetryAttem, _params$delayInterval;
799
- const maxRetryAttempts = (_params$maxRetryAttem = params === null || params === void 0 ? void 0 : params.maxRetryAttempts) !== null && _params$maxRetryAttem !== void 0 ? _params$maxRetryAttem : DEFAULT_MAX_RETRY_ATTEMPTS;
800
- const delayInterval = (_params$delayInterval = params === null || params === void 0 ? void 0 : params.delayInterval) !== null && _params$delayInterval !== void 0 ? _params$delayInterval : DELAY_INTERVAL;
773
+ const maxRetryAttempts = (params === null || params === void 0 ? void 0 : params.maxRetryAttempts) ?? DEFAULT_MAX_RETRY_ATTEMPTS;
774
+ const delayInterval = (params === null || params === void 0 ? void 0 : params.delayInterval) ?? DELAY_INTERVAL;
801
775
  return (request, next) => next(request).pipe(retry({
802
776
  delay: delayInterval,
803
777
  count: maxRetryAttempts
@@ -813,8 +787,7 @@ const ThresholdInterceptorFactory = (params) => {
813
787
  const handlers = [];
814
788
  const ongoingHandlers = /* @__PURE__ */ new Set();
815
789
  const tick = () => {
816
- var _params$maxParallel;
817
- 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) {
790
+ while (ongoingHandlers.size < ((params === null || params === void 0 ? void 0 : params.maxParallel) ?? 1) && handlers.length > 0) {
818
791
  const handler = handlers.shift();
819
792
  ongoingHandlers.add(handler);
820
793
  handler();
package/lib/facade.js CHANGED
@@ -2,7 +2,7 @@ import { FBase, FUniver } from "@univerjs/core/facade";
2
2
  import { HTTPService, WebSocketService } from "@univerjs/network";
3
3
  import { Inject, Injector } from "@univerjs/core";
4
4
 
5
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/decorateParam.js
5
+ //#region \0@oxc-project+runtime@0.140.0/helpers/esm/decorateParam.js
6
6
  function __decorateParam(paramIndex, decorator) {
7
7
  return function(target, key) {
8
8
  decorator(target, key, paramIndex);
@@ -10,7 +10,7 @@ function __decorateParam(paramIndex, decorator) {
10
10
  }
11
11
 
12
12
  //#endregion
13
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/decorate.js
13
+ //#region \0@oxc-project+runtime@0.140.0/helpers/esm/decorate.js
14
14
  function __decorate(decorators, target, key, desc) {
15
15
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
16
16
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
@@ -80,7 +80,7 @@ let FNetwork = class FNetwork extends FBase {
80
80
  * @returns {Observable<HTTPEvent>} An observable that emits the network response.
81
81
  */
82
82
  getSSE(method, url, params) {
83
- return this._httpService.getSSE(method, url, params);
83
+ return this._httpService.stream(method, url, params);
84
84
  }
85
85
  };
86
86
  FNetwork = __decorate([__decorateParam(0, Inject(Injector)), __decorateParam(1, Inject(HTTPService))], FNetwork);
package/lib/index.js CHANGED
@@ -4,7 +4,7 @@ import { concatMap, retry, share } from "rxjs/operators";
4
4
 
5
5
  //#region package.json
6
6
  var name = "@univerjs/network";
7
- var version = "1.0.0-alpha.7";
7
+ var version = "1.0.0-beta.0";
8
8
 
9
9
  //#endregion
10
10
  //#region src/config/config.ts
@@ -13,7 +13,7 @@ const configSymbol = Symbol(NETWORK_PLUGIN_CONFIG_KEY);
13
13
  const defaultPluginConfig = {};
14
14
 
15
15
  //#endregion
16
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/typeof.js
16
+ //#region \0@oxc-project+runtime@0.140.0/helpers/esm/typeof.js
17
17
  function _typeof(o) {
18
18
  "@babel/helpers - typeof";
19
19
  return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
@@ -24,7 +24,7 @@ function _typeof(o) {
24
24
  }
25
25
 
26
26
  //#endregion
27
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/toPrimitive.js
27
+ //#region \0@oxc-project+runtime@0.140.0/helpers/esm/toPrimitive.js
28
28
  function toPrimitive(t, r) {
29
29
  if ("object" != _typeof(t) || !t) return t;
30
30
  var e = t[Symbol.toPrimitive];
@@ -37,14 +37,14 @@ function toPrimitive(t, r) {
37
37
  }
38
38
 
39
39
  //#endregion
40
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/toPropertyKey.js
40
+ //#region \0@oxc-project+runtime@0.140.0/helpers/esm/toPropertyKey.js
41
41
  function toPropertyKey(t) {
42
42
  var i = toPrimitive(t, "string");
43
43
  return "symbol" == _typeof(i) ? i : i + "";
44
44
  }
45
45
 
46
46
  //#endregion
47
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/defineProperty.js
47
+ //#region \0@oxc-project+runtime@0.140.0/helpers/esm/defineProperty.js
48
48
  function _defineProperty(e, r, t) {
49
49
  return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
50
50
  value: t,
@@ -90,16 +90,12 @@ var HTTPHeaders = class {
90
90
  this._setHeader(key, value);
91
91
  }
92
92
  toHeadersInit(body) {
93
- var _headers$accept;
94
93
  const headers = {};
95
94
  this._headers.forEach((values, key) => {
96
95
  headers[key] = values.join(",");
97
96
  });
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
- }
97
+ headers.accept ??= "application/json, text/plain, */*";
98
+ if (!(body instanceof FormData)) headers["content-type"] ??= "application/json;charset=UTF-8";
103
99
  return headers;
104
100
  }
105
101
  _setHeader(name, value) {
@@ -167,8 +163,8 @@ var HTTPRequest = class {
167
163
  return `${this.url}${this.url.includes("?") ? "&" : "?"}${params}`;
168
164
  }
169
165
  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;
166
+ var _this$requestParams2;
167
+ const contentType = this.headers.get("Content-Type") ?? "application/json";
172
168
  const body = (_this$requestParams2 = this.requestParams) === null || _this$requestParams2 === void 0 ? void 0 : _this$requestParams2.body;
173
169
  if (body instanceof FormData) return body;
174
170
  if (isApplicationJSONType(contentType) && body && typeof body === "object") return JSON.stringify(body);
@@ -181,7 +177,7 @@ var HTTPRequest = class {
181
177
  };
182
178
 
183
179
  //#endregion
184
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/decorateParam.js
180
+ //#region \0@oxc-project+runtime@0.140.0/helpers/esm/decorateParam.js
185
181
  function __decorateParam(paramIndex, decorator) {
186
182
  return function(target, key) {
187
183
  decorator(target, key, paramIndex);
@@ -189,7 +185,7 @@ function __decorateParam(paramIndex, decorator) {
189
185
  }
190
186
 
191
187
  //#endregion
192
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/decorate.js
188
+ //#region \0@oxc-project+runtime@0.140.0/helpers/esm/decorate.js
193
189
  function __decorate(decorators, target, key, desc) {
194
190
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
195
191
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
@@ -215,10 +211,7 @@ let HTTPService = class HTTPService extends Disposable {
215
211
  registerHTTPInterceptor(interceptor) {
216
212
  if (this._interceptors.indexOf(interceptor) !== -1) throw new Error("[HTTPService]: The interceptor has already been registered!");
217
213
  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
- });
214
+ this._interceptors = this._interceptors.sort((a, b) => (a.priority ?? 0) - (b.priority ?? 0));
222
215
  this._pipe = null;
223
216
  return toDisposable(() => remove(this._interceptors, interceptor));
224
217
  }
@@ -246,44 +239,29 @@ let HTTPService = class HTTPService extends Disposable {
246
239
  * @returns A promise that resolves to the HTTP response.
247
240
  */
248
241
  async request(method, url, options) {
249
- var _options$withCredenti, _options$responseType;
250
242
  return await firstValueFrom(of(new HTTPRequest(method, url, {
251
243
  headers: new HTTPHeaders(options === null || options === void 0 ? void 0 : options.headers),
252
244
  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",
245
+ withCredentials: (options === null || options === void 0 ? void 0 : options.withCredentials) ?? false,
246
+ responseType: (options === null || options === void 0 ? void 0 : options.responseType) ?? "json",
255
247
  body: ["GET", "DELETE"].includes(method) ? void 0 : options === null || options === void 0 ? void 0 : options.body
256
248
  })).pipe(concatMap((request) => this._runInterceptorsAndImplementation(request))));
257
249
  }
258
250
  /**
259
251
  * Send an HTTP request. It returns an observable that emits HTTP events. For example, it can be used to
260
252
  * send Server-Sent Events (SSE) requests.
261
- * @deprecated Please use `stream` method instead.
262
253
  * @param method HTTP request method, e.g. GET, POST, PUT, DELETE, etc.
263
254
  * @param url The URL to send the request to.
264
255
  * @param _params Optional parameters for the request.
265
256
  * @returns An observable of the HTTP event.
266
257
  */
267
258
  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
259
  return of(new HTTPRequest(method, url, {
282
260
  headers: new HTTPHeaders(_params === null || _params === void 0 ? void 0 : _params.headers),
283
261
  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,
262
+ withCredentials: (_params === null || _params === void 0 ? void 0 : _params.withCredentials) ?? false,
285
263
  reportProgress: true,
286
- responseType: (_params$responseType = _params === null || _params === void 0 ? void 0 : _params.responseType) !== null && _params$responseType !== void 0 ? _params$responseType : "json",
264
+ responseType: (_params === null || _params === void 0 ? void 0 : _params.responseType) ?? "json",
287
265
  body: ["GET", "DELETE"].includes(method) ? void 0 : _params === null || _params === void 0 ? void 0 : _params.body
288
266
  })).pipe(concatMap((request) => this._runInterceptorsAndImplementation(request)));
289
267
  }
@@ -468,12 +446,11 @@ let FetchHTTPImplementation = class FetchHTTPImplementation {
468
446
  this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${urlWithParams} with params ${fetchParams}`);
469
447
  response = await fetchPromise;
470
448
  } catch (error) {
471
- var _error$status, _error$statusText;
472
449
  const e = new HTTPResponseError({
473
450
  request,
474
451
  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",
452
+ status: error.status ?? 0,
453
+ statusText: error.statusText ?? "Unknown Error",
477
454
  headers: error.headers
478
455
  });
479
456
  this._logService.error("[FetchHTTPImplementation]: network error", e);
@@ -520,15 +497,13 @@ let FetchHTTPImplementation = class FetchHTTPImplementation {
520
497
  chunks.push(value);
521
498
  receivedLength += value.length;
522
499
  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 });
500
+ partialText = (partialText ?? "") + (decoder ??= new TextDecoder()).decode(value, { stream: true });
525
501
  subscriber.next(new HTTPProgress(contentLength ? Number.parseInt(contentLength, 10) : void 0, receivedLength, partialText));
526
502
  }
527
503
  }
528
504
  const all = mergeChunks(chunks, receivedLength);
529
505
  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 : "");
506
+ return deserialize(request, all, response.headers.get("content-type") ?? "");
532
507
  } catch (error) {
533
508
  const e = new HTTPResponseError({
534
509
  request,
@@ -795,9 +770,8 @@ const MergeInterceptorFactory = (config, options = {}) => {
795
770
  const DEFAULT_MAX_RETRY_ATTEMPTS = 3;
796
771
  const DELAY_INTERVAL = 1e3;
797
772
  const RetryInterceptorFactory = (params) => {
798
- var _params$maxRetryAttem, _params$delayInterval;
799
- const maxRetryAttempts = (_params$maxRetryAttem = params === null || params === void 0 ? void 0 : params.maxRetryAttempts) !== null && _params$maxRetryAttem !== void 0 ? _params$maxRetryAttem : DEFAULT_MAX_RETRY_ATTEMPTS;
800
- const delayInterval = (_params$delayInterval = params === null || params === void 0 ? void 0 : params.delayInterval) !== null && _params$delayInterval !== void 0 ? _params$delayInterval : DELAY_INTERVAL;
773
+ const maxRetryAttempts = (params === null || params === void 0 ? void 0 : params.maxRetryAttempts) ?? DEFAULT_MAX_RETRY_ATTEMPTS;
774
+ const delayInterval = (params === null || params === void 0 ? void 0 : params.delayInterval) ?? DELAY_INTERVAL;
801
775
  return (request, next) => next(request).pipe(retry({
802
776
  delay: delayInterval,
803
777
  count: maxRetryAttempts
@@ -813,8 +787,7 @@ const ThresholdInterceptorFactory = (params) => {
813
787
  const handlers = [];
814
788
  const ongoingHandlers = /* @__PURE__ */ new Set();
815
789
  const tick = () => {
816
- var _params$maxParallel;
817
- 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) {
790
+ while (ongoingHandlers.size < ((params === null || params === void 0 ? void 0 : params.maxParallel) ?? 1) && handlers.length > 0) {
818
791
  const handler = handlers.shift();
819
792
  ongoingHandlers.add(handler);
820
793
  handler();
@@ -62,13 +62,13 @@ interface IFUniverNetworkMixin {
62
62
  * console.log('websocket error', error);
63
63
  * });
64
64
  *
65
- * univerAPI.onCommandExecuted((command, options) => {
65
+ * univerAPI.addEvent(univerAPI.Event.CommandExecuted, ({ id, type, params, options }) => {
66
66
  * // Only synchronize local mutations
67
- * if (command.type !== 2 || options?.fromCollab || options?.onlyLocal || command.id === 'doc.mutation.rich-text-editing') {
67
+ * if (type !== univerAPI.Enum.CommandType.MUTATION || options?.fromCollab || options?.onlyLocal || id === 'doc.mutation.rich-text-editing') {
68
68
  * return;
69
69
  * }
70
70
  *
71
- * const commandInfo = JSON.stringify({ command, options: { fromCollab: true } });
71
+ * const commandInfo = JSON.stringify({ command: { id, type, params }, options: { fromCollab: true } });
72
72
  * ws.send(commandInfo);
73
73
  * });
74
74
  * ```
@@ -89,22 +89,11 @@ export declare class HTTPService extends Disposable {
89
89
  /**
90
90
  * Send an HTTP request. It returns an observable that emits HTTP events. For example, it can be used to
91
91
  * send Server-Sent Events (SSE) requests.
92
- * @deprecated Please use `stream` method instead.
93
92
  * @param method HTTP request method, e.g. GET, POST, PUT, DELETE, etc.
94
93
  * @param url The URL to send the request to.
95
94
  * @param _params Optional parameters for the request.
96
95
  * @returns An observable of the HTTP event.
97
96
  */
98
- stream<T>(method: HTTPRequestMethod, url: string, _params?: IRequestParams): Observable<HTTPEvent<T>>;
99
- /**
100
- * Send a Server-Sent Events (SSE) request. It returns an observable that emits HTTP events. It is the observable
101
- * pair of the `request` method.
102
- * @deprecated Please use `stream` method instead.
103
- * @param method HTTP request method, e.g. GET, POST, PUT, DELETE, etc.
104
- * @param url The URL to send the request to.
105
- * @param _params Optional parameters for the request.
106
- * @returns An observable of the HTTP event.
107
- */
108
- getSSE<T>(method: HTTPRequestMethod, url: string, _params?: IPostRequestParams): Observable<HTTPEvent<T>>;
97
+ stream<T>(method: HTTPRequestMethod, url: string, _params?: IPostRequestParams): Observable<HTTPEvent<T>>;
109
98
  private _runInterceptorsAndImplementation;
110
99
  }
package/lib/umd/facade.js CHANGED
@@ -1 +1 @@
1
- (function(e,t){typeof exports==`object`&&typeof module<`u`?t(require("@univerjs/core/facade"),require("@univerjs/network"),require("@univerjs/core")):typeof define==`function`&&define.amd?define([`@univerjs/core/facade`,`@univerjs/network`,`@univerjs/core`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.UniverCoreFacade,e.UniverNetwork,e.UniverCore))})(this,function(e,t,n){function r(e,t){return function(n,r){t(n,r,e)}}function i(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 a=class extends e.FBase{constructor(e,t){super(),this._injector=e,this._httpService=t}get(e,t){return this._httpService.get(e,t)}post(e,t){return this._httpService.post(e,t)}put(e,t){return this._httpService.put(e,t)}delete(e,t){return this._httpService.delete(e,t)}patch(e,t){return this._httpService.patch(e,t)}getSSE(e,t,n){return this._httpService.getSSE(e,t,n)}};a=i([r(0,(0,n.Inject)(n.Injector)),r(1,(0,n.Inject)(t.HTTPService))],a);var o=class extends e.FUniver{getNetwork(){return this._injector.createInstance(a)}createSocket(e){let n=this._injector.createInstance(t.WebSocketService).createSocket(e);if(!n)throw Error(`[WebSocketService]: failed to create socket!`);return n}};e.FUniver.extend(o)});
1
+ (function(e,t){typeof exports==`object`&&typeof module<`u`?t(require("@univerjs/core/facade"),require("@univerjs/network"),require("@univerjs/core")):typeof define==`function`&&define.amd?define([`@univerjs/core/facade`,`@univerjs/network`,`@univerjs/core`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.UniverCoreFacade,e.UniverNetwork,e.UniverCore))})(this,function(e,t,n){function r(e,t){return function(n,r){t(n,r,e)}}function i(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 a=class extends e.FBase{constructor(e,t){super(),this._injector=e,this._httpService=t}get(e,t){return this._httpService.get(e,t)}post(e,t){return this._httpService.post(e,t)}put(e,t){return this._httpService.put(e,t)}delete(e,t){return this._httpService.delete(e,t)}patch(e,t){return this._httpService.patch(e,t)}getSSE(e,t,n){return this._httpService.stream(e,t,n)}};a=i([r(0,(0,n.Inject)(n.Injector)),r(1,(0,n.Inject)(t.HTTPService))],a);var o=class extends e.FUniver{getNetwork(){return this._injector.createInstance(a)}createSocket(e){let n=this._injector.createInstance(t.WebSocketService).createSocket(e);if(!n)throw Error(`[WebSocketService]: failed to create socket!`);return n}};e.FUniver.extend(o)});
package/lib/umd/index.js CHANGED
@@ -1,2 +1,2 @@
1
- (function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports,require("@univerjs/core"),require("rxjs"),require("rxjs/operators")):typeof define==`function`&&define.amd?define([`exports`,`@univerjs/core`,`rxjs`,`rxjs/operators`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.UniverNetwork={},e.UniverCore,e.rxjs,e.rxjs.operators))})(this,function(e,t,n,r){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var i=`@univerjs/network`,a=`1.0.0-alpha.7`;let o={};function s(e){"@babel/helpers - typeof";return s=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},s(e)}function c(e,t){if(s(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(s(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function l(e){var t=c(e,`string`);return s(t)==`symbol`?t:t+``}function u(e,t,n){return(t=l(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}let d=`application/json`;function f(e){return Array.isArray(e)?e.some(e=>e.includes(d)):e.includes(d)}var p=class{constructor(e){u(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))}};let m=(0,t.createIdentifier)(`network.http-implementation`);var h=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 g=0;var _=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,u(this,`uid`,g++)}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?d:e,r=(t=this.requestParams)==null?void 0:t.body;return r instanceof FormData?r:f(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 v(e,t){return function(n,r){t(n,r,e)}}function y(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 b=class extends t.Disposable{constructor(e){super(),this._http=e,u(this,`_interceptors`,[]),u(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,(0,t.toDisposable)(()=>(0,t.remove)(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,i){var a,o;return await(0,n.firstValueFrom)((0,n.of)(new _(e,t,{headers:new p(i==null?void 0:i.headers),params:new h(i==null?void 0:i.params),withCredentials:(a=i==null?void 0:i.withCredentials)==null?!1:a,responseType:(o=i==null?void 0:i.responseType)==null?`json`:o,body:[`GET`,`DELETE`].includes(e)||i==null?void 0:i.body})).pipe((0,r.concatMap)(e=>this._runInterceptorsAndImplementation(e))))}stream(e,t,n){return this.getSSE(e,t,n)}getSSE(e,t,i){var a,o;return(0,n.of)(new _(e,t,{headers:new p(i==null?void 0:i.headers),params:new h(i==null?void 0:i.params),withCredentials:(a=i==null?void 0:i.withCredentials)==null?!1:a,reportProgress:!0,responseType:(o=i==null?void 0:i.responseType)==null?`json`:o,body:[`GET`,`DELETE`].includes(e)||i==null?void 0:i.body})).pipe((0,r.concatMap)(e=>this._runInterceptorsAndImplementation(e)))}_runInterceptorsAndImplementation(e){return this._pipe||(this._pipe=this._interceptors.map(e=>e.interceptor).reduceRight((e,t)=>x(e,t),(e,t)=>t(e))),this._pipe(e,e=>this._http.send(e))}};b=y([v(0,m)],b);function x(e,t){return(n,r)=>t(n,t=>e(t,r))}let S=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}({}),C=function(e){return e[e.DownloadProgress=0]=`DownloadProgress`,e[e.Response=1]=`Response`,e}({});var w=class{constructor({body:e,headers:t,status:n,statusText:r}){u(this,`type`,1),u(this,`body`,void 0),u(this,`headers`,void 0),u(this,`status`,void 0),u(this,`statusText`,void 0),this.body=e,this.headers=t,this.status=n,this.statusText=r}},T=class{constructor(e,t,n){this.total=e,this.loaded=t,this.partialText=n,u(this,`type`,0)}},E=class{constructor(e,t,n){this.headers=e,this.status=t,this.statusText=n}},D=class{constructor({request:e,headers:t,status:n,statusText:r,error:i}){u(this,`request`,void 0),u(this,`headers`,void 0),u(this,`status`,void 0),u(this,`statusText`,void 0),u(this,`error`,void 0),this.request=e,this.headers=t,this.status=n,this.statusText=r,this.error=i}};function O(e){return{method:e.method,headers:e.getHeadersInit(),body:e.getBody(),credentials:e.withCredentials?`include`:void 0}}let k=class{constructor(e){this._logService=e}send(e){return new n.Observable(t=>{let n=new AbortController;return this._send(e,t,n).catch(n=>{t.error(new D({error:n,request:e}))}),()=>n.abort()})}async _send(e,t,n){let r;try{let t=O(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 D({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 p(r.headers),s=r.status,c=r.statusText,l=null;if(r.body&&(l=await this._readBody(e,r,t)),s>=200&&s<300)t.next(new w({body:l,headers:o,status:s,statusText:c}));else{let n=new D({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,m;u=((f=u)==null?``:f)+((m=d)==null?d=new TextDecoder:m).decode(t,{stream:!0}),n.next(new T(o?Number.parseInt(o,10):void 0,s,u))}}let h=A(i,s);try{var g;return M(e,h,(g=t.headers.get(`content-type`))==null?``:g)}catch(r){let i=new D({request:e,error:r,status:t.status,statusText:t.statusText,headers:new p(t.headers)});return this._logService.error(`[FetchHTTPImplementation]: network error`,i),n.error(i),null}}};k=y([v(0,t.ILogService)],k);function A(e,t){let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}let j=/^\)\]\}',?\n/;function M(e,t,n){switch(e.responseType){case`json`:let r=new TextDecoder().decode(t).replace(j,``);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 N=class{constructor(e){this._logService=e}send(e){return new n.Observable(t=>{let n=new XMLHttpRequest,r=e.getUrlWithParams(),i=O(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 E(new p(n.getAllResponseHeaders()),n.status,e)},s=()=>{let{headers:r,statusText:i,status:s}=o(),c=null,l=null;s!==204&&(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 w({body:c,headers:r,status:s,statusText:i}));else{let n=new D({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 D({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)}})}};N=y([v(0,t.ILogService)],N);let P=class extends t.Plugin{constructor(e=o,n,r,i){super(),this._config=e,this._logger=n,this._injector=r,this._configService=i;let{...a}=(0,t.merge)({},o,this._config);this._configService.setConfig(`network.config`,a)}onStarting(){var e,n,r;if(this._injector.get(b,t.Quantity.OPTIONAL,t.LookUp.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 i=(n=this._config)!=null&&n.useFetchImpl?k:typeof window<`u`?N:k;(0,t.registerDependencies)(this._injector,(0,t.mergeOverrideWithDependencies)([[b],[m,{useClass:i}]],(r=this._config)==null?void 0:r.override))}};u(P,`pluginName`,`UNIVER_NETWORK_PLUGIN`),u(P,`packageName`,i),u(P,`version`,a),P=y([v(1,t.ILogService),v(2,(0,t.Inject)(t.Injector)),v(3,t.IConfigService)],P);let F=e=>{let{errorStatusCodes:t,onAuthError:r}=e;return(e,i)=>i(e).pipe((0,n.catchError)(e=>(e instanceof D&&t.some(t=>t===e.status)&&r(),(0,n.throwError)(()=>e))))},I=(e=300)=>{let n=t.noop;return t=>new Promise(t=>{n();let r=setTimeout(()=>{t(!0)},e);n=()=>{clearTimeout(r),t(!1)}})},L=()=>(e,t)=>t.map(t=>({config:t,result:e})),R=(e,r={})=>{let{isMatch:i,getParamsFromRequest:a,mergeParamsToRequest:o}=e,{fetchCheck:s=I(300),distributeResult:c=L()}=r,l=[],u=e=>e.map(e=>e.config);return(e,r)=>i(e)?new n.Observable(n=>{let i={next:e=>n.next(e),error:e=>n.error(e),config:a(e),active:!0};l.push(i);let d=u(l);return s(e).then(t=>{if(t){let t=[];d.forEach(e=>{let n=l.findIndex(t=>t.config===e);if(n>=0){let[e]=l.splice(n,1);t.push(e)}});let i=u(t);if(!i.length)return;let a={hooks:t};t.forEach(e=>e.batch=a),a.subscription=r(o(i,e)).subscribe({next:e=>{if(e.type===1){let n=e.body,r=c(n,i);t.forEach(t=>{let n=r.find(e=>e.config===t.config);if(n){let r=new w({body:n.result,headers:e.headers,status:e.status,statusText:e.statusText});t.next(r)}else t.error(`batch error`)})}},complete:()=>n.complete(),error:e=>n.error(e)})}}),()=>{var e;if(i.active=!1,(0,t.remove)(l,i),(e=i.batch)!=null&&e.hooks.every(e=>!e.active)){var n;(n=i.batch.subscription)==null||n.unsubscribe()}}}):r(e)},z=e=>{var t,n;let i=(t=e==null?void 0:e.maxRetryAttempts)==null?3:t,a=(n=e==null?void 0:e.delayInterval)==null?1e3:n;return(e,t)=>t(e).pipe((0,r.retry)({delay:a,count:i}))},B=e=>{let r=[],i=new Set,a=()=>{for(var t;i.size<((t=e==null?void 0:e.maxParallel)==null?1:t)&&r.length>0;){let e=r.shift();i.add(e),e()}};return(e,o)=>new n.Observable(n=>{let s,c=()=>{s=o(e).subscribe({next:e=>n.next(e),error:e=>n.error(e),complete:()=>n.complete()})};return r.push(c),a(),()=>{s==null||s.unsubscribe(),i.delete(c),(0,t.remove)(r,c),a()}})},V=(0,t.createIdentifier)(`univer.network.socket.service`);var H=class extends t.Disposable{createSocket(e){try{let i=new WebSocket(e),a=new t.DisposableCollection;return{URL:e,close:(e,t)=>{i.close(e,t),a.dispose()},send:e=>{i.send(e)},open$:new n.Observable(e=>{let n=t=>e.next(t);i.addEventListener(`open`,n),a.add((0,t.toDisposable)(()=>i.removeEventListener(`open`,n)))}).pipe((0,r.share)()),close$:new n.Observable(e=>{let n=t=>e.next(t);i.addEventListener(`close`,n),a.add((0,t.toDisposable)(()=>i.removeEventListener(`close`,n)))}).pipe((0,r.share)()),error$:new n.Observable(e=>{let n=t=>e.next(t);i.addEventListener(`error`,n),a.add((0,t.toDisposable)(()=>i.removeEventListener(`error`,n)))}).pipe((0,r.share)()),message$:new n.Observable(e=>{let n=t=>e.next(t);i.addEventListener(`message`,n),a.add((0,t.toDisposable)(()=>i.removeEventListener(`message`,n)))}).pipe((0,r.share)())}}catch(e){return console.error(e),null}}};e.AuthInterceptorFactory=F,Object.defineProperty(e,"FetchHTTPImplementation",{enumerable:!0,get:function(){return k}}),e.HTTPEventType=C,e.HTTPHeaders=p,e.HTTPProgress=T,e.HTTPRequest=_,e.HTTPResponse=w,e.HTTPResponseError=D,Object.defineProperty(e,"HTTPService",{enumerable:!0,get:function(){return b}}),e.HTTPStatusCode=S,e.IHTTPImplementation=m,e.ISocketService=V,e.MergeInterceptorFactory=R,e.ResponseHeader=E,e.RetryInterceptorFactory=z,e.ThresholdInterceptorFactory=B,Object.defineProperty(e,"UniverNetworkPlugin",{enumerable:!0,get:function(){return P}}),e.WebSocketService=H,Object.defineProperty(e,"XHRHTTPImplementation",{enumerable:!0,get:function(){return N}})});
1
+ (function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports,require("@univerjs/core"),require("rxjs"),require("rxjs/operators")):typeof define==`function`&&define.amd?define([`exports`,`@univerjs/core`,`rxjs`,`rxjs/operators`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.UniverNetwork={},e.UniverCore,e.rxjs,e.rxjs.operators))})(this,function(e,t,n,r){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var i=`@univerjs/network`,a=`1.0.0-beta.0`;let o={};function s(e){"@babel/helpers - typeof";return s=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},s(e)}function c(e,t){if(s(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(s(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function l(e){var t=c(e,`string`);return s(t)==`symbol`?t:t+``}function u(e,t,n){return(t=l(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}let d=`application/json`;function f(e){return Array.isArray(e)?e.some(e=>e.includes(d)):e.includes(d)}var p=class{constructor(e){u(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??=`application/json, text/plain, */*`,e instanceof FormData||(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))}};let m=(0,t.createIdentifier)(`network.http-implementation`);var h=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 g=0;var _=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,u(this,`uid`,g++)}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;let t=this.headers.get(`Content-Type`)??`application/json`,n=(e=this.requestParams)==null?void 0:e.body;return n instanceof FormData?n:f(t)&&n&&typeof n==`object`?JSON.stringify(n):n?`${n}`:null}getHeadersInit(){var e;return this.headers.toHeadersInit((e=this.requestParams)==null?void 0:e.body)}};function v(e,t){return function(n,r){t(n,r,e)}}function y(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 b=class extends t.Disposable{constructor(e){super(),this._http=e,u(this,`_interceptors`,[]),u(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)=>(e.priority??0)-(t.priority??0)),this._pipe=null,(0,t.toDisposable)(()=>(0,t.remove)(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,i){return await(0,n.firstValueFrom)((0,n.of)(new _(e,t,{headers:new p(i==null?void 0:i.headers),params:new h(i==null?void 0:i.params),withCredentials:(i==null?void 0:i.withCredentials)??!1,responseType:(i==null?void 0:i.responseType)??`json`,body:[`GET`,`DELETE`].includes(e)||i==null?void 0:i.body})).pipe((0,r.concatMap)(e=>this._runInterceptorsAndImplementation(e))))}stream(e,t,i){return(0,n.of)(new _(e,t,{headers:new p(i==null?void 0:i.headers),params:new h(i==null?void 0:i.params),withCredentials:(i==null?void 0:i.withCredentials)??!1,reportProgress:!0,responseType:(i==null?void 0:i.responseType)??`json`,body:[`GET`,`DELETE`].includes(e)||i==null?void 0:i.body})).pipe((0,r.concatMap)(e=>this._runInterceptorsAndImplementation(e)))}_runInterceptorsAndImplementation(e){return this._pipe||=this._interceptors.map(e=>e.interceptor).reduceRight((e,t)=>x(e,t),(e,t)=>t(e)),this._pipe(e,e=>this._http.send(e))}};b=y([v(0,m)],b);function x(e,t){return(n,r)=>t(n,t=>e(t,r))}let S=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}({}),C=function(e){return e[e.DownloadProgress=0]=`DownloadProgress`,e[e.Response=1]=`Response`,e}({});var w=class{constructor({body:e,headers:t,status:n,statusText:r}){u(this,`type`,1),u(this,`body`,void 0),u(this,`headers`,void 0),u(this,`status`,void 0),u(this,`statusText`,void 0),this.body=e,this.headers=t,this.status=n,this.statusText=r}},T=class{constructor(e,t,n){this.total=e,this.loaded=t,this.partialText=n,u(this,`type`,0)}},E=class{constructor(e,t,n){this.headers=e,this.status=t,this.statusText=n}},D=class{constructor({request:e,headers:t,status:n,statusText:r,error:i}){u(this,`request`,void 0),u(this,`headers`,void 0),u(this,`status`,void 0),u(this,`statusText`,void 0),u(this,`error`,void 0),this.request=e,this.headers=t,this.status=n,this.statusText=r,this.error=i}};function O(e){return{method:e.method,headers:e.getHeadersInit(),body:e.getBody(),credentials:e.withCredentials?`include`:void 0}}let k=class{constructor(e){this._logService=e}send(e){return new n.Observable(t=>{let n=new AbortController;return this._send(e,t,n).catch(n=>{t.error(new D({error:n,request:e}))}),()=>n.abort()})}async _send(e,t,n){let r;try{let t=O(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){let r=new D({request:e,error:n,status:n.status??0,statusText:n.statusText??`Unknown Error`,headers:n.headers});this._logService.error(`[FetchHTTPImplementation]: network error`,r),t.error(r);return}let i=new p(r.headers),a=r.status,o=r.statusText,s=null;if(r.body&&(s=await this._readBody(e,r,t)),a>=200&&a<300)t.next(new w({body:s,headers:i,status:a,statusText:o}));else{let n=new D({request:e,error:s,status:a,statusText:o,headers:i});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;i.push(t),s+=t.length,c&&l===`text`&&(u=(u??``)+(d??=new TextDecoder).decode(t,{stream:!0}),n.next(new T(o?Number.parseInt(o,10):void 0,s,u)))}let f=A(i,s);try{return M(e,f,t.headers.get(`content-type`)??``)}catch(r){let i=new D({request:e,error:r,status:t.status,statusText:t.statusText,headers:new p(t.headers)});return this._logService.error(`[FetchHTTPImplementation]: network error`,i),n.error(i),null}}};k=y([v(0,t.ILogService)],k);function A(e,t){let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}let j=/^\)\]\}',?\n/;function M(e,t,n){switch(e.responseType){case`json`:let r=new TextDecoder().decode(t).replace(j,``);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 N=class{constructor(e){this._logService=e}send(e){return new n.Observable(t=>{let n=new XMLHttpRequest,r=e.getUrlWithParams(),i=O(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 E(new p(n.getAllResponseHeaders()),n.status,e)},s=()=>{let{headers:r,statusText:i,status:s}=o(),c=null,l=null;s!==204&&(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 w({body:c,headers:r,status:s,statusText:i}));else{let n=new D({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 D({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)}})}};N=y([v(0,t.ILogService)],N);let P=class extends t.Plugin{constructor(e=o,n,r,i){super(),this._config=e,this._logger=n,this._injector=r,this._configService=i;let{...a}=(0,t.merge)({},o,this._config);this._configService.setConfig(`network.config`,a)}onStarting(){var e,n,r;if(this._injector.get(b,t.Quantity.OPTIONAL,t.LookUp.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 i=(n=this._config)!=null&&n.useFetchImpl?k:typeof window<`u`?N:k;(0,t.registerDependencies)(this._injector,(0,t.mergeOverrideWithDependencies)([[b],[m,{useClass:i}]],(r=this._config)==null?void 0:r.override))}};u(P,`pluginName`,`UNIVER_NETWORK_PLUGIN`),u(P,`packageName`,i),u(P,`version`,a),P=y([v(1,t.ILogService),v(2,(0,t.Inject)(t.Injector)),v(3,t.IConfigService)],P);let F=e=>{let{errorStatusCodes:t,onAuthError:r}=e;return(e,i)=>i(e).pipe((0,n.catchError)(e=>(e instanceof D&&t.some(t=>t===e.status)&&r(),(0,n.throwError)(()=>e))))},I=(e=300)=>{let n=t.noop;return t=>new Promise(t=>{n();let r=setTimeout(()=>{t(!0)},e);n=()=>{clearTimeout(r),t(!1)}})},L=()=>(e,t)=>t.map(t=>({config:t,result:e})),R=(e,r={})=>{let{isMatch:i,getParamsFromRequest:a,mergeParamsToRequest:o}=e,{fetchCheck:s=I(300),distributeResult:c=L()}=r,l=[],u=e=>e.map(e=>e.config);return(e,r)=>i(e)?new n.Observable(n=>{let i={next:e=>n.next(e),error:e=>n.error(e),config:a(e),active:!0};l.push(i);let d=u(l);return s(e).then(t=>{if(t){let t=[];d.forEach(e=>{let n=l.findIndex(t=>t.config===e);if(n>=0){let[e]=l.splice(n,1);t.push(e)}});let i=u(t);if(!i.length)return;let a={hooks:t};t.forEach(e=>e.batch=a),a.subscription=r(o(i,e)).subscribe({next:e=>{if(e.type===1){let n=e.body,r=c(n,i);t.forEach(t=>{let n=r.find(e=>e.config===t.config);if(n){let r=new w({body:n.result,headers:e.headers,status:e.status,statusText:e.statusText});t.next(r)}else t.error(`batch error`)})}},complete:()=>n.complete(),error:e=>n.error(e)})}}),()=>{var e;if(i.active=!1,(0,t.remove)(l,i),(e=i.batch)!=null&&e.hooks.every(e=>!e.active)){var n;(n=i.batch.subscription)==null||n.unsubscribe()}}}):r(e)},z=e=>{let t=(e==null?void 0:e.maxRetryAttempts)??3,n=(e==null?void 0:e.delayInterval)??1e3;return(e,i)=>i(e).pipe((0,r.retry)({delay:n,count:t}))},B=e=>{let r=[],i=new Set,a=()=>{for(;i.size<((e==null?void 0:e.maxParallel)??1)&&r.length>0;){let e=r.shift();i.add(e),e()}};return(e,o)=>new n.Observable(n=>{let s,c=()=>{s=o(e).subscribe({next:e=>n.next(e),error:e=>n.error(e),complete:()=>n.complete()})};return r.push(c),a(),()=>{s==null||s.unsubscribe(),i.delete(c),(0,t.remove)(r,c),a()}})},V=(0,t.createIdentifier)(`univer.network.socket.service`);var H=class extends t.Disposable{createSocket(e){try{let i=new WebSocket(e),a=new t.DisposableCollection;return{URL:e,close:(e,t)=>{i.close(e,t),a.dispose()},send:e=>{i.send(e)},open$:new n.Observable(e=>{let n=t=>e.next(t);i.addEventListener(`open`,n),a.add((0,t.toDisposable)(()=>i.removeEventListener(`open`,n)))}).pipe((0,r.share)()),close$:new n.Observable(e=>{let n=t=>e.next(t);i.addEventListener(`close`,n),a.add((0,t.toDisposable)(()=>i.removeEventListener(`close`,n)))}).pipe((0,r.share)()),error$:new n.Observable(e=>{let n=t=>e.next(t);i.addEventListener(`error`,n),a.add((0,t.toDisposable)(()=>i.removeEventListener(`error`,n)))}).pipe((0,r.share)()),message$:new n.Observable(e=>{let n=t=>e.next(t);i.addEventListener(`message`,n),a.add((0,t.toDisposable)(()=>i.removeEventListener(`message`,n)))}).pipe((0,r.share)())}}catch(e){return console.error(e),null}}};e.AuthInterceptorFactory=F,Object.defineProperty(e,"FetchHTTPImplementation",{enumerable:!0,get:function(){return k}}),e.HTTPEventType=C,e.HTTPHeaders=p,e.HTTPProgress=T,e.HTTPRequest=_,e.HTTPResponse=w,e.HTTPResponseError=D,Object.defineProperty(e,"HTTPService",{enumerable:!0,get:function(){return b}}),e.HTTPStatusCode=S,e.IHTTPImplementation=m,e.ISocketService=V,e.MergeInterceptorFactory=R,e.ResponseHeader=E,e.RetryInterceptorFactory=z,e.ThresholdInterceptorFactory=B,Object.defineProperty(e,"UniverNetworkPlugin",{enumerable:!0,get:function(){return P}}),e.WebSocketService=H,Object.defineProperty(e,"XHRHTTPImplementation",{enumerable:!0,get:function(){return N}})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@univerjs/network",
3
- "version": "1.0.0-alpha.7",
3
+ "version": "1.0.0-beta.0",
4
4
  "private": false,
5
5
  "description": "Network service abstractions for Univer runtime integrations.",
6
6
  "author": "DreamNum Co., Ltd. <developer@univer.ai>",
@@ -62,13 +62,13 @@
62
62
  "rxjs": ">=7.0.0"
63
63
  },
64
64
  "dependencies": {
65
- "@univerjs/core": "1.0.0-alpha.7"
65
+ "@univerjs/core": "1.0.0-beta.0"
66
66
  },
67
67
  "devDependencies": {
68
68
  "rxjs": "^7.8.2",
69
69
  "typescript": "^6.0.3",
70
70
  "vitest": "^4.1.10",
71
- "@univerjs-infra/shared": "1.0.0-alpha.7"
71
+ "@univerjs-infra/shared": "1.0.0-beta.0"
72
72
  },
73
73
  "scripts": {
74
74
  "test": "vitest run",