@evefrontier/dapp-kit 0.1.9 → 0.2.0-alpha.1
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 +28 -25
- package/dist/config/dapp-kit.d.ts +4 -0
- package/dist/config/dapp-kit.d.ts.map +1 -0
- package/dist/config/dapp-kit.js +14 -0
- package/dist/config/index.d.ts +2 -0
- package/dist/config/index.d.ts.map +1 -0
- package/dist/config/index.js +1 -0
- package/dist/graphql/client.d.ts +277 -0
- package/dist/graphql/client.d.ts.map +1 -0
- package/dist/graphql/client.js +346 -0
- package/dist/graphql/index.d.ts +4 -0
- package/dist/graphql/index.d.ts.map +1 -0
- package/dist/graphql/index.js +16 -0
- package/dist/graphql/queries.d.ts +103 -0
- package/dist/graphql/queries.d.ts.map +1 -0
- package/{graphql/queries.ts → dist/graphql/queries.js} +113 -223
- package/dist/graphql/types.d.ts +396 -0
- package/dist/graphql/types.d.ts.map +1 -0
- package/dist/graphql/types.js +4 -0
- package/dist/hooks/index.d.ts +10 -0
- package/dist/hooks/index.d.ts.map +1 -0
- package/dist/hooks/index.js +8 -0
- package/dist/hooks/useCharacterDirectory.d.ts +16 -0
- package/dist/hooks/useCharacterDirectory.d.ts.map +1 -0
- package/dist/hooks/useCharacterDirectory.js +23 -0
- package/dist/hooks/useCharacterSearch.d.ts +24 -0
- package/dist/hooks/useCharacterSearch.d.ts.map +1 -0
- package/dist/hooks/useCharacterSearch.js +24 -0
- package/dist/hooks/useConnection.d.ts +51 -0
- package/dist/hooks/useConnection.d.ts.map +1 -0
- package/{hooks/useConnection.ts → dist/hooks/useConnection.js} +8 -10
- package/dist/hooks/useEntityRole.d.ts +26 -0
- package/dist/hooks/useEntityRole.d.ts.map +1 -0
- package/dist/hooks/useEntityRole.js +91 -0
- package/dist/hooks/useNotification.d.ts +72 -0
- package/dist/hooks/useNotification.d.ts.map +1 -0
- package/{hooks/useNotification.ts → dist/hooks/useNotification.js} +8 -12
- package/dist/hooks/useSmartObject.d.ts +44 -0
- package/dist/hooks/useSmartObject.d.ts.map +1 -0
- package/dist/hooks/useSmartObject.js +50 -0
- package/dist/hooks/useSponsoredTransaction.d.ts +147 -0
- package/dist/hooks/useSponsoredTransaction.d.ts.map +1 -0
- package/dist/hooks/useSponsoredTransaction.js +240 -0
- package/dist/hooks/useTypeNames.d.ts +11 -0
- package/dist/hooks/useTypeNames.d.ts.map +1 -0
- package/dist/hooks/useTypeNames.js +24 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +29 -0
- package/dist/providers/EveFrontierProvider.d.ts +23 -0
- package/dist/providers/EveFrontierProvider.d.ts.map +1 -0
- package/dist/providers/EveFrontierProvider.js +23 -0
- package/dist/providers/NotificationProvider.d.ts +14 -0
- package/dist/providers/NotificationProvider.d.ts.map +1 -0
- package/dist/providers/NotificationProvider.js +66 -0
- package/dist/providers/SmartObjectProvider.d.ts +31 -0
- package/dist/providers/SmartObjectProvider.d.ts.map +1 -0
- package/dist/providers/SmartObjectProvider.js +80 -0
- package/dist/providers/VaultProvider.d.ts +10 -0
- package/dist/providers/VaultProvider.d.ts.map +1 -0
- package/dist/providers/VaultProvider.js +79 -0
- package/dist/providers/index.d.ts +5 -0
- package/dist/providers/index.d.ts.map +1 -0
- package/dist/providers/index.js +4 -0
- package/dist/providers/smartObject/useEntityData.d.ts +29 -0
- package/dist/providers/smartObject/useEntityData.d.ts.map +1 -0
- package/dist/providers/smartObject/useEntityData.js +135 -0
- package/dist/providers/smartObject/useEntitySubscription.d.ts +14 -0
- package/dist/providers/smartObject/useEntitySubscription.d.ts.map +1 -0
- package/dist/providers/smartObject/useEntitySubscription.js +58 -0
- package/dist/providers/smartObject/useObjectSelection.d.ts +11 -0
- package/dist/providers/smartObject/useObjectSelection.d.ts.map +1 -0
- package/dist/providers/smartObject/useObjectSelection.js +27 -0
- package/dist/providers/smartObject/usePollingBackstop.d.ts +18 -0
- package/dist/providers/smartObject/usePollingBackstop.d.ts.map +1 -0
- package/dist/providers/smartObject/usePollingBackstop.js +38 -0
- package/dist/types/character.d.ts +21 -0
- package/dist/types/character.d.ts.map +1 -0
- package/dist/types/character.js +1 -0
- package/dist/types/contexts.d.ts +61 -0
- package/dist/types/contexts.d.ts.map +1 -0
- package/dist/types/contexts.js +6 -0
- package/dist/types/entity.d.ts +245 -0
- package/dist/types/entity.d.ts.map +1 -0
- package/dist/types/entity.js +6 -0
- package/dist/types/index.d.ts +6 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/index.js +5 -0
- package/dist/types/sponsoredTransaction.d.ts +26 -0
- package/dist/types/sponsoredTransaction.d.ts.map +1 -0
- package/dist/types/sponsoredTransaction.js +10 -0
- package/dist/types/types.d.ts +110 -0
- package/dist/types/types.d.ts.map +1 -0
- package/dist/types/types.js +41 -0
- package/dist/types/worldApiReturnTypes.d.ts +68 -0
- package/dist/types/worldApiReturnTypes.d.ts.map +1 -0
- package/dist/types/worldApiReturnTypes.js +1 -0
- package/{utils/burnRate.ts → dist/utils/burnRate.d.ts} +4 -29
- package/dist/utils/burnRate.d.ts.map +1 -0
- package/dist/utils/burnRate.js +25 -0
- package/dist/utils/characters.d.ts +26 -0
- package/dist/utils/characters.d.ts.map +1 -0
- package/dist/utils/characters.js +84 -0
- package/dist/utils/constants.d.ts +153 -0
- package/dist/utils/constants.d.ts.map +1 -0
- package/dist/utils/constants.js +190 -0
- package/dist/utils/datahub.d.ts +40 -0
- package/dist/utils/datahub.d.ts.map +1 -0
- package/{utils/datahub.ts → dist/utils/datahub.js} +32 -25
- package/dist/utils/entity.d.ts +58 -0
- package/dist/utils/entity.d.ts.map +1 -0
- package/dist/utils/entity.js +386 -0
- package/dist/utils/errors.d.ts +18 -0
- package/dist/utils/errors.d.ts.map +1 -0
- package/dist/utils/errors.js +128 -0
- package/dist/utils/events/entityEvents.d.ts +44 -0
- package/dist/utils/events/entityEvents.d.ts.map +1 -0
- package/dist/utils/events/entityEvents.js +95 -0
- package/dist/utils/events/entitySubscription.d.ts +30 -0
- package/dist/utils/events/entitySubscription.d.ts.map +1 -0
- package/dist/utils/events/entitySubscription.js +84 -0
- package/dist/utils/events/graphqlEventStream.d.ts +90 -0
- package/dist/utils/events/graphqlEventStream.d.ts.map +1 -0
- package/dist/utils/events/graphqlEventStream.js +198 -0
- package/dist/utils/events/refetchScheduler.d.ts +30 -0
- package/dist/utils/events/refetchScheduler.d.ts.map +1 -0
- package/dist/utils/events/refetchScheduler.js +57 -0
- package/dist/utils/events/sseClient.d.ts +42 -0
- package/dist/utils/events/sseClient.d.ts.map +1 -0
- package/dist/utils/events/sseClient.js +97 -0
- package/dist/utils/fuel.d.ts +231 -0
- package/dist/utils/fuel.d.ts.map +1 -0
- package/dist/utils/fuel.js +652 -0
- package/dist/utils/grid.d.ts +115 -0
- package/dist/utils/grid.d.ts.map +1 -0
- package/dist/utils/grid.js +115 -0
- package/dist/utils/index.d.ts +15 -0
- package/dist/utils/index.d.ts.map +1 -0
- package/dist/utils/index.js +22 -0
- package/dist/utils/inventory.d.ts +3 -0
- package/dist/utils/inventory.d.ts.map +1 -0
- package/dist/utils/inventory.js +12 -0
- package/dist/utils/logger.d.ts +25 -0
- package/dist/utils/logger.d.ts.map +1 -0
- package/dist/utils/logger.js +228 -0
- package/dist/utils/mapping.d.ts +30 -0
- package/dist/utils/mapping.d.ts.map +1 -0
- package/dist/utils/mapping.js +73 -0
- package/dist/utils/mvr/worldTypes.d.ts +35 -0
- package/dist/utils/mvr/worldTypes.d.ts.map +1 -0
- package/dist/utils/mvr/worldTypes.js +54 -0
- package/dist/utils/role.d.ts +116 -0
- package/dist/utils/role.d.ts.map +1 -0
- package/dist/utils/role.js +120 -0
- package/dist/utils/smartObject.d.ts +24 -0
- package/dist/utils/smartObject.d.ts.map +1 -0
- package/dist/utils/smartObject.js +24 -0
- package/dist/utils/utils.d.ts +133 -0
- package/dist/utils/utils.d.ts.map +1 -0
- package/dist/utils/utils.js +213 -0
- package/dist/wallet/features.d.ts +28 -0
- package/dist/wallet/features.d.ts.map +1 -0
- package/dist/wallet/features.js +22 -0
- package/dist/wallet/index.d.ts +9 -0
- package/dist/wallet/index.d.ts.map +1 -0
- package/dist/wallet/index.js +9 -0
- package/dist/wallet/utils.d.ts +71 -0
- package/dist/wallet/utils.d.ts.map +1 -0
- package/dist/wallet/utils.js +79 -0
- package/package.json +69 -35
- package/config/dapp-kit.ts +0 -20
- package/config/index.ts +0 -1
- package/graphql/client.ts +0 -578
- package/graphql/index.ts +0 -39
- package/graphql/types.ts +0 -468
- package/hooks/index.ts +0 -15
- package/hooks/useSmartObject.ts +0 -66
- package/hooks/useSponsoredTransaction.ts +0 -442
- package/index.ts +0 -88
- package/providers/EveFrontierProvider.tsx +0 -41
- package/providers/NotificationProvider.tsx +0 -108
- package/providers/SmartObjectProvider.tsx +0 -296
- package/providers/VaultProvider.tsx +0 -108
- package/providers/index.ts +0 -10
- package/types/contexts.ts +0 -67
- package/types/global.d.ts +0 -7
- package/types/index.ts +0 -4
- package/types/sponsoredTransaction.ts +0 -70
- package/types/types.ts +0 -198
- package/types/worldApiReturnTypes.ts +0 -144
- package/utils/__tests__/burnRate.test.ts +0 -121
- package/utils/__tests__/character.test.ts +0 -112
- package/utils/__tests__/characterOwnedObjects.test.ts +0 -225
- package/utils/__tests__/config.test.ts +0 -424
- package/utils/__tests__/datahub.test.ts +0 -58
- package/utils/__tests__/logger.test.ts +0 -145
- package/utils/__tests__/mapping.test.ts +0 -439
- package/utils/__tests__/utils.test.ts +0 -299
- package/utils/character.ts +0 -46
- package/utils/characterOwnedObjects.ts +0 -53
- package/utils/config.ts +0 -151
- package/utils/constants.ts +0 -254
- package/utils/errors.ts +0 -171
- package/utils/index.ts +0 -47
- package/utils/logger.ts +0 -300
- package/utils/mapping.ts +0 -118
- package/utils/transforms.ts +0 -263
- package/utils/utils.ts +0 -270
- package/wallet/features.ts +0 -136
- package/wallet/index.ts +0 -26
- package/wallet/utils.ts +0 -117
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { type SubscriptionStatus } from '../constants.js';
|
|
2
|
+
import { type EventStreamClient } from './graphqlEventStream.js';
|
|
3
|
+
/**
|
|
4
|
+
* Keep one entity up to date from a GraphQL event subscription: refetch when
|
|
5
|
+
* an event about the entity arrives (a few times, for indexer lag), and once
|
|
6
|
+
* after every reconnect to backfill what was missed.
|
|
7
|
+
*
|
|
8
|
+
* There is one stream per world package. Reports `connecting`, then `live`
|
|
9
|
+
* once every stream has connected. Reports `failed`, once, on a stream error,
|
|
10
|
+
* when `fail` is called (e.g. the endpoint serves no subscriptions), or when
|
|
11
|
+
* any stream has not connected within `connectTimeoutMs`; it then stops for
|
|
12
|
+
* good, so a broken endpoint is never retried in a loop. The caller falls back
|
|
13
|
+
* to normal polling on `failed`.
|
|
14
|
+
*
|
|
15
|
+
* @returns `stop`, which ends it without reporting, and `fail`
|
|
16
|
+
* @category Utilities - Events
|
|
17
|
+
*/
|
|
18
|
+
export declare function startEntitySubscription({ client, eventTypes, entityId, refetch, onStatus, connectTimeoutMs, refetchDelaysMs, }: {
|
|
19
|
+
client: EventStreamClient;
|
|
20
|
+
eventTypes: readonly string[];
|
|
21
|
+
entityId: string;
|
|
22
|
+
refetch: () => Promise<void>;
|
|
23
|
+
onStatus: (status: SubscriptionStatus) => void;
|
|
24
|
+
connectTimeoutMs?: number;
|
|
25
|
+
refetchDelaysMs?: readonly number[];
|
|
26
|
+
}): {
|
|
27
|
+
stop: () => void;
|
|
28
|
+
fail: (reason: unknown) => void;
|
|
29
|
+
};
|
|
30
|
+
//# sourceMappingURL=entitySubscription.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"entitySubscription.d.ts","sourceRoot":"","sources":["../../../utils/events/entitySubscription.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,kBAAkB,EACxB,MAAM,cAAc,CAAA;AAGrB,OAAO,EAGL,KAAK,iBAAiB,EACvB,MAAM,sBAAsB,CAAA;AAQ7B;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,uBAAuB,CAAC,EACtC,MAAM,EACN,UAAU,EACV,QAAQ,EACR,OAAO,EACP,QAAQ,EACR,gBAAkD,EAClD,eAAyC,GAC1C,EAAE;IACD,MAAM,EAAE,iBAAiB,CAAA;IACzB,UAAU,EAAE,SAAS,MAAM,EAAE,CAAA;IAC7B,QAAQ,EAAE,MAAM,CAAA;IAChB,OAAO,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAA;IAC5B,QAAQ,EAAE,CAAC,MAAM,EAAE,kBAAkB,KAAK,IAAI,CAAA;IAC9C,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB,eAAe,CAAC,EAAE,SAAS,MAAM,EAAE,CAAA;CACpC,GAAG;IAAE,IAAI,EAAE,MAAM,IAAI,CAAC;IAAC,IAAI,EAAE,CAAC,MAAM,EAAE,OAAO,KAAK,IAAI,CAAA;CAAE,CA2ExD"}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { SUBSCRIPTION_CONNECT_TIMEOUT_MS, } from '../constants.js';
|
|
2
|
+
import { createLogger } from '../logger.js';
|
|
3
|
+
import { entityEventMatcher, isEventForEntity } from './entityEvents.js';
|
|
4
|
+
import { createGraphqlEventStream, deriveEventFilters, } from './graphqlEventStream.js';
|
|
5
|
+
import { createEventRefetchScheduler, EVENT_REFETCH_DELAYS_MS, } from './refetchScheduler.js';
|
|
6
|
+
const log = createLogger();
|
|
7
|
+
/**
|
|
8
|
+
* Keep one entity up to date from a GraphQL event subscription: refetch when
|
|
9
|
+
* an event about the entity arrives (a few times, for indexer lag), and once
|
|
10
|
+
* after every reconnect to backfill what was missed.
|
|
11
|
+
*
|
|
12
|
+
* There is one stream per world package. Reports `connecting`, then `live`
|
|
13
|
+
* once every stream has connected. Reports `failed`, once, on a stream error,
|
|
14
|
+
* when `fail` is called (e.g. the endpoint serves no subscriptions), or when
|
|
15
|
+
* any stream has not connected within `connectTimeoutMs`; it then stops for
|
|
16
|
+
* good, so a broken endpoint is never retried in a loop. The caller falls back
|
|
17
|
+
* to normal polling on `failed`.
|
|
18
|
+
*
|
|
19
|
+
* @returns `stop`, which ends it without reporting, and `fail`
|
|
20
|
+
* @category Utilities - Events
|
|
21
|
+
*/
|
|
22
|
+
export function startEntitySubscription({ client, eventTypes, entityId, refetch, onStatus, connectTimeoutMs = SUBSCRIPTION_CONNECT_TIMEOUT_MS, refetchDelaysMs = EVENT_REFETCH_DELAYS_MS, }) {
|
|
23
|
+
const abort = new AbortController();
|
|
24
|
+
let done = false;
|
|
25
|
+
let live = false;
|
|
26
|
+
const expected = deriveEventFilters(eventTypes).map((filter) => filter.type);
|
|
27
|
+
const connected = new Set();
|
|
28
|
+
const onRefetchError = (error) => log.warn('[DappKit] Entity refetch after an event failed', error);
|
|
29
|
+
const scheduled = createEventRefetchScheduler(refetch, refetchDelaysMs, onRefetchError);
|
|
30
|
+
const end = () => {
|
|
31
|
+
done = true;
|
|
32
|
+
clearTimeout(timeout);
|
|
33
|
+
scheduled.cancel();
|
|
34
|
+
abort.abort();
|
|
35
|
+
};
|
|
36
|
+
const fail = (reason) => {
|
|
37
|
+
if (done)
|
|
38
|
+
return;
|
|
39
|
+
end();
|
|
40
|
+
log.warn('[DappKit] Entity subscription failed; falling back to polling', reason);
|
|
41
|
+
onStatus('failed');
|
|
42
|
+
};
|
|
43
|
+
const timeout = setTimeout(() => {
|
|
44
|
+
if (live)
|
|
45
|
+
return;
|
|
46
|
+
const missing = expected.filter((filter) => !connected.has(filter));
|
|
47
|
+
fail(new Error(`No connection within ${connectTimeoutMs} ms for ${missing.join(', ')}`));
|
|
48
|
+
}, connectTimeoutMs);
|
|
49
|
+
onStatus('connecting');
|
|
50
|
+
createGraphqlEventStream({
|
|
51
|
+
client,
|
|
52
|
+
eventTypes,
|
|
53
|
+
isTracked: entityEventMatcher(eventTypes),
|
|
54
|
+
signal: abort.signal,
|
|
55
|
+
onConnected: (_reconnected, filter) => {
|
|
56
|
+
if (done || live)
|
|
57
|
+
return;
|
|
58
|
+
connected.add(filter);
|
|
59
|
+
// Polling slows to the backstop only once every package is covered
|
|
60
|
+
if (expected.some((type) => !connected.has(type)))
|
|
61
|
+
return;
|
|
62
|
+
live = true;
|
|
63
|
+
clearTimeout(timeout);
|
|
64
|
+
log.info('[DappKit] Entity subscription live', { entityId });
|
|
65
|
+
onStatus('live');
|
|
66
|
+
},
|
|
67
|
+
onEvents: (events) => {
|
|
68
|
+
if (events.some((event) => isEventForEntity(event, entityId))) {
|
|
69
|
+
scheduled();
|
|
70
|
+
}
|
|
71
|
+
},
|
|
72
|
+
onGap: () => {
|
|
73
|
+
refetch().catch(onRefetchError);
|
|
74
|
+
},
|
|
75
|
+
onError: fail,
|
|
76
|
+
});
|
|
77
|
+
return {
|
|
78
|
+
stop: () => {
|
|
79
|
+
if (!done)
|
|
80
|
+
end();
|
|
81
|
+
},
|
|
82
|
+
fail,
|
|
83
|
+
};
|
|
84
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import type { SuiEvent } from '@mysten/sui/jsonRpc';
|
|
2
|
+
/**
|
|
3
|
+
* Whether an event type is one the consumer tracks. Defaults to an exact
|
|
4
|
+
* match against `eventTypes`; pass one to match more loosely, e.g. by
|
|
5
|
+
* `module::Struct` across package upgrades.
|
|
6
|
+
*/
|
|
7
|
+
export type EventTypeMatcher = (type: string) => boolean;
|
|
8
|
+
/**
|
|
9
|
+
* The GraphQL subscription document that feeds optimistic updates.
|
|
10
|
+
*
|
|
11
|
+
* Matches Sui's `Subscription.events(filter: EventFilter): EventEdge!` — each
|
|
12
|
+
* emission is a single edge. The decoded Move fields live under
|
|
13
|
+
* `node.contents.json`, the fully-qualified event type under
|
|
14
|
+
* `node.contents.type.repr`, and the event identity is the transaction digest
|
|
15
|
+
* plus `sequenceNumber`.
|
|
16
|
+
*
|
|
17
|
+
* `EventFilter.type` is a single string (prefix match on package /
|
|
18
|
+
* package::module / full type), so we open one subscription per package (see
|
|
19
|
+
* {@link deriveEventFilters}) and still narrow to exact types client-side.
|
|
20
|
+
*/
|
|
21
|
+
export declare const ASSEMBLY_EVENTS_SUBSCRIPTION = "\n subscription AssemblyEvents($filter: EventFilter) {\n events(filter: $filter) {\n cursor\n node {\n sequenceNumber\n transaction {\n digest\n }\n contents {\n type {\n repr\n }\n json\n }\n }\n }\n }\n";
|
|
22
|
+
export type EventUnsubscribe = () => Promise<void>;
|
|
23
|
+
export type StreamEvent = Pick<SuiEvent, 'id' | 'type' | 'parsedJson'>;
|
|
24
|
+
export type StreamEventBatchHandler = (events: StreamEvent[]) => void;
|
|
25
|
+
/**
|
|
26
|
+
* Called when a subscription reconnects after an interruption, so the consumer
|
|
27
|
+
* can fire a confirming refetch and backfill anything missed while
|
|
28
|
+
* disconnected. This is the GraphQL analogue of the gRPC checkpoint-gap signal.
|
|
29
|
+
*/
|
|
30
|
+
export type StreamGapHandler = () => void;
|
|
31
|
+
/** Minimal sink shape (a subset of the `graphql-sse` Sink). */
|
|
32
|
+
export type EventStreamSink = {
|
|
33
|
+
next: (value: unknown) => void;
|
|
34
|
+
error: (error: unknown) => void;
|
|
35
|
+
complete: () => void;
|
|
36
|
+
};
|
|
37
|
+
/**
|
|
38
|
+
* Transport abstraction so the stream is testable without a real SSE
|
|
39
|
+
* connection. Production wiring (see eventRefresh.ts) adapts a `graphql-sse`
|
|
40
|
+
* client to this.
|
|
41
|
+
*/
|
|
42
|
+
export type EventStreamClient = {
|
|
43
|
+
/**
|
|
44
|
+
* Open a subscription; returns a disposer that ends it. `onConnected` fires
|
|
45
|
+
* on every (re)connect with `reconnected` indicating whether it followed a
|
|
46
|
+
* broken connection.
|
|
47
|
+
*/
|
|
48
|
+
subscribe: (payload: {
|
|
49
|
+
query: string;
|
|
50
|
+
variables: Record<string, unknown>;
|
|
51
|
+
}, sink: EventStreamSink, onConnected?: (reconnected: boolean) => void) => () => void;
|
|
52
|
+
};
|
|
53
|
+
/**
|
|
54
|
+
* Distinct server-side filters to subscribe with, one per package referenced by
|
|
55
|
+
* `eventTypes`. `EventFilter.type` prefix-matches, so a bare package id catches
|
|
56
|
+
* every module (inventory/fuel/status) under it in a single subscription.
|
|
57
|
+
* Exported for unit testing.
|
|
58
|
+
*/
|
|
59
|
+
export declare function deriveEventFilters(eventTypes: readonly string[]): {
|
|
60
|
+
type: string;
|
|
61
|
+
}[];
|
|
62
|
+
/**
|
|
63
|
+
* Map a raw subscription emission to the `StreamEvent` batch the consumer
|
|
64
|
+
* expects. Exported for unit testing. Events without a decodable type or
|
|
65
|
+
* `parsedJson`, or whose type is not in `eventTypes`, are dropped (the server
|
|
66
|
+
* filters by package, so this narrows to the exact tracked types).
|
|
67
|
+
*/
|
|
68
|
+
export declare function extractEventsFromSubscription(data: unknown, eventTypes: readonly string[], isTracked?: EventTypeMatcher): StreamEvent[];
|
|
69
|
+
/**
|
|
70
|
+
* Subscribe to assembly Move events over the GraphQL SSE subscription and
|
|
71
|
+
* deliver them in batches to `onEvents`. Mirrors the contract the gRPC
|
|
72
|
+
* checkpoint stream provided: deduped `{ id, type, parsedJson }` events, plus
|
|
73
|
+
* an `onGap` signal on reconnect so the consumer can fire a confirming refetch.
|
|
74
|
+
*
|
|
75
|
+
* Opens one subscription per package (Sui's `EventFilter.type` takes a single
|
|
76
|
+
* value); all subscriptions share one dedupe set and one `onEvents` sink.
|
|
77
|
+
*/
|
|
78
|
+
export declare function createGraphqlEventStream({ client, eventTypes, isTracked, onConnected: onEachConnect, onError, onEvents, onGap, signal, }: {
|
|
79
|
+
client: EventStreamClient;
|
|
80
|
+
eventTypes: readonly string[];
|
|
81
|
+
/** Which delivered types to keep; defaults to exact `eventTypes` matches */
|
|
82
|
+
isTracked?: EventTypeMatcher;
|
|
83
|
+
/** Called on every (re)connect of any of the subscriptions, with that subscription's package filter */
|
|
84
|
+
onConnected?: (reconnected: boolean, filter: string) => void;
|
|
85
|
+
onError?: (error: unknown) => void;
|
|
86
|
+
onEvents?: StreamEventBatchHandler;
|
|
87
|
+
onGap?: StreamGapHandler;
|
|
88
|
+
signal?: AbortSignal;
|
|
89
|
+
}): EventUnsubscribe;
|
|
90
|
+
//# sourceMappingURL=graphqlEventStream.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"graphqlEventStream.d.ts","sourceRoot":"","sources":["../../../utils/events/graphqlEventStream.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAA;AAWnD;;;;GAIG;AACH,MAAM,MAAM,gBAAgB,GAAG,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAA;AAOxD;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,4BAA4B,0TAkBxC,CAAA;AAID,MAAM,MAAM,gBAAgB,GAAG,MAAM,OAAO,CAAC,IAAI,CAAC,CAAA;AAClD,MAAM,MAAM,WAAW,GAAG,IAAI,CAAC,QAAQ,EAAE,IAAI,GAAG,MAAM,GAAG,YAAY,CAAC,CAAA;AACtE,MAAM,MAAM,uBAAuB,GAAG,CAAC,MAAM,EAAE,WAAW,EAAE,KAAK,IAAI,CAAA;AACrE;;;;GAIG;AACH,MAAM,MAAM,gBAAgB,GAAG,MAAM,IAAI,CAAA;AAEzC,+DAA+D;AAC/D,MAAM,MAAM,eAAe,GAAG;IAC5B,IAAI,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAA;IAC9B,KAAK,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAA;IAC/B,QAAQ,EAAE,MAAM,IAAI,CAAA;CACrB,CAAA;AAED;;;;GAIG;AACH,MAAM,MAAM,iBAAiB,GAAG;IAC9B;;;;OAIG;IACH,SAAS,EAAE,CACT,OAAO,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;KAAE,EAC9D,IAAI,EAAE,eAAe,EACrB,WAAW,CAAC,EAAE,CAAC,WAAW,EAAE,OAAO,KAAK,IAAI,KACzC,MAAM,IAAI,CAAA;CAChB,CAAA;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAChC,UAAU,EAAE,SAAS,MAAM,EAAE,GAC5B;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,EAAE,CAOpB;AAiDD;;;;;GAKG;AACH,wBAAgB,6BAA6B,CAC3C,IAAI,EAAE,OAAO,EACb,UAAU,EAAE,SAAS,MAAM,EAAE,EAC7B,SAAS,GAAE,gBAA2C,GACrD,WAAW,EAAE,CAOf;AAoBD;;;;;;;;GAQG;AACH,wBAAgB,wBAAwB,CAAC,EACvC,MAAM,EACN,UAAU,EACV,SAAoC,EACpC,WAAW,EAAE,aAAa,EAC1B,OAAO,EACP,QAAQ,EACR,KAAK,EACL,MAAM,GACP,EAAE;IACD,MAAM,EAAE,iBAAiB,CAAA;IACzB,UAAU,EAAE,SAAS,MAAM,EAAE,CAAA;IAC7B,4EAA4E;IAC5E,SAAS,CAAC,EAAE,gBAAgB,CAAA;IAC5B,uGAAuG;IACvG,WAAW,CAAC,EAAE,CAAC,WAAW,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,KAAK,IAAI,CAAA;IAC5D,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAA;IAClC,QAAQ,CAAC,EAAE,uBAAuB,CAAA;IAClC,KAAK,CAAC,EAAE,gBAAgB,CAAA;IACxB,MAAM,CAAC,EAAE,WAAW,CAAA;CACrB,GAAG,gBAAgB,CA2DnB"}
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import { createLogger } from '../logger.js';
|
|
2
|
+
// Bound the dedupe set so long-lived subscriptions don't grow it unbounded.
|
|
3
|
+
const EVENT_STREAM_MAX_SEEN_EVENTS = 5000;
|
|
4
|
+
const log = createLogger();
|
|
5
|
+
const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
6
|
+
const exactMatcher = (eventTypes) => (type) => eventTypes.includes(type);
|
|
7
|
+
/**
|
|
8
|
+
* The GraphQL subscription document that feeds optimistic updates.
|
|
9
|
+
*
|
|
10
|
+
* Matches Sui's `Subscription.events(filter: EventFilter): EventEdge!` — each
|
|
11
|
+
* emission is a single edge. The decoded Move fields live under
|
|
12
|
+
* `node.contents.json`, the fully-qualified event type under
|
|
13
|
+
* `node.contents.type.repr`, and the event identity is the transaction digest
|
|
14
|
+
* plus `sequenceNumber`.
|
|
15
|
+
*
|
|
16
|
+
* `EventFilter.type` is a single string (prefix match on package /
|
|
17
|
+
* package::module / full type), so we open one subscription per package (see
|
|
18
|
+
* {@link deriveEventFilters}) and still narrow to exact types client-side.
|
|
19
|
+
*/
|
|
20
|
+
export const ASSEMBLY_EVENTS_SUBSCRIPTION = `
|
|
21
|
+
subscription AssemblyEvents($filter: EventFilter) {
|
|
22
|
+
events(filter: $filter) {
|
|
23
|
+
cursor
|
|
24
|
+
node {
|
|
25
|
+
sequenceNumber
|
|
26
|
+
transaction {
|
|
27
|
+
digest
|
|
28
|
+
}
|
|
29
|
+
contents {
|
|
30
|
+
type {
|
|
31
|
+
repr
|
|
32
|
+
}
|
|
33
|
+
json
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
`;
|
|
39
|
+
/**
|
|
40
|
+
* Distinct server-side filters to subscribe with, one per package referenced by
|
|
41
|
+
* `eventTypes`. `EventFilter.type` prefix-matches, so a bare package id catches
|
|
42
|
+
* every module (inventory/fuel/status) under it in a single subscription.
|
|
43
|
+
* Exported for unit testing.
|
|
44
|
+
*/
|
|
45
|
+
export function deriveEventFilters(eventTypes) {
|
|
46
|
+
const packages = new Set();
|
|
47
|
+
for (const eventType of eventTypes) {
|
|
48
|
+
const packageId = eventType.split('::')[0];
|
|
49
|
+
if (packageId)
|
|
50
|
+
packages.add(packageId);
|
|
51
|
+
}
|
|
52
|
+
return [...packages].map((type) => ({ type }));
|
|
53
|
+
}
|
|
54
|
+
function parseSequenceNumber(value) {
|
|
55
|
+
if (typeof value === 'string')
|
|
56
|
+
return value;
|
|
57
|
+
if (typeof value === 'number')
|
|
58
|
+
return String(value);
|
|
59
|
+
return '0';
|
|
60
|
+
}
|
|
61
|
+
function edgeToStreamEvent(edge) {
|
|
62
|
+
if (!isRecord(edge))
|
|
63
|
+
return null;
|
|
64
|
+
const node = isRecord(edge['node']) ? edge['node'] : edge;
|
|
65
|
+
const contents = isRecord(node['contents']) ? node['contents'] : undefined;
|
|
66
|
+
const parsedJson = contents?.['json'];
|
|
67
|
+
const type = isRecord(contents?.['type'])
|
|
68
|
+
? contents['type']['repr']
|
|
69
|
+
: undefined;
|
|
70
|
+
if (typeof type !== 'string' || !isRecord(parsedJson))
|
|
71
|
+
return null;
|
|
72
|
+
const transaction = isRecord(node['transaction'])
|
|
73
|
+
? node['transaction']
|
|
74
|
+
: undefined;
|
|
75
|
+
const digest = transaction?.['digest'];
|
|
76
|
+
const cursor = edge['cursor'];
|
|
77
|
+
// Prefer the tx digest for the dedupe id; fall back to the edge cursor.
|
|
78
|
+
const txDigest = typeof digest === 'string'
|
|
79
|
+
? digest
|
|
80
|
+
: typeof cursor === 'string'
|
|
81
|
+
? cursor
|
|
82
|
+
: '';
|
|
83
|
+
return {
|
|
84
|
+
id: { txDigest, eventSeq: parseSequenceNumber(node['sequenceNumber']) },
|
|
85
|
+
type,
|
|
86
|
+
parsedJson,
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
function toEdgeArray(data) {
|
|
90
|
+
// graphql-sse delivers `{ data: { events: <EventEdge> } }`, one edge per
|
|
91
|
+
// message. Tolerate a pre-unwrapped payload or a list of edges.
|
|
92
|
+
const root = isRecord(data) && 'data' in data ? data['data'] : data;
|
|
93
|
+
if (!isRecord(root))
|
|
94
|
+
return [];
|
|
95
|
+
const events = root['events'];
|
|
96
|
+
if (Array.isArray(events))
|
|
97
|
+
return events;
|
|
98
|
+
if (events !== undefined && events !== null)
|
|
99
|
+
return [events];
|
|
100
|
+
return [];
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Map a raw subscription emission to the `StreamEvent` batch the consumer
|
|
104
|
+
* expects. Exported for unit testing. Events without a decodable type or
|
|
105
|
+
* `parsedJson`, or whose type is not in `eventTypes`, are dropped (the server
|
|
106
|
+
* filters by package, so this narrows to the exact tracked types).
|
|
107
|
+
*/
|
|
108
|
+
export function extractEventsFromSubscription(data, eventTypes, isTracked = exactMatcher(eventTypes)) {
|
|
109
|
+
return toEdgeArray(data).flatMap((edge) => {
|
|
110
|
+
const event = edgeToStreamEvent(edge);
|
|
111
|
+
if (!event)
|
|
112
|
+
return [];
|
|
113
|
+
if (!isTracked(event.type))
|
|
114
|
+
return [];
|
|
115
|
+
return [event];
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
function collectUnseenEvents(events, seenEventIds) {
|
|
119
|
+
return events.filter((event) => {
|
|
120
|
+
const eventId = `${event.id.txDigest}:${event.id.eventSeq}`;
|
|
121
|
+
if (seenEventIds.has(eventId))
|
|
122
|
+
return false;
|
|
123
|
+
seenEventIds.add(eventId);
|
|
124
|
+
// Evict oldest ids (insertion order) once the set exceeds its cap.
|
|
125
|
+
while (seenEventIds.size > EVENT_STREAM_MAX_SEEN_EVENTS) {
|
|
126
|
+
const oldest = seenEventIds.values().next().value;
|
|
127
|
+
if (oldest === undefined)
|
|
128
|
+
break;
|
|
129
|
+
seenEventIds.delete(oldest);
|
|
130
|
+
}
|
|
131
|
+
return true;
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Subscribe to assembly Move events over the GraphQL SSE subscription and
|
|
136
|
+
* deliver them in batches to `onEvents`. Mirrors the contract the gRPC
|
|
137
|
+
* checkpoint stream provided: deduped `{ id, type, parsedJson }` events, plus
|
|
138
|
+
* an `onGap` signal on reconnect so the consumer can fire a confirming refetch.
|
|
139
|
+
*
|
|
140
|
+
* Opens one subscription per package (Sui's `EventFilter.type` takes a single
|
|
141
|
+
* value); all subscriptions share one dedupe set and one `onEvents` sink.
|
|
142
|
+
*/
|
|
143
|
+
export function createGraphqlEventStream({ client, eventTypes, isTracked = exactMatcher(eventTypes), onConnected: onEachConnect, onError, onEvents, onGap, signal, }) {
|
|
144
|
+
const seenEventIds = new Set();
|
|
145
|
+
let stopped = false;
|
|
146
|
+
const disposers = [];
|
|
147
|
+
const sink = {
|
|
148
|
+
next: (value) => {
|
|
149
|
+
if (stopped)
|
|
150
|
+
return;
|
|
151
|
+
const parsed = extractEventsFromSubscription(value, eventTypes, isTracked);
|
|
152
|
+
const events = collectUnseenEvents(parsed, seenEventIds);
|
|
153
|
+
// Gated by VITE_LOG_LEVEL / Vite MODE (dev defaults to `debug`).
|
|
154
|
+
// `raw` is the untouched subscription payload, `parsed` is after
|
|
155
|
+
// type-mapping/filtering, `delivered` is after dedupe.
|
|
156
|
+
log.debug('[DappKit] GraphQL subscription message', {
|
|
157
|
+
raw: value,
|
|
158
|
+
parsed,
|
|
159
|
+
delivered: events,
|
|
160
|
+
});
|
|
161
|
+
if (events.length > 0)
|
|
162
|
+
onEvents?.(events);
|
|
163
|
+
},
|
|
164
|
+
error: (error) => {
|
|
165
|
+
if (stopped || signal?.aborted)
|
|
166
|
+
return;
|
|
167
|
+
onError?.(error);
|
|
168
|
+
},
|
|
169
|
+
complete: () => {
|
|
170
|
+
log.debug('[DappKit] GraphQL event subscription completed');
|
|
171
|
+
},
|
|
172
|
+
};
|
|
173
|
+
const onConnected = (filter) => (reconnected) => {
|
|
174
|
+
if (stopped)
|
|
175
|
+
return;
|
|
176
|
+
onEachConnect?.(reconnected, filter);
|
|
177
|
+
// Only reconnects can have missed events; the initial connect needs no
|
|
178
|
+
// backfill because the provider already did its initial fetch.
|
|
179
|
+
if (reconnected)
|
|
180
|
+
onGap?.();
|
|
181
|
+
};
|
|
182
|
+
if (!stopped && !signal?.aborted) {
|
|
183
|
+
for (const filter of deriveEventFilters(eventTypes)) {
|
|
184
|
+
const dispose = client.subscribe({ query: ASSEMBLY_EVENTS_SUBSCRIPTION, variables: { filter } }, sink, onConnected(filter.type));
|
|
185
|
+
disposers.push(dispose);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
const stop = async () => {
|
|
189
|
+
stopped = true;
|
|
190
|
+
for (const dispose of disposers)
|
|
191
|
+
dispose();
|
|
192
|
+
disposers.length = 0;
|
|
193
|
+
};
|
|
194
|
+
signal?.addEventListener('abort', () => {
|
|
195
|
+
void stop();
|
|
196
|
+
});
|
|
197
|
+
return stop;
|
|
198
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Delays before each refetch after an event: the first, then the confirmations
|
|
3
|
+
* that let the indexer behind the query endpoint catch up.
|
|
4
|
+
*/
|
|
5
|
+
export declare const EVENT_REFETCH_DELAYS_MS: readonly [250, 1500, 3500];
|
|
6
|
+
/**
|
|
7
|
+
* A refetch scheduled after an event. Calling it again never postpones a
|
|
8
|
+
* pending first refetch; it re-arms only the confirmations. `cancel` drops all.
|
|
9
|
+
*/
|
|
10
|
+
export type ScheduledRefetch = (() => void) & {
|
|
11
|
+
cancel: () => void;
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Refetch a few times after an event: the event can arrive before the query
|
|
15
|
+
* endpoint's indexer has the transaction, so one immediate refetch could still
|
|
16
|
+
* read the old version.
|
|
17
|
+
*
|
|
18
|
+
* The first refetch is bounded: it runs `delaysMs[0]` after the event that
|
|
19
|
+
* scheduled it, and later events while it is pending leave it alone, so a
|
|
20
|
+
* steady stream of events still refetches about every `delaysMs[0]`. The
|
|
21
|
+
* confirmations (`delaysMs[1…]`) follow the latest event: each event cancels
|
|
22
|
+
* and re-arms them, so they run once a burst has ended.
|
|
23
|
+
*
|
|
24
|
+
* @param refetch - The refetch to run
|
|
25
|
+
* @param delaysMs - The first refetch's delay, then each confirmation's, in ms
|
|
26
|
+
* @param onError - Called when a refetch rejects
|
|
27
|
+
* @category Utilities - Events
|
|
28
|
+
*/
|
|
29
|
+
export declare function createEventRefetchScheduler(refetch: () => Promise<void>, delaysMs?: readonly number[], onError?: (error: unknown) => void): ScheduledRefetch;
|
|
30
|
+
//# sourceMappingURL=refetchScheduler.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"refetchScheduler.d.ts","sourceRoot":"","sources":["../../../utils/events/refetchScheduler.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,eAAO,MAAM,uBAAuB,YAAI,GAAG,EAAE,IAAI,EAAE,IAAI,CAAU,CAAA;AAEjE;;;GAGG;AACH,MAAM,MAAM,gBAAgB,GAAG,CAAC,MAAM,IAAI,CAAC,GAAG;IAAE,MAAM,EAAE,MAAM,IAAI,CAAA;CAAE,CAAA;AAEpE;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,2BAA2B,CACzC,OAAO,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,EAC5B,QAAQ,GAAE,SAAS,MAAM,EAA4B,EACrD,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,GACjC,gBAAgB,CAuClB"}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Delays before each refetch after an event: the first, then the confirmations
|
|
3
|
+
* that let the indexer behind the query endpoint catch up.
|
|
4
|
+
*/
|
|
5
|
+
export const EVENT_REFETCH_DELAYS_MS = [250, 1500, 3500];
|
|
6
|
+
/**
|
|
7
|
+
* Refetch a few times after an event: the event can arrive before the query
|
|
8
|
+
* endpoint's indexer has the transaction, so one immediate refetch could still
|
|
9
|
+
* read the old version.
|
|
10
|
+
*
|
|
11
|
+
* The first refetch is bounded: it runs `delaysMs[0]` after the event that
|
|
12
|
+
* scheduled it, and later events while it is pending leave it alone, so a
|
|
13
|
+
* steady stream of events still refetches about every `delaysMs[0]`. The
|
|
14
|
+
* confirmations (`delaysMs[1…]`) follow the latest event: each event cancels
|
|
15
|
+
* and re-arms them, so they run once a burst has ended.
|
|
16
|
+
*
|
|
17
|
+
* @param refetch - The refetch to run
|
|
18
|
+
* @param delaysMs - The first refetch's delay, then each confirmation's, in ms
|
|
19
|
+
* @param onError - Called when a refetch rejects
|
|
20
|
+
* @category Utilities - Events
|
|
21
|
+
*/
|
|
22
|
+
export function createEventRefetchScheduler(refetch, delaysMs = EVENT_REFETCH_DELAYS_MS, onError) {
|
|
23
|
+
const [firstDelayMs, ...confirmDelaysMs] = delaysMs;
|
|
24
|
+
let first = null;
|
|
25
|
+
let confirms = [];
|
|
26
|
+
const run = () => {
|
|
27
|
+
refetch().catch((error) => onError?.(error));
|
|
28
|
+
};
|
|
29
|
+
const cancelConfirms = () => {
|
|
30
|
+
for (const timeout of confirms)
|
|
31
|
+
clearTimeout(timeout);
|
|
32
|
+
confirms = [];
|
|
33
|
+
};
|
|
34
|
+
const scheduledRefetch = () => {
|
|
35
|
+
if (first === null && firstDelayMs !== undefined) {
|
|
36
|
+
first = setTimeout(() => {
|
|
37
|
+
first = null;
|
|
38
|
+
run();
|
|
39
|
+
}, firstDelayMs);
|
|
40
|
+
}
|
|
41
|
+
cancelConfirms();
|
|
42
|
+
confirms = confirmDelaysMs.map((delayMs) => {
|
|
43
|
+
const timeoutId = setTimeout(() => {
|
|
44
|
+
confirms = confirms.filter((timeout) => timeout !== timeoutId);
|
|
45
|
+
run();
|
|
46
|
+
}, delayMs);
|
|
47
|
+
return timeoutId;
|
|
48
|
+
});
|
|
49
|
+
};
|
|
50
|
+
scheduledRefetch.cancel = () => {
|
|
51
|
+
if (first !== null)
|
|
52
|
+
clearTimeout(first);
|
|
53
|
+
first = null;
|
|
54
|
+
cancelConfirms();
|
|
55
|
+
};
|
|
56
|
+
return scheduledRefetch;
|
|
57
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { EventStreamClient } from './graphqlEventStream.js';
|
|
2
|
+
/**
|
|
3
|
+
* The endpoint answered, but not with an event stream: it does not serve
|
|
4
|
+
* GraphQL subscriptions (a localnet replies `200 application/json` with
|
|
5
|
+
* "Schema is not configured for subscriptions"). Not worth retrying.
|
|
6
|
+
*
|
|
7
|
+
* @category Utilities - Events
|
|
8
|
+
*/
|
|
9
|
+
export declare class SubscriptionsUnsupportedError extends Error {
|
|
10
|
+
name: string;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Pass an SSE response through, or throw {@link SubscriptionsUnsupportedError}
|
|
14
|
+
* when the URL serves no subscriptions: a 404, 405 or 501, or a successful
|
|
15
|
+
* response that is not `text/event-stream`. Other error statuses pass through
|
|
16
|
+
* for `graphql-sse` to retry as network errors.
|
|
17
|
+
*
|
|
18
|
+
* @category Utilities - Events
|
|
19
|
+
*/
|
|
20
|
+
export declare function assertEventStream(res: Response): Promise<Response>;
|
|
21
|
+
/**
|
|
22
|
+
* Adapt a `graphql-sse` client to the transport-agnostic EventStreamClient the
|
|
23
|
+
* stream consumes. Uses "distinct connections" mode (one SSE request per
|
|
24
|
+
* subscription); the per-subscription `connected(reconnected)` listener drives
|
|
25
|
+
* the gap signal. SSE runs over `fetch`, so X-Client-ID is a real header.
|
|
26
|
+
*
|
|
27
|
+
* `graphql-sse` reports a connect as soon as the response arrives, before
|
|
28
|
+
* reading it, and retries network errors. `onUnsupported` fires as soon as a
|
|
29
|
+
* response turns out not to be an event stream, so the caller can stop before
|
|
30
|
+
* any retries.
|
|
31
|
+
*
|
|
32
|
+
* @category Utilities - Events
|
|
33
|
+
*/
|
|
34
|
+
export declare function createGraphqlSseEventStreamClient({ url, authToken, onUnsupported, fetchFn, }: {
|
|
35
|
+
url: string;
|
|
36
|
+
authToken?: string | undefined;
|
|
37
|
+
onUnsupported?: (error: SubscriptionsUnsupportedError) => void;
|
|
38
|
+
fetchFn?: typeof fetch;
|
|
39
|
+
}): EventStreamClient & {
|
|
40
|
+
dispose: () => void;
|
|
41
|
+
};
|
|
42
|
+
//# sourceMappingURL=sseClient.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sseClient.d.ts","sourceRoot":"","sources":["../../../utils/events/sseClient.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAA;AAE7D;;;;;;GAMG;AACH,qBAAa,6BAA8B,SAAQ,KAAK;IAC7C,IAAI,SAAkC;CAChD;AAmBD;;;;;;;GAOG;AACH,wBAAsB,iBAAiB,CAAC,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,CAYxE;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,iCAAiC,CAAC,EAChD,GAAG,EACH,SAAS,EACT,aAAa,EACb,OAA0B,GAC3B,EAAE;IACD,GAAG,EAAE,MAAM,CAAA;IACX,SAAS,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IAC9B,aAAa,CAAC,EAAE,CAAC,KAAK,EAAE,6BAA6B,KAAK,IAAI,CAAA;IAC9D,OAAO,CAAC,EAAE,OAAO,KAAK,CAAA;CACvB,GAAG,iBAAiB,GAAG;IAAE,OAAO,EAAE,MAAM,IAAI,CAAA;CAAE,CA6B9C"}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { createClient } from 'graphql-sse';
|
|
2
|
+
import { GRAPHQL_CLIENT_ID } from '../constants.js';
|
|
3
|
+
/**
|
|
4
|
+
* The endpoint answered, but not with an event stream: it does not serve
|
|
5
|
+
* GraphQL subscriptions (a localnet replies `200 application/json` with
|
|
6
|
+
* "Schema is not configured for subscriptions"). Not worth retrying.
|
|
7
|
+
*
|
|
8
|
+
* @category Utilities - Events
|
|
9
|
+
*/
|
|
10
|
+
export class SubscriptionsUnsupportedError extends Error {
|
|
11
|
+
constructor() {
|
|
12
|
+
super(...arguments);
|
|
13
|
+
Object.defineProperty(this, "name", {
|
|
14
|
+
enumerable: true,
|
|
15
|
+
configurable: true,
|
|
16
|
+
writable: true,
|
|
17
|
+
value: 'SubscriptionsUnsupportedError'
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Statuses that mean the URL serves no subscriptions at all, rather than a
|
|
23
|
+
* passing failure (a localnet answers 404 "Subscriptions are not enabled on
|
|
24
|
+
* this instance" on `/graphql/subscriptions`).
|
|
25
|
+
*/
|
|
26
|
+
const UNSUPPORTED_STATUSES = new Set([404, 405, 501]);
|
|
27
|
+
async function reason(res) {
|
|
28
|
+
try {
|
|
29
|
+
const text = (await res.text()).trim().slice(0, 200);
|
|
30
|
+
return text ? `: ${text}` : '';
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
// The reason is a nicety; the status or content type already decides
|
|
34
|
+
return '';
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Pass an SSE response through, or throw {@link SubscriptionsUnsupportedError}
|
|
39
|
+
* when the URL serves no subscriptions: a 404, 405 or 501, or a successful
|
|
40
|
+
* response that is not `text/event-stream`. Other error statuses pass through
|
|
41
|
+
* for `graphql-sse` to retry as network errors.
|
|
42
|
+
*
|
|
43
|
+
* @category Utilities - Events
|
|
44
|
+
*/
|
|
45
|
+
export async function assertEventStream(res) {
|
|
46
|
+
if (UNSUPPORTED_STATUSES.has(res.status)) {
|
|
47
|
+
throw new SubscriptionsUnsupportedError(`Subscription endpoint answered ${res.status}${await reason(res)}`);
|
|
48
|
+
}
|
|
49
|
+
if (!res.ok)
|
|
50
|
+
return res;
|
|
51
|
+
const type = res.headers.get('content-type') ?? '';
|
|
52
|
+
if (type.includes('text/event-stream'))
|
|
53
|
+
return res;
|
|
54
|
+
throw new SubscriptionsUnsupportedError(`Expected an event stream, got ${type || 'no content type'}${await reason(res)}`);
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Adapt a `graphql-sse` client to the transport-agnostic EventStreamClient the
|
|
58
|
+
* stream consumes. Uses "distinct connections" mode (one SSE request per
|
|
59
|
+
* subscription); the per-subscription `connected(reconnected)` listener drives
|
|
60
|
+
* the gap signal. SSE runs over `fetch`, so X-Client-ID is a real header.
|
|
61
|
+
*
|
|
62
|
+
* `graphql-sse` reports a connect as soon as the response arrives, before
|
|
63
|
+
* reading it, and retries network errors. `onUnsupported` fires as soon as a
|
|
64
|
+
* response turns out not to be an event stream, so the caller can stop before
|
|
65
|
+
* any retries.
|
|
66
|
+
*
|
|
67
|
+
* @category Utilities - Events
|
|
68
|
+
*/
|
|
69
|
+
export function createGraphqlSseEventStreamClient({ url, authToken, onUnsupported, fetchFn = globalThis.fetch, }) {
|
|
70
|
+
const client = createClient({
|
|
71
|
+
url,
|
|
72
|
+
headers: {
|
|
73
|
+
'X-Client-ID': GRAPHQL_CLIENT_ID,
|
|
74
|
+
...(authToken ? { Authorization: `Bearer ${authToken}` } : {}),
|
|
75
|
+
},
|
|
76
|
+
fetchFn: async (input, init) => {
|
|
77
|
+
const res = await fetchFn(input, init);
|
|
78
|
+
try {
|
|
79
|
+
return await assertEventStream(res);
|
|
80
|
+
}
|
|
81
|
+
catch (error) {
|
|
82
|
+
if (error instanceof SubscriptionsUnsupportedError) {
|
|
83
|
+
onUnsupported?.(error);
|
|
84
|
+
}
|
|
85
|
+
throw error;
|
|
86
|
+
}
|
|
87
|
+
},
|
|
88
|
+
});
|
|
89
|
+
return {
|
|
90
|
+
subscribe: (payload, sink, onConnected) => client.subscribe(payload, sink, {
|
|
91
|
+
connected: (reconnected) => onConnected?.(reconnected),
|
|
92
|
+
}),
|
|
93
|
+
dispose: () => {
|
|
94
|
+
client.dispose();
|
|
95
|
+
},
|
|
96
|
+
};
|
|
97
|
+
}
|