typedrest 0.4.1 → 0.5.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/README.md +2 -0
- package/endpoints/Endpoint.js +9 -22
- package/endpoints/EntryEndpoint.js +3 -14
- package/endpoints/generic/ETagEndpointBase.js +27 -42
- package/endpoints/generic/ElementEndpoint.js +39 -60
- package/endpoints/generic/GenericCollectionEndpoint.js +70 -44
- package/endpoints/generic/GenericCollectionEndpoint.test.ts +123 -0
- package/endpoints/generic/GenericCollectionEndpoint.ts +54 -1
- package/endpoints/generic/PartialResponse.js +33 -0
- package/endpoints/generic/PartialResponse.ts +28 -0
- package/endpoints/generic/index.js +2 -1
- package/endpoints/generic/index.ts +1 -0
- package/endpoints/index.js +3 -2
- package/endpoints/index.ts +1 -0
- package/endpoints/raw/BlobEndpoint.js +10 -27
- package/endpoints/raw/UploadEndpoint.js +11 -22
- package/endpoints/reactive/Delay.js +27 -0
- package/endpoints/reactive/Delay.ts +26 -0
- package/endpoints/reactive/GenericStreamingCollectionEndpoint.js +79 -0
- package/endpoints/reactive/GenericStreamingCollectionEndpoint.ts +73 -0
- package/endpoints/reactive/PollingEndpoint.js +67 -0
- package/endpoints/reactive/PollingEndpoint.test.ts +84 -0
- package/endpoints/reactive/PollingEndpoint.ts +66 -0
- package/endpoints/reactive/SseStreamingEndpoint.js +120 -0
- package/endpoints/reactive/SseStreamingEndpoint.test.ts +169 -0
- package/endpoints/reactive/SseStreamingEndpoint.ts +115 -0
- package/endpoints/reactive/StreamingCollectionEndpoint.js +23 -0
- package/endpoints/reactive/StreamingCollectionEndpoint.test.ts +110 -0
- package/endpoints/reactive/StreamingCollectionEndpoint.ts +20 -0
- package/endpoints/reactive/StreamingEndpoint.js +56 -0
- package/endpoints/reactive/StreamingEndpoint.test.ts +130 -0
- package/endpoints/reactive/StreamingEndpoint.ts +50 -0
- package/endpoints/reactive/index.js +22 -0
- package/endpoints/reactive/index.ts +5 -0
- package/endpoints/rpc/ActionEndpoint.js +3 -14
- package/endpoints/rpc/ConsumerEndpoint.js +5 -16
- package/endpoints/rpc/FunctionEndpoint.js +6 -17
- package/endpoints/rpc/ProducerEndpoint.js +4 -15
- package/endpoints/rpc/RpcEndpointBase.js +3 -14
- package/errors/DefaultErrorHandler.js +19 -27
- package/errors/DefaultErrorHandler.ts +4 -1
- package/errors/Errors.js +8 -2
- package/errors/Errors.ts +5 -0
- package/http/EntityStream.js +42 -0
- package/http/EntityStream.ts +40 -0
- package/http/HttpContentRange.js +39 -0
- package/http/HttpContentRange.ts +41 -0
- package/http/HttpHeader.js +6 -1
- package/http/HttpHeader.ts +6 -1
- package/http/HttpStatusCode.js +4 -1
- package/http/HttpStatusCode.ts +4 -1
- package/http/ResponseCache.js +4 -15
- package/http/RetryAfter.js +24 -0
- package/http/RetryAfter.ts +19 -0
- package/http/ServerSentEvents.js +140 -0
- package/http/ServerSentEvents.ts +145 -0
- package/http/index.js +5 -1
- package/http/index.ts +4 -0
- package/links/AggregateLinkExtractor.js +7 -18
- package/links/HalLinkExtractor.js +9 -20
- package/links/HeaderLinkExtractor.js +4 -15
- package/package.json +8 -8
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.PollingEndpoint = void 0;
|
|
4
|
+
const ElementEndpoint_1 = require("../generic/ElementEndpoint");
|
|
5
|
+
const Delay_1 = require("./Delay");
|
|
6
|
+
const http_1 = require("../../http");
|
|
7
|
+
/**
|
|
8
|
+
* Endpoint for a resource that can be polled for state changes.
|
|
9
|
+
* @typeParam TEntity The type of entity the endpoint represents.
|
|
10
|
+
*/
|
|
11
|
+
class PollingEndpoint extends ElementEndpoint_1.ElementEndpoint {
|
|
12
|
+
/**
|
|
13
|
+
* Creates a new polling endpoint.
|
|
14
|
+
* @param referrer The endpoint used to navigate to this one.
|
|
15
|
+
* @param relativeUri The URI of this endpoint relative to the `referrer`'s. Add a `./` prefix here to imply a trailing slash in the `referrer`'s URI.
|
|
16
|
+
* @param endCondition A check to determine whether the entity has reached its final state and no further polling is required.
|
|
17
|
+
*/
|
|
18
|
+
constructor(referrer, relativeUri, endCondition) {
|
|
19
|
+
super(referrer, relativeUri);
|
|
20
|
+
this.endCondition = endCondition;
|
|
21
|
+
/**
|
|
22
|
+
* The interval in milliseconds to wait between polling requests.
|
|
23
|
+
* Automatically updated whenever the server sends a {@link http!HttpHeader.RetryAfter} header.
|
|
24
|
+
*/
|
|
25
|
+
this.pollingInterval = 3000;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* @inheritDoc
|
|
29
|
+
*/
|
|
30
|
+
async handle(response) {
|
|
31
|
+
var _a;
|
|
32
|
+
await super.handle(response);
|
|
33
|
+
this.pollingInterval = (_a = (0, http_1.retryAfter)(response)) !== null && _a !== void 0 ? _a : this.pollingInterval;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Provides a stream of the `TEntity`'s states, polling the server for changes.
|
|
37
|
+
* States that are identical to the previously provided one are skipped.
|
|
38
|
+
* @param signal Used to stop polling.
|
|
39
|
+
* @throws {@link errors!AuthenticationError}: {@link http!HttpStatusCode.Unauthorized}
|
|
40
|
+
* @throws {@link errors!AuthorizationError}: {@link http!HttpStatusCode.Forbidden}
|
|
41
|
+
* @throws {@link errors!NotFoundError}: {@link http!HttpStatusCode.NotFound} or {@link http!HttpStatusCode.Gone}
|
|
42
|
+
* @throws {@link errors!HttpError}: Other non-success status code
|
|
43
|
+
*/
|
|
44
|
+
async *stream(signal) {
|
|
45
|
+
var _a;
|
|
46
|
+
// NOTE: Compare the serialized form because every poll deserializes a new object instance.
|
|
47
|
+
let previous;
|
|
48
|
+
while (!(signal === null || signal === void 0 ? void 0 : signal.aborted)) {
|
|
49
|
+
const entity = await this.read(signal);
|
|
50
|
+
const serialized = this.serializer.serialize(entity);
|
|
51
|
+
if (serialized !== previous) {
|
|
52
|
+
previous = serialized;
|
|
53
|
+
yield entity;
|
|
54
|
+
}
|
|
55
|
+
if ((_a = this.endCondition) === null || _a === void 0 ? void 0 : _a.call(this, entity))
|
|
56
|
+
return;
|
|
57
|
+
if (!await (0, Delay_1.delay)(this.pollingInterval, signal))
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Provides a stream of the `TEntity`'s states using {@link stream}.
|
|
63
|
+
*/
|
|
64
|
+
[Symbol.asyncIterator]() { return this.stream(); }
|
|
65
|
+
}
|
|
66
|
+
exports.PollingEndpoint = PollingEndpoint;
|
|
67
|
+
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiUG9sbGluZ0VuZHBvaW50LmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiUG9sbGluZ0VuZHBvaW50LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7OztBQUFBLGdFQUE2RDtBQUU3RCxtQ0FBZ0M7QUFDaEMscUNBQXdDO0FBRXhDOzs7R0FHRztBQUNILE1BQWEsZUFBeUIsU0FBUSxpQ0FBd0I7SUFDbEU7Ozs7O09BS0c7SUFDSCxZQUFZLFFBQWtCLEVBQUUsV0FBeUIsRUFBbUIsWUFBMkM7UUFDbkgsS0FBSyxDQUFDLFFBQVEsRUFBRSxXQUFXLENBQUMsQ0FBQztRQUQyQyxpQkFBWSxHQUFaLFlBQVksQ0FBK0I7UUFJdkg7OztXQUdHO1FBQ0gsb0JBQWUsR0FBRyxJQUFJLENBQUM7SUFOdkIsQ0FBQztJQVFEOztPQUVHO0lBQ08sS0FBSyxDQUFDLE1BQU0sQ0FBQyxRQUFrQjs7UUFDckMsTUFBTSxLQUFLLENBQUMsTUFBTSxDQUFDLFFBQVEsQ0FBQyxDQUFDO1FBQzdCLElBQUksQ0FBQyxlQUFlLEdBQUcsTUFBQSxJQUFBLGlCQUFVLEVBQUMsUUFBUSxDQUFDLG1DQUFJLElBQUksQ0FBQyxlQUFlLENBQUM7SUFDeEUsQ0FBQztJQUVEOzs7Ozs7OztPQVFHO0lBQ0gsS0FBSyxDQUFDLENBQUMsTUFBTSxDQUFDLE1BQW9COztRQUM5QiwyRkFBMkY7UUFDM0YsSUFBSSxRQUE0QixDQUFDO1FBRWpDLE9BQU8sQ0FBQyxDQUFBLE1BQU0sYUFBTixNQUFNLHVCQUFOLE1BQU0sQ0FBRSxPQUFPLENBQUEsRUFBRSxDQUFDO1lBQ3RCLE1BQU0sTUFBTSxHQUFHLE1BQU0sSUFBSSxDQUFDLElBQUksQ0FBQyxNQUFNLENBQUMsQ0FBQztZQUV2QyxNQUFNLFVBQVUsR0FBRyxJQUFJLENBQUMsVUFBVSxDQUFDLFNBQVMsQ0FBQyxNQUFNLENBQUMsQ0FBQztZQUNyRCxJQUFJLFVBQVUsS0FBSyxRQUFRLEVBQUUsQ0FBQztnQkFDMUIsUUFBUSxHQUFHLFVBQVUsQ0FBQztnQkFDdEIsTUFBTSxNQUFNLENBQUM7WUFDakIsQ0FBQztZQUVELElBQUksTUFBQSxJQUFJLENBQUMsWUFBWSxxREFBRyxNQUFNLENBQUM7Z0JBQUUsT0FBTztZQUN4QyxJQUFJLENBQUMsTUFBTSxJQUFBLGFBQUssRUFBQyxJQUFJLENBQUMsZUFBZSxFQUFFLE1BQU0sQ0FBQztnQkFBRSxPQUFPO1FBQzNELENBQUM7SUFDTCxDQUFDO0lBRUQ7O09BRUc7SUFDSCxDQUFDLE1BQU0sQ0FBQyxhQUFhLENBQUMsS0FBSyxPQUFPLElBQUksQ0FBQyxNQUFNLEVBQUUsQ0FBQyxDQUFDLENBQUM7Q0FDckQ7QUF4REQsMENBd0RDIn0=
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import fetchMock from 'jest-fetch-mock';
|
|
2
|
+
import { PollingEndpoint } from '.';
|
|
3
|
+
import { EntryEndpoint } from '..';
|
|
4
|
+
import { HttpHeader } from '../../http';
|
|
5
|
+
|
|
6
|
+
class MockEntity {
|
|
7
|
+
constructor(public id: number, public name: string) { }
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
fetchMock.enableMocks();
|
|
11
|
+
let endpoint: PollingEndpoint<MockEntity>;
|
|
12
|
+
|
|
13
|
+
beforeEach(() => {
|
|
14
|
+
fetchMock.resetMocks();
|
|
15
|
+
endpoint = new PollingEndpoint<MockEntity>(new EntryEndpoint('http://localhost/'), 'endpoint', x => x.id === 3);
|
|
16
|
+
endpoint.pollingInterval = 0;
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
async function collect<T>(stream: AsyncIterable<T>) {
|
|
20
|
+
const result: T[] = [];
|
|
21
|
+
for await (const element of stream) result.push(element);
|
|
22
|
+
return result;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
test('stream', async () => {
|
|
26
|
+
fetchMock.mockResponses(
|
|
27
|
+
'{"id":1,"name":"test"}',
|
|
28
|
+
'{"id":2,"name":"test"}',
|
|
29
|
+
['{"id":3,"name":"test"}', { headers: { [HttpHeader.RetryAfter]: '42' } }]
|
|
30
|
+
);
|
|
31
|
+
|
|
32
|
+
expect(await collect(endpoint.stream())).toEqual([
|
|
33
|
+
new MockEntity(1, 'test'),
|
|
34
|
+
new MockEntity(2, 'test'),
|
|
35
|
+
new MockEntity(3, 'test')
|
|
36
|
+
]);
|
|
37
|
+
expect(endpoint.pollingInterval).toBe(42000);
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
test('streamSkipsUnchanged', async () => {
|
|
41
|
+
fetchMock.mockResponses(
|
|
42
|
+
'{"id":1,"name":"test"}',
|
|
43
|
+
'{"id":1,"name":"test"}',
|
|
44
|
+
'{"id":2,"name":"test"}',
|
|
45
|
+
'{"id":3,"name":"test"}'
|
|
46
|
+
);
|
|
47
|
+
|
|
48
|
+
expect(await collect(endpoint.stream())).toEqual([
|
|
49
|
+
new MockEntity(1, 'test'),
|
|
50
|
+
new MockEntity(2, 'test'),
|
|
51
|
+
new MockEntity(3, 'test')
|
|
52
|
+
]);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
test('streamAsyncIterator', async () => {
|
|
56
|
+
fetchMock.mockResponses('{"id":3,"name":"test"}');
|
|
57
|
+
|
|
58
|
+
expect(await collect(endpoint)).toEqual([new MockEntity(3, 'test')]);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
test('streamAbort', async () => {
|
|
62
|
+
fetchMock.mockResponse('{"id":1,"name":"test"}');
|
|
63
|
+
const controller = new AbortController();
|
|
64
|
+
|
|
65
|
+
const result: MockEntity[] = [];
|
|
66
|
+
for await (const element of endpoint.stream(controller.signal)) {
|
|
67
|
+
result.push(element);
|
|
68
|
+
controller.abort();
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
expect(result).toEqual([new MockEntity(1, 'test')]);
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
test('streamBreak', async () => {
|
|
75
|
+
fetchMock.mockResponse('{"id":1,"name":"test"}');
|
|
76
|
+
|
|
77
|
+
const result: MockEntity[] = [];
|
|
78
|
+
for await (const element of endpoint.stream()) {
|
|
79
|
+
result.push(element);
|
|
80
|
+
break;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
expect(result).toEqual([new MockEntity(1, 'test')]);
|
|
84
|
+
});
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { ElementEndpoint } from "../generic/ElementEndpoint";
|
|
2
|
+
import { Endpoint } from "../Endpoint";
|
|
3
|
+
import { delay } from "./Delay";
|
|
4
|
+
import { retryAfter } from "../../http";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Endpoint for a resource that can be polled for state changes.
|
|
8
|
+
* @typeParam TEntity The type of entity the endpoint represents.
|
|
9
|
+
*/
|
|
10
|
+
export class PollingEndpoint<TEntity> extends ElementEndpoint<TEntity> {
|
|
11
|
+
/**
|
|
12
|
+
* Creates a new polling endpoint.
|
|
13
|
+
* @param referrer The endpoint used to navigate to this one.
|
|
14
|
+
* @param relativeUri The URI of this endpoint relative to the `referrer`'s. Add a `./` prefix here to imply a trailing slash in the `referrer`'s URI.
|
|
15
|
+
* @param endCondition A check to determine whether the entity has reached its final state and no further polling is required.
|
|
16
|
+
*/
|
|
17
|
+
constructor(referrer: Endpoint, relativeUri: URL | string, private readonly endCondition?: (entity: TEntity) => boolean) {
|
|
18
|
+
super(referrer, relativeUri);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The interval in milliseconds to wait between polling requests.
|
|
23
|
+
* Automatically updated whenever the server sends a {@link http!HttpHeader.RetryAfter} header.
|
|
24
|
+
*/
|
|
25
|
+
pollingInterval = 3000;
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* @inheritDoc
|
|
29
|
+
*/
|
|
30
|
+
protected async handle(response: Response) {
|
|
31
|
+
await super.handle(response);
|
|
32
|
+
this.pollingInterval = retryAfter(response) ?? this.pollingInterval;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Provides a stream of the `TEntity`'s states, polling the server for changes.
|
|
37
|
+
* States that are identical to the previously provided one are skipped.
|
|
38
|
+
* @param signal Used to stop polling.
|
|
39
|
+
* @throws {@link errors!AuthenticationError}: {@link http!HttpStatusCode.Unauthorized}
|
|
40
|
+
* @throws {@link errors!AuthorizationError}: {@link http!HttpStatusCode.Forbidden}
|
|
41
|
+
* @throws {@link errors!NotFoundError}: {@link http!HttpStatusCode.NotFound} or {@link http!HttpStatusCode.Gone}
|
|
42
|
+
* @throws {@link errors!HttpError}: Other non-success status code
|
|
43
|
+
*/
|
|
44
|
+
async *stream(signal?: AbortSignal): AsyncIterableIterator<TEntity> {
|
|
45
|
+
// NOTE: Compare the serialized form because every poll deserializes a new object instance.
|
|
46
|
+
let previous: string | undefined;
|
|
47
|
+
|
|
48
|
+
while (!signal?.aborted) {
|
|
49
|
+
const entity = await this.read(signal);
|
|
50
|
+
|
|
51
|
+
const serialized = this.serializer.serialize(entity);
|
|
52
|
+
if (serialized !== previous) {
|
|
53
|
+
previous = serialized;
|
|
54
|
+
yield entity;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
if (this.endCondition?.(entity)) return;
|
|
58
|
+
if (!await delay(this.pollingInterval, signal)) return;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Provides a stream of the `TEntity`'s states using {@link stream}.
|
|
64
|
+
*/
|
|
65
|
+
[Symbol.asyncIterator]() { return this.stream(); }
|
|
66
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SseStreamingEndpoint = void 0;
|
|
4
|
+
const Endpoint_1 = require("../Endpoint");
|
|
5
|
+
const Delay_1 = require("./Delay");
|
|
6
|
+
const http_1 = require("../../http");
|
|
7
|
+
const eventStreamMediaType = "text/event-stream";
|
|
8
|
+
/**
|
|
9
|
+
* Endpoint for a stream of `TEntity`s using Server-Sent Events (SSE).<br>
|
|
10
|
+
* Sends `Accept: text/event-stream`. By default, transparently reconnects on connection drops or transient errors,
|
|
11
|
+
* honoring the server-supplied `retry:` interval and resuming via the {@link http!HttpHeader.LastEventId} header.
|
|
12
|
+
* @typeParam TEntity The type of individual elements in the stream.
|
|
13
|
+
*/
|
|
14
|
+
class SseStreamingEndpoint extends Endpoint_1.Endpoint {
|
|
15
|
+
/**
|
|
16
|
+
* Creates a new SSE streaming endpoint.
|
|
17
|
+
* @param referrer The endpoint used to navigate to this one.
|
|
18
|
+
* @param relativeUri The URI of this endpoint relative to the `referrer`'s. Add a `./` prefix here to imply a trailing slash in the `referrer`'s URI.
|
|
19
|
+
* @param eventType If set, only events with this `event:` type are provided; others are ignored. Leave unspecified to provide all events.
|
|
20
|
+
*/
|
|
21
|
+
constructor(referrer, relativeUri, eventType) {
|
|
22
|
+
super(referrer, relativeUri);
|
|
23
|
+
this.eventType = eventType;
|
|
24
|
+
/**
|
|
25
|
+
* Whether to transparently reconnect on connection drops, transient transport errors and 5xx responses.
|
|
26
|
+
*/
|
|
27
|
+
this.autoReconnect = true;
|
|
28
|
+
/**
|
|
29
|
+
* The reconnection interval in milliseconds used when the server has not (yet) supplied one via the SSE `retry:` field.
|
|
30
|
+
*/
|
|
31
|
+
this.defaultReconnectionInterval = 3000;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Provides a stream of `TEntity`s, reconnecting as needed unless {@link autoReconnect} is disabled.
|
|
35
|
+
* @param signal Used to close the connection.
|
|
36
|
+
* @throws {@link errors!AuthenticationError}: {@link http!HttpStatusCode.Unauthorized}
|
|
37
|
+
* @throws {@link errors!AuthorizationError}: {@link http!HttpStatusCode.Forbidden}
|
|
38
|
+
* @throws {@link errors!NotFoundError}: {@link http!HttpStatusCode.NotFound} or {@link http!HttpStatusCode.Gone}
|
|
39
|
+
* @throws {@link errors!HttpError}: Other non-success status code
|
|
40
|
+
*/
|
|
41
|
+
async *stream(signal) {
|
|
42
|
+
const state = { lastEventId: undefined, reconnectionInterval: this.defaultReconnectionInterval };
|
|
43
|
+
while (!(signal === null || signal === void 0 ? void 0 : signal.aborted)) {
|
|
44
|
+
let reconnect;
|
|
45
|
+
try {
|
|
46
|
+
reconnect = yield* this.consumeOnce(state, signal);
|
|
47
|
+
}
|
|
48
|
+
catch (err) {
|
|
49
|
+
// Aborting is a regular way of ending the stream, not an error
|
|
50
|
+
if (signal === null || signal === void 0 ? void 0 : signal.aborted)
|
|
51
|
+
return;
|
|
52
|
+
// Transport-level failures are the ones worth retrying; anything else is the server telling us no
|
|
53
|
+
if (!this.autoReconnect || !SseStreamingEndpoint.isTransient(err))
|
|
54
|
+
throw err;
|
|
55
|
+
reconnect = true;
|
|
56
|
+
}
|
|
57
|
+
if (!reconnect)
|
|
58
|
+
return;
|
|
59
|
+
if (!await (0, Delay_1.delay)(state.reconnectionInterval, signal))
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Provides a stream of `TEntity`s using {@link stream}.
|
|
65
|
+
*/
|
|
66
|
+
[Symbol.asyncIterator]() { return this.stream(); }
|
|
67
|
+
/**
|
|
68
|
+
* Opens a connection and provides events until the stream ends.
|
|
69
|
+
* @param state Carries the last event id and the reconnection interval over to the next attempt.
|
|
70
|
+
* @param signal Used to close the connection.
|
|
71
|
+
* @returns `true` if another connection attempt should be made; `false` if the stream has ended for good.
|
|
72
|
+
*/
|
|
73
|
+
async *consumeOnce(state, signal) {
|
|
74
|
+
var _a;
|
|
75
|
+
// NOTE: Abort the request when the consumer stops iterating, not just when the caller's signal fires.
|
|
76
|
+
const controller = new AbortController();
|
|
77
|
+
const onAbort = () => controller.abort();
|
|
78
|
+
signal === null || signal === void 0 ? void 0 : signal.addEventListener("abort", onAbort, { once: true });
|
|
79
|
+
if (signal === null || signal === void 0 ? void 0 : signal.aborted)
|
|
80
|
+
controller.abort();
|
|
81
|
+
try {
|
|
82
|
+
const headers = new Headers({ [http_1.HttpHeader.Accept]: eventStreamMediaType });
|
|
83
|
+
if (state.lastEventId)
|
|
84
|
+
headers.set(http_1.HttpHeader.LastEventId, state.lastEventId);
|
|
85
|
+
const response = await this.httpClient.send(this.uri, http_1.HttpMethod.Get, controller.signal, headers);
|
|
86
|
+
if (response.status === http_1.HttpStatusCode.NoContent)
|
|
87
|
+
return false;
|
|
88
|
+
if (this.autoReconnect && response.status >= 500)
|
|
89
|
+
return true;
|
|
90
|
+
await this.handle(response);
|
|
91
|
+
const reader = new http_1.SseReader(response);
|
|
92
|
+
try {
|
|
93
|
+
for await (const event of reader.events()) {
|
|
94
|
+
if (this.eventType !== undefined && event.type !== this.eventType)
|
|
95
|
+
continue;
|
|
96
|
+
yield this.serializer.deserialize(event.data);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
finally {
|
|
100
|
+
state.lastEventId = (_a = reader.lastEventId) !== null && _a !== void 0 ? _a : state.lastEventId;
|
|
101
|
+
if (reader.reconnectionInterval !== undefined)
|
|
102
|
+
state.reconnectionInterval = reader.reconnectionInterval;
|
|
103
|
+
}
|
|
104
|
+
return this.autoReconnect;
|
|
105
|
+
}
|
|
106
|
+
finally {
|
|
107
|
+
signal === null || signal === void 0 ? void 0 : signal.removeEventListener("abort", onAbort);
|
|
108
|
+
controller.abort();
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Determines whether an error is a transport-level failure that may succeed on a retry.
|
|
113
|
+
* The Fetch API reports these as `TypeError`s, while responses the server actually sent become {@link errors!HttpError}s.
|
|
114
|
+
*/
|
|
115
|
+
static isTransient(err) {
|
|
116
|
+
return err instanceof TypeError;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
exports.SseStreamingEndpoint = SseStreamingEndpoint;
|
|
120
|
+
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiU3NlU3RyZWFtaW5nRW5kcG9pbnQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJTc2VTdHJlYW1pbmdFbmRwb2ludC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7QUFBQSwwQ0FBdUM7QUFDdkMsbUNBQWdDO0FBQ2hDLHFDQUErRTtBQUUvRSxNQUFNLG9CQUFvQixHQUFHLG1CQUFtQixDQUFDO0FBRWpEOzs7OztHQUtHO0FBQ0gsTUFBYSxvQkFBOEIsU0FBUSxtQkFBUTtJQUN2RDs7Ozs7T0FLRztJQUNILFlBQVksUUFBa0IsRUFBRSxXQUF5QixFQUFtQixTQUFrQjtRQUMxRixLQUFLLENBQUMsUUFBUSxFQUFFLFdBQVcsQ0FBQyxDQUFDO1FBRDJDLGNBQVMsR0FBVCxTQUFTLENBQVM7UUFJOUY7O1dBRUc7UUFDSCxrQkFBYSxHQUFHLElBQUksQ0FBQztRQUVyQjs7V0FFRztRQUNILGdDQUEyQixHQUFHLElBQUksQ0FBQ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QUN2QixDQUFDO0lBQ0wsQ0FBQztJQUVEOzs7T0FHRztJQUNLLE1BQU0sQ0FBQyxXQUFXLENBQUMsR0FBWTtRQUNuQyxPQUFPLEdBQUcsWUFBWSxTQUFTLENBQUM7SUFDcEMsQ0FBQztDQUNKO0FBdEdELG9EQXNHQyJ9
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* NOTE: The jsdom environment does not expose response bodies as streams, so these tests need the node environment.
|
|
3
|
+
* @jest-environment node
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import fetchMock from 'jest-fetch-mock';
|
|
7
|
+
import { SseStreamingEndpoint } from '.';
|
|
8
|
+
import { EntryEndpoint } from '..';
|
|
9
|
+
import { ConflictError } from '../../errors';
|
|
10
|
+
import { HttpHeader, HttpStatusCode } from '../../http';
|
|
11
|
+
|
|
12
|
+
class MockEntity {
|
|
13
|
+
constructor(public id: number, public name: string) { }
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
fetchMock.enableMocks();
|
|
17
|
+
let entryEndpoint: EntryEndpoint;
|
|
18
|
+
let endpoint: SseStreamingEndpoint<MockEntity>;
|
|
19
|
+
|
|
20
|
+
beforeEach(() => {
|
|
21
|
+
fetchMock.resetMocks();
|
|
22
|
+
entryEndpoint = new EntryEndpoint('http://localhost/');
|
|
23
|
+
endpoint = new SseStreamingEndpoint<MockEntity>(entryEndpoint, 'endpoint');
|
|
24
|
+
endpoint.autoReconnect = false;
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
function sseEvent(data: string, type?: string, id?: string) {
|
|
28
|
+
return (type ? `event: ${type}\n` : '')
|
|
29
|
+
+ (id ? `id: ${id}\n` : '')
|
|
30
|
+
+ `data: ${data}\n\n`;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Mocks a response that ends the stream for good.<br>
|
|
35
|
+
* NOTE: Needs a `null` body because a 204 response must not have one.
|
|
36
|
+
*/
|
|
37
|
+
function mockNoContentOnce() {
|
|
38
|
+
fetchMock.mockImplementationOnce(async () => new Response(null, { status: HttpStatusCode.NoContent }));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function requestHeader(index: number, header: HttpHeader) {
|
|
42
|
+
return new Headers(fetchMock.mock.calls[index][1]?.headers).get(header);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async function collect<T>(stream: AsyncIterable<T>) {
|
|
46
|
+
const result: T[] = [];
|
|
47
|
+
for await (const element of stream) result.push(element);
|
|
48
|
+
return result;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
test('stream', async () => {
|
|
52
|
+
fetchMock.mockResponseOnce(
|
|
53
|
+
sseEvent('{"id":5,"name":"test1"}')
|
|
54
|
+
+ sseEvent('{"id":6,"name":"test2"}')
|
|
55
|
+
+ sseEvent('{"id":7,"name":"test3"}'));
|
|
56
|
+
|
|
57
|
+
expect(await collect(endpoint.stream())).toEqual([
|
|
58
|
+
new MockEntity(5, 'test1'),
|
|
59
|
+
new MockEntity(6, 'test2'),
|
|
60
|
+
new MockEntity(7, 'test3')
|
|
61
|
+
]);
|
|
62
|
+
expect(requestHeader(0, HttpHeader.Accept)).toBe('text/event-stream');
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
test('streamAsyncIterator', async () => {
|
|
66
|
+
fetchMock.mockResponseOnce(sseEvent('{"id":5,"name":"test1"}'));
|
|
67
|
+
|
|
68
|
+
expect(await collect(endpoint)).toEqual([new MockEntity(5, 'test1')]);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
test('streamEventTypeFilter', async () => {
|
|
72
|
+
endpoint = new SseStreamingEndpoint<MockEntity>(entryEndpoint, 'endpoint', 'update');
|
|
73
|
+
endpoint.autoReconnect = false;
|
|
74
|
+
|
|
75
|
+
fetchMock.mockResponseOnce(
|
|
76
|
+
sseEvent('{"id":1,"name":"skip"}', 'ignored')
|
|
77
|
+
+ sseEvent('{"id":5,"name":"test1"}', 'update')
|
|
78
|
+
+ sseEvent('{"id":99,"name":"default"}')
|
|
79
|
+
+ sseEvent('{"id":6,"name":"test2"}', 'update'));
|
|
80
|
+
|
|
81
|
+
expect(await collect(endpoint.stream())).toEqual([
|
|
82
|
+
new MockEntity(5, 'test1'),
|
|
83
|
+
new MockEntity(6, 'test2')
|
|
84
|
+
]);
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
test('streamComments', async () => {
|
|
88
|
+
fetchMock.mockResponseOnce(': keep-alive\n\n' + sseEvent('{"id":5,"name":"test1"}'));
|
|
89
|
+
|
|
90
|
+
expect(await collect(endpoint.stream())).toEqual([new MockEntity(5, 'test1')]);
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
test('streamMultiLineData', async () => {
|
|
94
|
+
fetchMock.mockResponseOnce('data: {"id":5,\ndata: "name":"test1"}\n\n');
|
|
95
|
+
|
|
96
|
+
expect(await collect(endpoint.stream())).toEqual([new MockEntity(5, 'test1')]);
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
test('streamCarriageReturns', async () => {
|
|
100
|
+
fetchMock.mockResponseOnce('data: {"id":5,"name":"test1"}\r\n\r\ndata: {"id":6,"name":"test2"}\r\r');
|
|
101
|
+
|
|
102
|
+
expect(await collect(endpoint.stream())).toEqual([
|
|
103
|
+
new MockEntity(5, 'test1'),
|
|
104
|
+
new MockEntity(6, 'test2')
|
|
105
|
+
]);
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
test('streamError', async () => {
|
|
109
|
+
fetchMock.mockResponseOnce('{"message":"my message"}', {
|
|
110
|
+
status: HttpStatusCode.Conflict,
|
|
111
|
+
headers: { [HttpHeader.ContentType]: 'application/json' }
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
await expect(collect(endpoint.stream())).rejects.toThrow(new ConflictError('my message', HttpStatusCode.Conflict));
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
test('streamNoContentCompletes', async () => {
|
|
118
|
+
endpoint.autoReconnect = true;
|
|
119
|
+
mockNoContentOnce();
|
|
120
|
+
|
|
121
|
+
expect(await collect(endpoint.stream())).toEqual([]);
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
test('streamReconnectsWithLastEventId', async () => {
|
|
125
|
+
endpoint.autoReconnect = true;
|
|
126
|
+
endpoint.defaultReconnectionInterval = 0;
|
|
127
|
+
fetchMock.mockResponseOnce(sseEvent('{"id":5,"name":"test1"}', undefined, '42'));
|
|
128
|
+
mockNoContentOnce();
|
|
129
|
+
|
|
130
|
+
expect(await collect(endpoint.stream())).toEqual([new MockEntity(5, 'test1')]);
|
|
131
|
+
expect(requestHeader(0, HttpHeader.LastEventId)).toBeNull();
|
|
132
|
+
expect(requestHeader(1, HttpHeader.LastEventId)).toBe('42');
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
test('streamReconnectsOnServerError', async () => {
|
|
136
|
+
endpoint.autoReconnect = true;
|
|
137
|
+
endpoint.defaultReconnectionInterval = 0;
|
|
138
|
+
fetchMock.mockResponseOnce('', { status: 503 });
|
|
139
|
+
fetchMock.mockResponseOnce(sseEvent('{"id":5,"name":"test1"}'));
|
|
140
|
+
mockNoContentOnce();
|
|
141
|
+
|
|
142
|
+
expect(await collect(endpoint.stream())).toEqual([new MockEntity(5, 'test1')]);
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
test('streamHonorsRetryField', async () => {
|
|
146
|
+
endpoint.autoReconnect = true;
|
|
147
|
+
endpoint.defaultReconnectionInterval = 0;
|
|
148
|
+
fetchMock.mockResponseOnce('retry: 42\n\n' + sseEvent('{"id":5,"name":"test1"}'));
|
|
149
|
+
mockNoContentOnce();
|
|
150
|
+
|
|
151
|
+
const start = Date.now();
|
|
152
|
+
expect(await collect(endpoint.stream())).toEqual([new MockEntity(5, 'test1')]);
|
|
153
|
+
expect(Date.now() - start).toBeGreaterThanOrEqual(42);
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
test('streamAbort', async () => {
|
|
157
|
+
endpoint.autoReconnect = true;
|
|
158
|
+
endpoint.defaultReconnectionInterval = 0;
|
|
159
|
+
fetchMock.mockResponse(sseEvent('{"id":5,"name":"test1"}'));
|
|
160
|
+
const controller = new AbortController();
|
|
161
|
+
|
|
162
|
+
const result: MockEntity[] = [];
|
|
163
|
+
for await (const element of endpoint.stream(controller.signal)) {
|
|
164
|
+
result.push(element);
|
|
165
|
+
controller.abort();
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
expect(result).toEqual([new MockEntity(5, 'test1')]);
|
|
169
|
+
});
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { Endpoint } from "../Endpoint";
|
|
2
|
+
import { delay } from "./Delay";
|
|
3
|
+
import { HttpMethod, HttpHeader, HttpStatusCode, SseReader } from "../../http";
|
|
4
|
+
|
|
5
|
+
const eventStreamMediaType = "text/event-stream";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Endpoint for a stream of `TEntity`s using Server-Sent Events (SSE).<br>
|
|
9
|
+
* Sends `Accept: text/event-stream`. By default, transparently reconnects on connection drops or transient errors,
|
|
10
|
+
* honoring the server-supplied `retry:` interval and resuming via the {@link http!HttpHeader.LastEventId} header.
|
|
11
|
+
* @typeParam TEntity The type of individual elements in the stream.
|
|
12
|
+
*/
|
|
13
|
+
export class SseStreamingEndpoint<TEntity> extends Endpoint {
|
|
14
|
+
/**
|
|
15
|
+
* Creates a new SSE streaming endpoint.
|
|
16
|
+
* @param referrer The endpoint used to navigate to this one.
|
|
17
|
+
* @param relativeUri The URI of this endpoint relative to the `referrer`'s. Add a `./` prefix here to imply a trailing slash in the `referrer`'s URI.
|
|
18
|
+
* @param eventType If set, only events with this `event:` type are provided; others are ignored. Leave unspecified to provide all events.
|
|
19
|
+
*/
|
|
20
|
+
constructor(referrer: Endpoint, relativeUri: URL | string, private readonly eventType?: string) {
|
|
21
|
+
super(referrer, relativeUri);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Whether to transparently reconnect on connection drops, transient transport errors and 5xx responses.
|
|
26
|
+
*/
|
|
27
|
+
autoReconnect = true;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The reconnection interval in milliseconds used when the server has not (yet) supplied one via the SSE `retry:` field.
|
|
31
|
+
*/
|
|
32
|
+
defaultReconnectionInterval = 3000;
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Provides a stream of `TEntity`s, reconnecting as needed unless {@link autoReconnect} is disabled.
|
|
36
|
+
* @param signal Used to close the connection.
|
|
37
|
+
* @throws {@link errors!AuthenticationError}: {@link http!HttpStatusCode.Unauthorized}
|
|
38
|
+
* @throws {@link errors!AuthorizationError}: {@link http!HttpStatusCode.Forbidden}
|
|
39
|
+
* @throws {@link errors!NotFoundError}: {@link http!HttpStatusCode.NotFound} or {@link http!HttpStatusCode.Gone}
|
|
40
|
+
* @throws {@link errors!HttpError}: Other non-success status code
|
|
41
|
+
*/
|
|
42
|
+
async *stream(signal?: AbortSignal): AsyncIterableIterator<TEntity> {
|
|
43
|
+
const state = { lastEventId: undefined as string | undefined, reconnectionInterval: this.defaultReconnectionInterval };
|
|
44
|
+
|
|
45
|
+
while (!signal?.aborted) {
|
|
46
|
+
let reconnect: boolean;
|
|
47
|
+
try {
|
|
48
|
+
reconnect = yield* this.consumeOnce(state, signal);
|
|
49
|
+
} catch (err) {
|
|
50
|
+
// Aborting is a regular way of ending the stream, not an error
|
|
51
|
+
if (signal?.aborted) return;
|
|
52
|
+
|
|
53
|
+
// Transport-level failures are the ones worth retrying; anything else is the server telling us no
|
|
54
|
+
if (!this.autoReconnect || !SseStreamingEndpoint.isTransient(err)) throw err;
|
|
55
|
+
reconnect = true;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
if (!reconnect) return;
|
|
59
|
+
if (!await delay(state.reconnectionInterval, signal)) return;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Provides a stream of `TEntity`s using {@link stream}.
|
|
65
|
+
*/
|
|
66
|
+
[Symbol.asyncIterator]() { return this.stream(); }
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Opens a connection and provides events until the stream ends.
|
|
70
|
+
* @param state Carries the last event id and the reconnection interval over to the next attempt.
|
|
71
|
+
* @param signal Used to close the connection.
|
|
72
|
+
* @returns `true` if another connection attempt should be made; `false` if the stream has ended for good.
|
|
73
|
+
*/
|
|
74
|
+
private async *consumeOnce(state: { lastEventId?: string; reconnectionInterval: number; }, signal?: AbortSignal): AsyncGenerator<TEntity, boolean> {
|
|
75
|
+
// NOTE: Abort the request when the consumer stops iterating, not just when the caller's signal fires.
|
|
76
|
+
const controller = new AbortController();
|
|
77
|
+
const onAbort = () => controller.abort();
|
|
78
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
79
|
+
if (signal?.aborted) controller.abort();
|
|
80
|
+
|
|
81
|
+
try {
|
|
82
|
+
const headers = new Headers({ [HttpHeader.Accept]: eventStreamMediaType });
|
|
83
|
+
if (state.lastEventId) headers.set(HttpHeader.LastEventId, state.lastEventId);
|
|
84
|
+
|
|
85
|
+
const response = await this.httpClient.send(this.uri, HttpMethod.Get, controller.signal, headers);
|
|
86
|
+
if (response.status === HttpStatusCode.NoContent) return false;
|
|
87
|
+
if (this.autoReconnect && response.status >= 500) return true;
|
|
88
|
+
await this.handle(response);
|
|
89
|
+
|
|
90
|
+
const reader = new SseReader(response);
|
|
91
|
+
try {
|
|
92
|
+
for await (const event of reader.events()) {
|
|
93
|
+
if (this.eventType !== undefined && event.type !== this.eventType) continue;
|
|
94
|
+
yield this.serializer.deserialize<TEntity>(event.data);
|
|
95
|
+
}
|
|
96
|
+
} finally {
|
|
97
|
+
state.lastEventId = reader.lastEventId ?? state.lastEventId;
|
|
98
|
+
if (reader.reconnectionInterval !== undefined) state.reconnectionInterval = reader.reconnectionInterval;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
return this.autoReconnect;
|
|
102
|
+
} finally {
|
|
103
|
+
signal?.removeEventListener("abort", onAbort);
|
|
104
|
+
controller.abort();
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Determines whether an error is a transport-level failure that may succeed on a retry.
|
|
110
|
+
* The Fetch API reports these as `TypeError`s, while responses the server actually sent become {@link errors!HttpError}s.
|
|
111
|
+
*/
|
|
112
|
+
private static isTransient(err: unknown) {
|
|
113
|
+
return err instanceof TypeError;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.StreamingCollectionEndpoint = void 0;
|
|
4
|
+
const GenericStreamingCollectionEndpoint_1 = require("./GenericStreamingCollectionEndpoint");
|
|
5
|
+
const ElementEndpoint_1 = require("../generic/ElementEndpoint");
|
|
6
|
+
/**
|
|
7
|
+
* Endpoint for a collection of `TEntity`s observable as an append-only stream using long-polling,
|
|
8
|
+
* addressable as {@link ElementEndpoint}s.<br>
|
|
9
|
+
* Use {@link GenericStreamingCollectionEndpoint} instead if you wish to customize the element endpoint type.
|
|
10
|
+
* @typeParam TEntity The type of individual elements in the collection.
|
|
11
|
+
*/
|
|
12
|
+
class StreamingCollectionEndpoint extends GenericStreamingCollectionEndpoint_1.GenericStreamingCollectionEndpoint {
|
|
13
|
+
/**
|
|
14
|
+
* Creates a new streaming collection endpoint.
|
|
15
|
+
* @param referrer The endpoint used to navigate to this one.
|
|
16
|
+
* @param relativeUri The URI of this endpoint relative to the `referrer`'s. Add a `./` prefix here to imply a trailing slash in the `referrer`'s URI.
|
|
17
|
+
*/
|
|
18
|
+
constructor(referrer, relativeUri) {
|
|
19
|
+
super(referrer, relativeUri, ElementEndpoint_1.ElementEndpoint);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
exports.StreamingCollectionEndpoint = StreamingCollectionEndpoint;
|
|
23
|
+
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiU3RyZWFtaW5nQ29sbGVjdGlvbkVuZHBvaW50LmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiU3RyZWFtaW5nQ29sbGVjdGlvbkVuZHBvaW50LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7OztBQUFBLDZGQUEwRjtBQUMxRixnRUFBNkQ7QUFHN0Q7Ozs7O0dBS0c7QUFDSCxNQUFhLDJCQUFxQyxTQUFRLHVFQUFxRTtJQUMzSDs7OztPQUlHO0lBQ0gsWUFBWSxRQUFrQixFQUFFLFdBQXlCO1FBQ3JELEtBQUssQ0FBQyxRQUFRLEVBQUUsV0FBVyxFQUFFLGlDQUFlLENBQUMsQ0FBQztJQUNsRCxDQUFDO0NBQ0o7QUFURCxrRUFTQyJ9
|