@univerjs/network 0.1.0-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Copyright 2023-present DreamNum Inc.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ export declare class HTTPParams {
17
+ readonly params?: {
18
+ [key: string]: string | number | boolean;
19
+ } | undefined;
20
+ constructor(params?: {
21
+ [key: string]: string | number | boolean;
22
+ } | undefined);
23
+ toString(): string;
24
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Copyright 2023-present DreamNum Inc.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import type { HTTPHeaders } from './headers';
17
+ import type { HTTPResponseType } from './http';
18
+ import type { HTTPParams } from './params';
19
+ export type HTTPRequestMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
20
+ export interface IHTTPRequestParams {
21
+ body?: any;
22
+ headers: HTTPHeaders;
23
+ params?: HTTPParams;
24
+ responseType: HTTPResponseType;
25
+ withCredentials: boolean;
26
+ }
27
+ export declare class HTTPRequest {
28
+ readonly method: HTTPRequestMethod;
29
+ readonly url: string;
30
+ readonly requestParams?: IHTTPRequestParams | undefined;
31
+ get headers(): HTTPHeaders;
32
+ get withCredentials(): boolean;
33
+ get responseType(): string;
34
+ constructor(method: HTTPRequestMethod, url: string, requestParams?: IHTTPRequestParams | undefined);
35
+ getUrlWithParams(): string;
36
+ getBody(): string | null;
37
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Copyright 2023-present DreamNum Inc.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import type { HTTPHeaders } from './headers';
17
+ /**
18
+ * There are multiple events could be resolved from the HTTP server.
19
+ */
20
+ export type HTTPEvent<T> = HTTPResponse<T> | HTTPResponseError;
21
+ /** Wraps (success) response info. */
22
+ export declare class HTTPResponse<T> {
23
+ readonly body: T;
24
+ readonly headers: HTTPHeaders;
25
+ readonly status: number;
26
+ readonly statusText: string;
27
+ constructor({ body, headers, status, statusText, }: {
28
+ body: T;
29
+ headers: HTTPHeaders;
30
+ status: number;
31
+ statusText: string;
32
+ });
33
+ }
34
+ export declare class HTTPResponseError {
35
+ readonly headers: HTTPHeaders;
36
+ readonly status: number;
37
+ readonly statusText: string;
38
+ readonly error: any;
39
+ constructor({ headers, status, statusText, error, }: {
40
+ headers: HTTPHeaders;
41
+ status: number;
42
+ statusText: string;
43
+ error: any;
44
+ });
45
+ }
46
+ export declare class ResponseHeader {
47
+ readonly headers: HTTPHeaders;
48
+ readonly status: number;
49
+ readonly statusText: string;
50
+ constructor(headers: HTTPHeaders, status: number, statusText: string);
51
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Copyright 2023-present DreamNum Inc.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import type { Nullable } from '@univerjs/core';
17
+ import { Disposable } from '@univerjs/core';
18
+ import { Observable } from 'rxjs';
19
+ export type SocketBodyType = string | ArrayBufferLike | Blob | ArrayBufferView;
20
+ /**
21
+ * This service is responsible for establishing bidi-directional connection to a remote server.
22
+ */
23
+ export declare const ISocketService: import("@wendellhu/redi").IdentifierDecorator<ISocketService>;
24
+ export interface ISocketService {
25
+ createSocket(url: string): Nullable<ISocket>;
26
+ }
27
+ /**
28
+ * An interface that represents a socket connection.
29
+ */
30
+ export interface ISocket {
31
+ URL: string;
32
+ close(code?: number, reason?: string): void;
33
+ /**
34
+ * Send a message to the remote server.
35
+ */
36
+ send(data: SocketBodyType): void;
37
+ close$: Observable<CloseEvent>;
38
+ error$: Observable<Event>;
39
+ message$: Observable<MessageEvent>;
40
+ open$: Observable<Event>;
41
+ }
42
+ /**
43
+ * This service create a WebSocket connection to a remote server.
44
+ */
45
+ export declare class WebSocketService extends Disposable implements ISocketService {
46
+ createSocket(URL: string): Nullable<ISocket>;
47
+ }
@@ -0,0 +1,422 @@
1
+ (function(global, factory) {
2
+ typeof exports === "object" && typeof module !== "undefined" ? factory(exports, require("@univerjs/core"), require("rxjs"), require("rxjs/operators"), require("@wendellhu/redi")) : typeof define === "function" && define.amd ? define(["exports", "@univerjs/core", "rxjs", "rxjs/operators", "@wendellhu/redi"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global.UniverNetwork = {}, global.UniverCore, global.rxjs, global.rxjs.operators, global["@wendellhu/redi"]));
3
+ })(this, function(exports2, core, rxjs, operators, redi) {
4
+ "use strict";var __defProp = Object.defineProperty;
5
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
+ var __publicField = (obj, key, value) => {
7
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
8
+ return value;
9
+ };
10
+
11
+ const ApplicationJSONType = "application/json";
12
+ class HTTPHeaders {
13
+ constructor(headers) {
14
+ __publicField(this, "_headers", /* @__PURE__ */ new Map());
15
+ if (typeof headers === "string") {
16
+ headers.split("\n").forEach((header) => {
17
+ const [name, value] = header.split(":");
18
+ if (name && value) {
19
+ this._setHeader(name, value);
20
+ }
21
+ });
22
+ } else {
23
+ if (headers) {
24
+ Object.keys(headers).forEach(([name, value]) => {
25
+ this._setHeader(name, value);
26
+ });
27
+ }
28
+ }
29
+ }
30
+ forEach(callback) {
31
+ this._headers.forEach((v, key) => callback(key, v));
32
+ }
33
+ has(key) {
34
+ return !!this._headers.has(key.toLowerCase());
35
+ }
36
+ get(key) {
37
+ const k = key.toLowerCase();
38
+ return this._headers.has(k) ? this._headers.get(k) : null;
39
+ }
40
+ _setHeader(name, value) {
41
+ const lowerCase = name.toLowerCase();
42
+ if (this._headers.has(lowerCase)) {
43
+ this._headers.get(lowerCase).push(value.toString());
44
+ } else {
45
+ this._headers.set(lowerCase, [value.toString()]);
46
+ }
47
+ }
48
+ }
49
+ const IHTTPImplementation = redi.createIdentifier("univer-pro.network.http-implementation");
50
+ class HTTPParams {
51
+ constructor(params) {
52
+ this.params = params;
53
+ }
54
+ toString() {
55
+ if (!this.params) {
56
+ return "";
57
+ }
58
+ return Object.keys(this.params).map((key) => `${key}=${this.params[key]}`).join("&");
59
+ }
60
+ }
61
+ class HTTPRequest {
62
+ constructor(method, url, requestParams) {
63
+ this.method = method;
64
+ this.url = url;
65
+ this.requestParams = requestParams;
66
+ }
67
+ get headers() {
68
+ return this.requestParams.headers;
69
+ }
70
+ get withCredentials() {
71
+ return this.requestParams.withCredentials;
72
+ }
73
+ get responseType() {
74
+ return this.requestParams.responseType;
75
+ }
76
+ getUrlWithParams() {
77
+ var _a, _b;
78
+ const params = (_b = (_a = this.requestParams) == null ? void 0 : _a.params) == null ? void 0 : _b.toString();
79
+ if (!params) {
80
+ return this.url;
81
+ }
82
+ return `${this.url}${this.url.includes("?") ? "&" : "?"}${params}`;
83
+ }
84
+ getBody() {
85
+ var _a;
86
+ const contentType = this.headers.get("Content-Type") ?? ApplicationJSONType;
87
+ const body = (_a = this.requestParams) == null ? void 0 : _a.body;
88
+ if (contentType === ApplicationJSONType && body && typeof body === "object") {
89
+ return JSON.stringify(body);
90
+ }
91
+ return body ? `${body}` : null;
92
+ }
93
+ }
94
+ class HTTPResponse {
95
+ constructor({
96
+ body,
97
+ headers,
98
+ status,
99
+ statusText
100
+ }) {
101
+ __publicField(this, "body");
102
+ __publicField(this, "headers");
103
+ __publicField(this, "status");
104
+ __publicField(this, "statusText");
105
+ this.body = body;
106
+ this.headers = headers;
107
+ this.status = status;
108
+ this.statusText = statusText;
109
+ }
110
+ }
111
+ class HTTPResponseError {
112
+ constructor({
113
+ headers,
114
+ status,
115
+ statusText,
116
+ error
117
+ }) {
118
+ __publicField(this, "headers");
119
+ __publicField(this, "status");
120
+ __publicField(this, "statusText");
121
+ __publicField(this, "error");
122
+ this.headers = headers;
123
+ this.status = status;
124
+ this.statusText = statusText;
125
+ this.error = error;
126
+ }
127
+ }
128
+ class ResponseHeader {
129
+ constructor(headers, status, statusText) {
130
+ this.headers = headers;
131
+ this.status = status;
132
+ this.statusText = statusText;
133
+ }
134
+ }
135
+ var __defProp2 = Object.defineProperty;
136
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
137
+ var __decorateClass = (decorators, target, key, kind) => {
138
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
139
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
140
+ if (decorator = decorators[i])
141
+ result = (kind ? decorator(target, key, result) : decorator(result)) || result;
142
+ if (kind && result)
143
+ __defProp2(target, key, result);
144
+ return result;
145
+ };
146
+ var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
147
+ exports2.HTTPService = class HTTPService extends core.Disposable {
148
+ constructor(_http) {
149
+ super();
150
+ __publicField(this, "_interceptors", []);
151
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
152
+ __publicField(this, "_pipe");
153
+ this._http = _http;
154
+ }
155
+ registerHTTPInterceptor(interceptor) {
156
+ if (this._interceptors.indexOf(interceptor) !== -1) {
157
+ throw new Error("[HTTPService]: The interceptor has already been registered!");
158
+ }
159
+ this._interceptors.push(interceptor);
160
+ this._interceptors = this._interceptors.sort((a, b) => (a.priority ?? 0) - (b.priority ?? 0));
161
+ this._pipe = null;
162
+ return core.toDisposable(() => core.remove(this._interceptors, interceptor));
163
+ }
164
+ get(url, options) {
165
+ return this._request("GET", url, options);
166
+ }
167
+ post(url, options) {
168
+ return this._request("POST", url, options);
169
+ }
170
+ put(url, options) {
171
+ return this._request("PUT", url, options);
172
+ }
173
+ delete(url, options) {
174
+ return this._request("DELETE", url, options);
175
+ }
176
+ /** The HTTP request implementations */
177
+ async _request(method, url, options) {
178
+ const headers = new HTTPHeaders(options == null ? void 0 : options.headers);
179
+ const params = new HTTPParams(options == null ? void 0 : options.params);
180
+ const request = new HTTPRequest(method, url, {
181
+ headers,
182
+ params,
183
+ withCredentials: (options == null ? void 0 : options.withCredentials) ?? false,
184
+ // default value for withCredentials is false by MDN
185
+ responseType: (options == null ? void 0 : options.responseType) ?? "json",
186
+ body: options == null ? void 0 : options.body
187
+ });
188
+ const events$ = rxjs.of(request).pipe(
189
+ operators.concatMap((request2) => this._runInterceptorsAndImplementation(request2))
190
+ );
191
+ const result = await rxjs.firstValueFrom(events$);
192
+ if (result instanceof HTTPResponse) {
193
+ return result;
194
+ }
195
+ throw new Error(`${result.error}`);
196
+ }
197
+ _runInterceptorsAndImplementation(request) {
198
+ if (!this._pipe) {
199
+ this._pipe = this._interceptors.map((handler) => handler.interceptor).reduceRight(
200
+ (nextHandlerFunction, interceptorFunction) => chainInterceptorFn(nextHandlerFunction, interceptorFunction),
201
+ (requestFromPrevInterceptor, finalHandler) => finalHandler(requestFromPrevInterceptor)
202
+ );
203
+ }
204
+ return this._pipe(
205
+ request,
206
+ (requestToNext) => this._http.send(requestToNext)
207
+ /* final handler */
208
+ );
209
+ }
210
+ };
211
+ exports2.HTTPService = __decorateClass([
212
+ __decorateParam(0, IHTTPImplementation)
213
+ ], exports2.HTTPService);
214
+ function chainInterceptorFn(afterInterceptorChain, currentInterceptorFn) {
215
+ return (prevRequest, nextHandlerFn) => currentInterceptorFn(prevRequest, (nextRequest) => afterInterceptorChain(nextRequest, nextHandlerFn));
216
+ }
217
+ const SuccessStatusCodeLowerBound = 200;
218
+ const ErrorStatusCodeLowerBound = 300;
219
+ var HTTPStatusCode = /* @__PURE__ */ ((HTTPStatusCode2) => {
220
+ HTTPStatusCode2[HTTPStatusCode2["Continue"] = 100] = "Continue";
221
+ HTTPStatusCode2[HTTPStatusCode2["SwitchingProtocols"] = 101] = "SwitchingProtocols";
222
+ HTTPStatusCode2[HTTPStatusCode2["Processing"] = 102] = "Processing";
223
+ HTTPStatusCode2[HTTPStatusCode2["EarlyHints"] = 103] = "EarlyHints";
224
+ HTTPStatusCode2[HTTPStatusCode2["Ok"] = 200] = "Ok";
225
+ HTTPStatusCode2[HTTPStatusCode2["Created"] = 201] = "Created";
226
+ HTTPStatusCode2[HTTPStatusCode2["Accepted"] = 202] = "Accepted";
227
+ HTTPStatusCode2[HTTPStatusCode2["NonAuthoritativeInformation"] = 203] = "NonAuthoritativeInformation";
228
+ HTTPStatusCode2[HTTPStatusCode2["NoContent"] = 204] = "NoContent";
229
+ HTTPStatusCode2[HTTPStatusCode2["ResetContent"] = 205] = "ResetContent";
230
+ HTTPStatusCode2[HTTPStatusCode2["PartialContent"] = 206] = "PartialContent";
231
+ HTTPStatusCode2[HTTPStatusCode2["MultiStatus"] = 207] = "MultiStatus";
232
+ HTTPStatusCode2[HTTPStatusCode2["AlreadyReported"] = 208] = "AlreadyReported";
233
+ HTTPStatusCode2[HTTPStatusCode2["ImUsed"] = 226] = "ImUsed";
234
+ HTTPStatusCode2[HTTPStatusCode2["MultipleChoices"] = 300] = "MultipleChoices";
235
+ HTTPStatusCode2[HTTPStatusCode2["MovedPermanently"] = 301] = "MovedPermanently";
236
+ HTTPStatusCode2[HTTPStatusCode2["Found"] = 302] = "Found";
237
+ HTTPStatusCode2[HTTPStatusCode2["SeeOther"] = 303] = "SeeOther";
238
+ HTTPStatusCode2[HTTPStatusCode2["NotModified"] = 304] = "NotModified";
239
+ HTTPStatusCode2[HTTPStatusCode2["UseProxy"] = 305] = "UseProxy";
240
+ HTTPStatusCode2[HTTPStatusCode2["Unused"] = 306] = "Unused";
241
+ HTTPStatusCode2[HTTPStatusCode2["TemporaryRedirect"] = 307] = "TemporaryRedirect";
242
+ HTTPStatusCode2[HTTPStatusCode2["PermanentRedirect"] = 308] = "PermanentRedirect";
243
+ HTTPStatusCode2[HTTPStatusCode2["BadRequest"] = 400] = "BadRequest";
244
+ HTTPStatusCode2[HTTPStatusCode2["Unauthorized"] = 401] = "Unauthorized";
245
+ HTTPStatusCode2[HTTPStatusCode2["PaymentRequired"] = 402] = "PaymentRequired";
246
+ HTTPStatusCode2[HTTPStatusCode2["Forbidden"] = 403] = "Forbidden";
247
+ HTTPStatusCode2[HTTPStatusCode2["NotFound"] = 404] = "NotFound";
248
+ HTTPStatusCode2[HTTPStatusCode2["MethodNotAllowed"] = 405] = "MethodNotAllowed";
249
+ HTTPStatusCode2[HTTPStatusCode2["NotAcceptable"] = 406] = "NotAcceptable";
250
+ HTTPStatusCode2[HTTPStatusCode2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
251
+ HTTPStatusCode2[HTTPStatusCode2["RequestTimeout"] = 408] = "RequestTimeout";
252
+ HTTPStatusCode2[HTTPStatusCode2["Conflict"] = 409] = "Conflict";
253
+ HTTPStatusCode2[HTTPStatusCode2["Gone"] = 410] = "Gone";
254
+ HTTPStatusCode2[HTTPStatusCode2["LengthRequired"] = 411] = "LengthRequired";
255
+ HTTPStatusCode2[HTTPStatusCode2["PreconditionFailed"] = 412] = "PreconditionFailed";
256
+ HTTPStatusCode2[HTTPStatusCode2["PayloadTooLarge"] = 413] = "PayloadTooLarge";
257
+ HTTPStatusCode2[HTTPStatusCode2["UriTooLong"] = 414] = "UriTooLong";
258
+ HTTPStatusCode2[HTTPStatusCode2["UnsupportedMediaType"] = 415] = "UnsupportedMediaType";
259
+ HTTPStatusCode2[HTTPStatusCode2["RangeNotSatisfiable"] = 416] = "RangeNotSatisfiable";
260
+ HTTPStatusCode2[HTTPStatusCode2["ExpectationFailed"] = 417] = "ExpectationFailed";
261
+ HTTPStatusCode2[HTTPStatusCode2["ImATeapot"] = 418] = "ImATeapot";
262
+ HTTPStatusCode2[HTTPStatusCode2["MisdirectedRequest"] = 421] = "MisdirectedRequest";
263
+ HTTPStatusCode2[HTTPStatusCode2["UnprocessableEntity"] = 422] = "UnprocessableEntity";
264
+ HTTPStatusCode2[HTTPStatusCode2["Locked"] = 423] = "Locked";
265
+ HTTPStatusCode2[HTTPStatusCode2["FailedDependency"] = 424] = "FailedDependency";
266
+ HTTPStatusCode2[HTTPStatusCode2["TooEarly"] = 425] = "TooEarly";
267
+ HTTPStatusCode2[HTTPStatusCode2["UpgradeRequired"] = 426] = "UpgradeRequired";
268
+ HTTPStatusCode2[HTTPStatusCode2["PreconditionRequired"] = 428] = "PreconditionRequired";
269
+ HTTPStatusCode2[HTTPStatusCode2["TooManyRequests"] = 429] = "TooManyRequests";
270
+ HTTPStatusCode2[HTTPStatusCode2["RequestHeaderFieldsTooLarge"] = 431] = "RequestHeaderFieldsTooLarge";
271
+ HTTPStatusCode2[HTTPStatusCode2["UnavailableForLegalReasons"] = 451] = "UnavailableForLegalReasons";
272
+ HTTPStatusCode2[HTTPStatusCode2["InternalServerError"] = 500] = "InternalServerError";
273
+ HTTPStatusCode2[HTTPStatusCode2["NotImplemented"] = 501] = "NotImplemented";
274
+ HTTPStatusCode2[HTTPStatusCode2["BadGateway"] = 502] = "BadGateway";
275
+ HTTPStatusCode2[HTTPStatusCode2["ServiceUnavailable"] = 503] = "ServiceUnavailable";
276
+ HTTPStatusCode2[HTTPStatusCode2["GatewayTimeout"] = 504] = "GatewayTimeout";
277
+ HTTPStatusCode2[HTTPStatusCode2["HttpVersionNotSupported"] = 505] = "HttpVersionNotSupported";
278
+ HTTPStatusCode2[HTTPStatusCode2["VariantAlsoNegotiates"] = 506] = "VariantAlsoNegotiates";
279
+ HTTPStatusCode2[HTTPStatusCode2["InsufficientStorage"] = 507] = "InsufficientStorage";
280
+ HTTPStatusCode2[HTTPStatusCode2["LoopDetected"] = 508] = "LoopDetected";
281
+ HTTPStatusCode2[HTTPStatusCode2["NotExtended"] = 510] = "NotExtended";
282
+ HTTPStatusCode2[HTTPStatusCode2["NetworkAuthenticationRequired"] = 511] = "NetworkAuthenticationRequired";
283
+ return HTTPStatusCode2;
284
+ })(HTTPStatusCode || {});
285
+ class XHRHTTPImplementation {
286
+ send(request) {
287
+ return new rxjs.Observable((observer) => {
288
+ const xhr = new XMLHttpRequest();
289
+ xhr.open(request.method, request.getUrlWithParams());
290
+ if (request.withCredentials) {
291
+ xhr.withCredentials = true;
292
+ }
293
+ request.headers.forEach((key, value) => xhr.setRequestHeader(key, value.join(",")));
294
+ if (!request.headers.has("Accept")) {
295
+ xhr.setRequestHeader("Accept", "application/json, text/plain, */*");
296
+ }
297
+ if (!request.headers.has("Content-Type")) {
298
+ xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
299
+ }
300
+ const buildResponseHeader = () => {
301
+ const statusText = xhr.statusText || "OK";
302
+ const headers = new HTTPHeaders(xhr.getAllResponseHeaders());
303
+ return new ResponseHeader(headers, xhr.status, statusText);
304
+ };
305
+ const onLoadHandler = () => {
306
+ const { headers, statusText, status } = buildResponseHeader();
307
+ const { responseType } = request;
308
+ let body2 = null;
309
+ let error = null;
310
+ if (status !== HTTPStatusCode.NoContent) {
311
+ body2 = typeof xhr.response === "undefined" ? xhr.responseText : xhr.response;
312
+ }
313
+ let success = status >= SuccessStatusCodeLowerBound && status < ErrorStatusCodeLowerBound;
314
+ if (responseType === "json" && typeof body2 === "string") {
315
+ const originalBody = body2;
316
+ try {
317
+ body2 = body2 ? JSON.parse(body2) : null;
318
+ } catch (e) {
319
+ success = false;
320
+ body2 = originalBody;
321
+ error = e;
322
+ }
323
+ }
324
+ if (success) {
325
+ observer.next(
326
+ new HTTPResponse({
327
+ body: body2,
328
+ headers,
329
+ status,
330
+ statusText
331
+ })
332
+ );
333
+ } else {
334
+ observer.next(
335
+ new HTTPResponseError({
336
+ error,
337
+ headers,
338
+ status,
339
+ statusText
340
+ })
341
+ );
342
+ }
343
+ };
344
+ const onErrorHandler = (error) => {
345
+ const res = new HTTPResponseError({
346
+ error,
347
+ status: xhr.status || 0,
348
+ statusText: xhr.statusText || "Unknown Error",
349
+ headers: buildResponseHeader().headers
350
+ });
351
+ observer.next(res);
352
+ };
353
+ xhr.addEventListener("load", onLoadHandler);
354
+ xhr.addEventListener("error", onErrorHandler);
355
+ xhr.addEventListener("abort", onErrorHandler);
356
+ xhr.addEventListener("timeout", onErrorHandler);
357
+ const body = request.getBody();
358
+ xhr.send(body);
359
+ return () => {
360
+ if (xhr.readyState !== xhr.DONE) {
361
+ xhr.abort();
362
+ }
363
+ xhr.removeEventListener("load", onLoadHandler);
364
+ xhr.removeEventListener("error", onErrorHandler);
365
+ xhr.removeEventListener("abort", onErrorHandler);
366
+ xhr.removeEventListener("timeout", onErrorHandler);
367
+ };
368
+ });
369
+ }
370
+ }
371
+ const ISocketService = redi.createIdentifier("univer.socket");
372
+ class WebSocketService extends core.Disposable {
373
+ createSocket(URL) {
374
+ try {
375
+ const connection = new WebSocket(URL);
376
+ const disposables = new core.DisposableCollection();
377
+ const webSocket = {
378
+ URL,
379
+ close: (code, reason) => {
380
+ connection.close(code, reason);
381
+ disposables.dispose();
382
+ },
383
+ send: (data) => {
384
+ connection.send(data);
385
+ },
386
+ open$: new rxjs.Observable((subscriber) => {
387
+ const callback = (event) => subscriber.next(event);
388
+ connection.addEventListener("open", callback);
389
+ disposables.add(core.toDisposable(() => connection.removeEventListener("open", callback)));
390
+ }).pipe(operators.share()),
391
+ close$: new rxjs.Observable((subscriber) => {
392
+ const callback = (event) => subscriber.next(event);
393
+ connection.addEventListener("close", callback);
394
+ disposables.add(core.toDisposable(() => connection.removeEventListener("close", callback)));
395
+ }).pipe(operators.share()),
396
+ error$: new rxjs.Observable((subscriber) => {
397
+ const callback = (event) => subscriber.next(event);
398
+ connection.addEventListener("error", callback);
399
+ disposables.add(core.toDisposable(() => connection.removeEventListener("error", callback)));
400
+ }).pipe(operators.share()),
401
+ message$: new rxjs.Observable((subscriber) => {
402
+ const callback = (event) => subscriber.next(event);
403
+ connection.addEventListener("message", callback);
404
+ disposables.add(core.toDisposable(() => connection.removeEventListener("message", callback)));
405
+ }).pipe(operators.share())
406
+ };
407
+ return webSocket;
408
+ } catch (e) {
409
+ console.error(e);
410
+ return null;
411
+ }
412
+ }
413
+ }
414
+ exports2.HTTPHeaders = HTTPHeaders;
415
+ exports2.HTTPRequest = HTTPRequest;
416
+ exports2.HTTPResponse = HTTPResponse;
417
+ exports2.IHTTPImplementation = IHTTPImplementation;
418
+ exports2.ISocketService = ISocketService;
419
+ exports2.WebSocketService = WebSocketService;
420
+ exports2.XHRHTTPImplementation = XHRHTTPImplementation;
421
+ Object.defineProperty(exports2, Symbol.toStringTag, { value: "Module" });
422
+ });
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@univerjs/network",
3
+ "version": "0.1.0-alpha.3",
4
+ "keywords": [],
5
+ "author": "DreamNum <developer@univer.ai>",
6
+ "license": "Apache-2.0",
7
+ "main": "./lib/cjs/index.js",
8
+ "module": "./lib/es/index.js",
9
+ "types": "./lib/types/index.d.ts",
10
+ "publishConfig": {
11
+ "access": "public"
12
+ },
13
+ "exports": {
14
+ ".": {
15
+ "import": "./lib/es/index.js",
16
+ "require": "./lib/cjs/index.js",
17
+ "types": "./lib/types/index.d.ts"
18
+ },
19
+ "./*": {
20
+ "import": "./lib/es/*",
21
+ "require": "./lib/cjs/*",
22
+ "types": "./lib/types/index.d.ts"
23
+ }
24
+ },
25
+ "directories": {
26
+ "lib": "lib"
27
+ },
28
+ "files": [
29
+ "lib"
30
+ ],
31
+ "private": false,
32
+ "devDependencies": {
33
+ "@wendellhu/redi": "^0.12.12",
34
+ "rxjs": "^7.8.1",
35
+ "typescript": "^5.3.3",
36
+ "vite": "^5.0.8",
37
+ "vite-plugin-dts": "^3.6.4",
38
+ "vite-plugin-externals": "^0.6.2",
39
+ "vitest": "^1.0.4",
40
+ "@univerjs/core": "0.1.0-alpha.3"
41
+ },
42
+ "peerDependencies": {
43
+ "@wendellhu/redi": ">=0.12.12",
44
+ "rxjs": ">=7.0.0",
45
+ "@univerjs/core": "0.1.0-alpha.3"
46
+ },
47
+ "scripts": {
48
+ "build": "tsc && vite build"
49
+ }
50
+ }