@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,423 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => {
4
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
+ return value;
6
+ };
7
+ import { Disposable, toDisposable, remove, DisposableCollection } from "@univerjs/core";
8
+ import { of, firstValueFrom, Observable } from "rxjs";
9
+ import { concatMap, share } from "rxjs/operators";
10
+ import { createIdentifier } from "@wendellhu/redi";
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 = 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
+ let HTTPService = class extends 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 toDisposable(() => 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$ = of(request).pipe(
189
+ concatMap((request2) => this._runInterceptorsAndImplementation(request2))
190
+ );
191
+ const result = await 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
+ HTTPService = __decorateClass([
212
+ __decorateParam(0, IHTTPImplementation)
213
+ ], 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 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 = createIdentifier("univer.socket");
372
+ class WebSocketService extends Disposable {
373
+ createSocket(URL) {
374
+ try {
375
+ const connection = new WebSocket(URL);
376
+ const disposables = new 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 Observable((subscriber) => {
387
+ const callback = (event) => subscriber.next(event);
388
+ connection.addEventListener("open", callback);
389
+ disposables.add(toDisposable(() => connection.removeEventListener("open", callback)));
390
+ }).pipe(share()),
391
+ close$: new Observable((subscriber) => {
392
+ const callback = (event) => subscriber.next(event);
393
+ connection.addEventListener("close", callback);
394
+ disposables.add(toDisposable(() => connection.removeEventListener("close", callback)));
395
+ }).pipe(share()),
396
+ error$: new Observable((subscriber) => {
397
+ const callback = (event) => subscriber.next(event);
398
+ connection.addEventListener("error", callback);
399
+ disposables.add(toDisposable(() => connection.removeEventListener("error", callback)));
400
+ }).pipe(share()),
401
+ message$: new Observable((subscriber) => {
402
+ const callback = (event) => subscriber.next(event);
403
+ connection.addEventListener("message", callback);
404
+ disposables.add(toDisposable(() => connection.removeEventListener("message", callback)));
405
+ }).pipe(share())
406
+ };
407
+ return webSocket;
408
+ } catch (e) {
409
+ console.error(e);
410
+ return null;
411
+ }
412
+ }
413
+ }
414
+ export {
415
+ HTTPHeaders,
416
+ HTTPRequest,
417
+ HTTPResponse,
418
+ HTTPService,
419
+ IHTTPImplementation,
420
+ ISocketService,
421
+ WebSocketService,
422
+ XHRHTTPImplementation
423
+ };
@@ -0,0 +1,22 @@
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 { HTTPHeaders } from './services/http/headers';
17
+ export { HTTPService } from './services/http/http.service';
18
+ export { IHTTPImplementation } from './services/http/implementations/implementation';
19
+ export { XHRHTTPImplementation } from './services/http/implementations/xhr';
20
+ export { HTTPRequest } from './services/http/request';
21
+ export { HTTPResponse } from './services/http/response';
22
+ export { type ISocket, ISocketService, type SocketBodyType, WebSocketService, } from './services/web-socket/web-socket.service';
@@ -0,0 +1,31 @@
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
+ interface IHeadersConstructorProps {
17
+ [key: string]: string | number | boolean;
18
+ }
19
+ export declare const ApplicationJSONType = "application/json";
20
+ /**
21
+ * It wraps headers of HTTP requests' and responses' headers.
22
+ */
23
+ export declare class HTTPHeaders {
24
+ private readonly _headers;
25
+ constructor(headers?: IHeadersConstructorProps | string);
26
+ forEach(callback: (name: string, value: string[]) => void): void;
27
+ has(key: string): boolean;
28
+ get(key: string): string[] | null;
29
+ private _setHeader;
30
+ }
31
+ export {};
@@ -0,0 +1,88 @@
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 type HTTPResponseType = 'arraybuffer' | 'blob' | 'json' | 'text';
17
+ export declare const SuccessStatusCodeLowerBound = 200;
18
+ export declare const ErrorStatusCodeLowerBound = 300;
19
+ /**
20
+ * Http status codes.
21
+ *
22
+ * https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
23
+ */
24
+ export declare enum HTTPStatusCode {
25
+ Continue = 100,
26
+ SwitchingProtocols = 101,
27
+ Processing = 102,
28
+ EarlyHints = 103,
29
+ Ok = 200,
30
+ Created = 201,
31
+ Accepted = 202,
32
+ NonAuthoritativeInformation = 203,
33
+ NoContent = 204,
34
+ ResetContent = 205,
35
+ PartialContent = 206,
36
+ MultiStatus = 207,
37
+ AlreadyReported = 208,
38
+ ImUsed = 226,
39
+ MultipleChoices = 300,
40
+ MovedPermanently = 301,
41
+ Found = 302,
42
+ SeeOther = 303,
43
+ NotModified = 304,
44
+ UseProxy = 305,
45
+ Unused = 306,
46
+ TemporaryRedirect = 307,
47
+ PermanentRedirect = 308,
48
+ BadRequest = 400,
49
+ Unauthorized = 401,
50
+ PaymentRequired = 402,
51
+ Forbidden = 403,
52
+ NotFound = 404,
53
+ MethodNotAllowed = 405,
54
+ NotAcceptable = 406,
55
+ ProxyAuthenticationRequired = 407,
56
+ RequestTimeout = 408,
57
+ Conflict = 409,
58
+ Gone = 410,
59
+ LengthRequired = 411,
60
+ PreconditionFailed = 412,
61
+ PayloadTooLarge = 413,
62
+ UriTooLong = 414,
63
+ UnsupportedMediaType = 415,
64
+ RangeNotSatisfiable = 416,
65
+ ExpectationFailed = 417,
66
+ ImATeapot = 418,
67
+ MisdirectedRequest = 421,
68
+ UnprocessableEntity = 422,
69
+ Locked = 423,
70
+ FailedDependency = 424,
71
+ TooEarly = 425,
72
+ UpgradeRequired = 426,
73
+ PreconditionRequired = 428,
74
+ TooManyRequests = 429,
75
+ RequestHeaderFieldsTooLarge = 431,
76
+ UnavailableForLegalReasons = 451,
77
+ InternalServerError = 500,
78
+ NotImplemented = 501,
79
+ BadGateway = 502,
80
+ ServiceUnavailable = 503,
81
+ GatewayTimeout = 504,
82
+ HttpVersionNotSupported = 505,
83
+ VariantAlsoNegotiates = 506,
84
+ InsufficientStorage = 507,
85
+ LoopDetected = 508,
86
+ NotExtended = 510,
87
+ NetworkAuthenticationRequired = 511
88
+ }
@@ -0,0 +1,62 @@
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 { Disposable } from '@univerjs/core';
17
+ import type { IDisposable } from '@wendellhu/redi';
18
+ import type { Observable } from 'rxjs';
19
+ import type { HTTPResponseType } from './http';
20
+ import { IHTTPImplementation } from './implementations/implementation';
21
+ import { HTTPRequest } from './request';
22
+ import type { HTTPEvent } from './response';
23
+ import { HTTPResponse } from './response';
24
+ export interface IRequestParams {
25
+ body?: any;
26
+ /** Query params. These params would be append to the url before the request is sent. */
27
+ params?: {
28
+ [param: string]: string | number | boolean;
29
+ };
30
+ headers?: {
31
+ [key: string]: string | number | boolean;
32
+ };
33
+ responseType?: HTTPResponseType;
34
+ withCredentials?: boolean;
35
+ }
36
+ export interface IPostRequestParams extends IRequestParams {
37
+ body?: any;
38
+ }
39
+ type HTTPHandlerFn = (request: HTTPRequest) => Observable<HTTPEvent<unknown>>;
40
+ type HTTPInterceptorFn = (request: HTTPRequest, next: HTTPHandlerFn) => Observable<HTTPEvent<unknown>>;
41
+ /**
42
+ * Register an HTTP interceptor. Interceptor could modify requests, responses, headers or errors.
43
+ */
44
+ export interface IHTTPInterceptor {
45
+ priority?: number;
46
+ interceptor: HTTPInterceptorFn;
47
+ }
48
+ export declare class HTTPService extends Disposable {
49
+ private readonly _http;
50
+ private _interceptors;
51
+ private _pipe;
52
+ constructor(_http: IHTTPImplementation);
53
+ registerHTTPInterceptor(interceptor: IHTTPInterceptor): IDisposable;
54
+ get<T>(url: string, options?: IRequestParams): Promise<HTTPResponse<T>>;
55
+ post<T>(url: string, options?: IPostRequestParams): Promise<HTTPResponse<T>>;
56
+ put<T>(url: string, options?: IPostRequestParams): Promise<HTTPResponse<T>>;
57
+ delete<T>(url: string, options?: IRequestParams): Promise<HTTPResponse<T>>;
58
+ /** The HTTP request implementations */
59
+ private _request;
60
+ private _runInterceptorsAndImplementation;
61
+ }
62
+ export {};
@@ -0,0 +1,25 @@
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 { Observable } from 'rxjs';
17
+ import type { HTTPRequest } from '../request';
18
+ import type { HTTPEvent } from '../response';
19
+ /**
20
+ * HTTP service could be implemented differently on platforms.
21
+ */
22
+ export interface IHTTPImplementation {
23
+ send(request: HTTPRequest): Observable<HTTPEvent<any>>;
24
+ }
25
+ export declare const IHTTPImplementation: import("@wendellhu/redi").IdentifierDecorator<IHTTPImplementation>;
@@ -0,0 +1,25 @@
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 { Observable } from 'rxjs';
17
+ import type { HTTPRequest } from '../request';
18
+ import type { HTTPEvent } from '../response';
19
+ import type { IHTTPImplementation } from './implementation';
20
+ /**
21
+ * A HTTP implementation using XHR. XHR could only be async.
22
+ */
23
+ export declare class XHRHTTPImplementation implements IHTTPImplementation {
24
+ send(request: HTTPRequest): Observable<HTTPEvent<any>>;
25
+ }