@entifix/react-integration 0.13.0 → 0.14.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/dist/event-source.d.ts +5 -4
- package/dist/event-source.d.ts.map +1 -1
- package/dist/event-source.js +5 -4
- package/dist/event-source.js.map +1 -1
- package/dist/hooks/use-data-loading/use-data-loading.d.ts +2 -2
- package/dist/hooks/use-data-loading/use-data-loading.d.ts.map +1 -1
- package/dist/hooks/use-data-loading/use-data-loading.js.map +1 -1
- package/dist/hooks/use-data-loading/use-data-loading.types.d.ts +3 -3
- package/dist/hooks/use-data-loading/use-data-loading.types.d.ts.map +1 -1
- package/dist/hooks/use-data-loading/use-data-loading.types.js.map +1 -1
- package/dist/hooks/use-entity-link-source/use-entity-link-source.d.ts.map +1 -1
- package/dist/hooks/use-entity-link-source/use-entity-link-source.js.map +1 -1
- package/dist/hooks/use-entity-link-source/use-entity-link-source.types.d.ts +3 -3
- package/dist/hooks/use-entity-link-source/use-entity-link-source.types.d.ts.map +1 -1
- package/dist/hooks/use-entity-link-source/use-entity-link-source.types.js.map +1 -1
- package/dist/hooks/use-entity-mutation/use-entity-mutation.d.ts +2 -2
- package/dist/hooks/use-entity-mutation/use-entity-mutation.d.ts.map +1 -1
- package/dist/hooks/use-entity-mutation/use-entity-mutation.js.map +1 -1
- package/dist/hooks/use-entity-mutation/use-entity-mutation.types.d.ts +4 -4
- package/dist/hooks/use-entity-mutation/use-entity-mutation.types.d.ts.map +1 -1
- package/dist/hooks/use-entity-mutation/use-entity-mutation.types.js.map +1 -1
- package/dist/hooks/use-entity-record/use-entity-record.d.ts +2 -2
- package/dist/hooks/use-entity-record/use-entity-record.d.ts.map +1 -1
- package/dist/hooks/use-entity-record/use-entity-record.js.map +1 -1
- package/dist/hooks/use-entity-record/use-entity-record.types.d.ts +3 -3
- package/dist/hooks/use-entity-record/use-entity-record.types.d.ts.map +1 -1
- package/dist/hooks/use-entity-record/use-entity-record.types.js.map +1 -1
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -1
- package/dist/pending/pending-flow-store.d.ts +86 -0
- package/dist/pending/pending-flow-store.d.ts.map +1 -0
- package/dist/pending/pending-flow-store.js +124 -0
- package/dist/pending/pending-flow-store.js.map +1 -0
- package/dist/pending/use-optimistic-mutation.d.ts +61 -0
- package/dist/pending/use-optimistic-mutation.d.ts.map +1 -0
- package/dist/pending/use-optimistic-mutation.js +88 -0
- package/dist/pending/use-optimistic-mutation.js.map +1 -0
- package/dist/pending/use-pending-flow-settlement.d.ts +43 -0
- package/dist/pending/use-pending-flow-settlement.d.ts.map +1 -0
- package/dist/pending/use-pending-flow-settlement.js +126 -0
- package/dist/pending/use-pending-flow-settlement.js.map +1 -0
- package/dist/reactive/event-source-push-channel.d.ts +56 -0
- package/dist/reactive/event-source-push-channel.d.ts.map +1 -0
- package/dist/reactive/event-source-push-channel.js +118 -0
- package/dist/reactive/event-source-push-channel.js.map +1 -0
- package/dist/reactive/push-channel.d.ts +69 -0
- package/dist/reactive/push-channel.d.ts.map +1 -0
- package/dist/reactive/push-channel.js +33 -0
- package/dist/reactive/push-channel.js.map +1 -0
- package/dist/reactive/push-router.d.ts +26 -0
- package/dist/reactive/push-router.d.ts.map +1 -0
- package/dist/reactive/push-router.js +64 -0
- package/dist/reactive/push-router.js.map +1 -0
- package/dist/reactive/use-reactive-cache.d.ts +49 -0
- package/dist/reactive/use-reactive-cache.d.ts.map +1 -0
- package/dist/reactive/use-reactive-cache.js +106 -0
- package/dist/reactive/use-reactive-cache.js.map +1 -0
- package/package.json +7 -7
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import type { PushChannel } from './push-channel.js';
|
|
2
|
+
/** The stream URL's repeated parameter naming one subscribed topic. */
|
|
3
|
+
export declare const PUSH_TOPIC_PARAM = "topic";
|
|
4
|
+
/** The stream URL's repeated parameter carrying one flow capability. */
|
|
5
|
+
export declare const PUSH_CAPABILITY_PARAM = "capability";
|
|
6
|
+
/**
|
|
7
|
+
* The stream URL's parameter carrying the last event id seen, on a reopen. A
|
|
8
|
+
* new `EventSource` cannot set the `Last-Event-ID` header itself.
|
|
9
|
+
*/
|
|
10
|
+
export declare const PUSH_CURSOR_PARAM = "lastEventId";
|
|
11
|
+
export interface EventSourcePushChannelOptions {
|
|
12
|
+
/** The stream's same-origin URL, without the topic parameters. */
|
|
13
|
+
readonly url: string;
|
|
14
|
+
/**
|
|
15
|
+
* Refreshes the session when the server asks for a reauth. The stream stays
|
|
16
|
+
* closed until it resolves; a rejection leaves it closed until the next
|
|
17
|
+
* change of interest, because reopening on a credential known to be dead is
|
|
18
|
+
* a `401`, which an `EventSource` never retries.
|
|
19
|
+
*/
|
|
20
|
+
readonly refresh: () => Promise<void>;
|
|
21
|
+
/**
|
|
22
|
+
* The flow capabilities to present, read at every open. A host that hands
|
|
23
|
+
* an anonymous holder a capability returns it here.
|
|
24
|
+
*/
|
|
25
|
+
readonly capabilities?: () => readonly string[];
|
|
26
|
+
/**
|
|
27
|
+
* How long a change of interest waits before reopening, in milliseconds, so
|
|
28
|
+
* a screen mounting five subscriptions reopens once. Defaults to 25.
|
|
29
|
+
*/
|
|
30
|
+
readonly reopenDelayMs?: number;
|
|
31
|
+
}
|
|
32
|
+
export interface EventSourcePushChannel extends PushChannel {
|
|
33
|
+
/**
|
|
34
|
+
* How many frames this channel dropped because they did not decode. A frame
|
|
35
|
+
* is dropped rather than thrown, so the count is the only trace a drifted
|
|
36
|
+
* server leaves in the browser.
|
|
37
|
+
*/
|
|
38
|
+
dropped(): number;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* The push channel's browser end: **one** `EventSource` per tab per base URL,
|
|
42
|
+
* multiplexing every subscribed topic
|
|
43
|
+
* ([ADR 0021](../../../../../docs/adr/0021-server-push-and-the-multiplexed-channel.md)).
|
|
44
|
+
*
|
|
45
|
+
* The topic set is the stream's URL, so a change of interest closes the stream
|
|
46
|
+
* and opens a new one, carrying the last event id so the server can resume.
|
|
47
|
+
* The reopen is debounced; a stream nobody listens to is closed on the same
|
|
48
|
+
* delay. Every frame is decoded through the message registry, and one that
|
|
49
|
+
* does not decode is dropped and counted.
|
|
50
|
+
*
|
|
51
|
+
* On `event: reauth` the stream is closed at once — before the server's EOF
|
|
52
|
+
* could make the browser reconnect on the expiring cookie — and reopened only
|
|
53
|
+
* once `refresh` resolves.
|
|
54
|
+
*/
|
|
55
|
+
export declare function makeEventSourcePushChannel({ url, refresh, capabilities, reopenDelayMs, }: EventSourcePushChannelOptions): EventSourcePushChannel;
|
|
56
|
+
//# sourceMappingURL=event-source-push-channel.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"event-source-push-channel.d.ts","sourceRoot":"","sources":["../../src/reactive/event-source-push-channel.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAGrD,uEAAuE;AACvE,eAAO,MAAM,gBAAgB,UAAU,CAAC;AACxC,wEAAwE;AACxE,eAAO,MAAM,qBAAqB,eAAe,CAAC;AAClD;;;GAGG;AACH,eAAO,MAAM,iBAAiB,gBAAgB,CAAC;AAE/C,MAAM,WAAW,6BAA6B;IAC5C,kEAAkE;IAClE,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB;;;;;OAKG;IACH,QAAQ,CAAC,OAAO,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IACtC;;;OAGG;IACH,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,SAAS,MAAM,EAAE,CAAC;IAChD;;;OAGG;IACH,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;CACjC;AAED,MAAM,WAAW,sBAAuB,SAAQ,WAAW;IACzD;;;;OAIG;IACH,OAAO,IAAI,MAAM,CAAC;CACnB;AAmCD;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,0BAA0B,CAAC,EACzC,GAAG,EACH,OAAO,EACP,YAAuB,EACvB,aAAkB,GACnB,EAAE,6BAA6B,GAAG,sBAAsB,CA8FxD"}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { decodeEvent } from '@entifix/core';
|
|
2
|
+
import { Effect, Result, Schema } from 'effect';
|
|
3
|
+
import { makePushRouter } from './push-router.js';
|
|
4
|
+
/** The stream URL's repeated parameter naming one subscribed topic. */ export const PUSH_TOPIC_PARAM = 'topic';
|
|
5
|
+
/** The stream URL's repeated parameter carrying one flow capability. */ export const PUSH_CAPABILITY_PARAM = 'capability';
|
|
6
|
+
/**
|
|
7
|
+
* The stream URL's parameter carrying the last event id seen, on a reopen. A
|
|
8
|
+
* new `EventSource` cannot set the `Last-Event-ID` header itself.
|
|
9
|
+
*/ export const PUSH_CURSOR_PARAM = 'lastEventId';
|
|
10
|
+
const EventFrame = Schema.Struct({
|
|
11
|
+
topics: Schema.Array(Schema.String),
|
|
12
|
+
envelope: Schema.Unknown
|
|
13
|
+
});
|
|
14
|
+
const ResyncFrame = Schema.Struct({
|
|
15
|
+
topics: Schema.Array(Schema.String)
|
|
16
|
+
});
|
|
17
|
+
const parse = (raw, decode)=>Effect.runSync(Effect.result(Effect.flatMap(Effect.try(()=>JSON.parse(raw)), decode)));
|
|
18
|
+
const decodeEventFrame = (body)=>Effect.flatMap(Schema.decodeUnknownEffect(EventFrame)(body), (frame)=>Effect.map(decodeEvent(frame.envelope), (event)=>({
|
|
19
|
+
topics: frame.topics,
|
|
20
|
+
event
|
|
21
|
+
})));
|
|
22
|
+
/**
|
|
23
|
+
* The push channel's browser end: **one** `EventSource` per tab per base URL,
|
|
24
|
+
* multiplexing every subscribed topic
|
|
25
|
+
* ([ADR 0021](../../../../../docs/adr/0021-server-push-and-the-multiplexed-channel.md)).
|
|
26
|
+
*
|
|
27
|
+
* The topic set is the stream's URL, so a change of interest closes the stream
|
|
28
|
+
* and opens a new one, carrying the last event id so the server can resume.
|
|
29
|
+
* The reopen is debounced; a stream nobody listens to is closed on the same
|
|
30
|
+
* delay. Every frame is decoded through the message registry, and one that
|
|
31
|
+
* does not decode is dropped and counted.
|
|
32
|
+
*
|
|
33
|
+
* On `event: reauth` the stream is closed at once — before the server's EOF
|
|
34
|
+
* could make the browser reconnect on the expiring cookie — and reopened only
|
|
35
|
+
* once `refresh` resolves.
|
|
36
|
+
*/ export function makeEventSourcePushChannel({ url, refresh, capabilities = ()=>[], reopenDelayMs = 25 }) {
|
|
37
|
+
const router = makePushRouter();
|
|
38
|
+
let source;
|
|
39
|
+
let openedUrl;
|
|
40
|
+
let lastEventId;
|
|
41
|
+
let timer;
|
|
42
|
+
let refreshing = false;
|
|
43
|
+
let dropped = 0;
|
|
44
|
+
const streamUrl = ()=>{
|
|
45
|
+
const topics = router.topics();
|
|
46
|
+
if (topics.length === 0) return undefined;
|
|
47
|
+
const params = new URLSearchParams();
|
|
48
|
+
for (const topic of topics)params.append(PUSH_TOPIC_PARAM, topic);
|
|
49
|
+
for (const capability of [
|
|
50
|
+
...capabilities()
|
|
51
|
+
].sort())params.append(PUSH_CAPABILITY_PARAM, capability);
|
|
52
|
+
return `${url}${url.includes('?') ? '&' : '?'}${params.toString()}`;
|
|
53
|
+
};
|
|
54
|
+
const close = ()=>{
|
|
55
|
+
source == null ? void 0 : source.close();
|
|
56
|
+
source = undefined;
|
|
57
|
+
openedUrl = undefined;
|
|
58
|
+
router.disconnected();
|
|
59
|
+
};
|
|
60
|
+
const open = (target)=>{
|
|
61
|
+
const cursor = lastEventId === undefined ? '' : `&${PUSH_CURSOR_PARAM}=${encodeURIComponent(lastEventId)}`;
|
|
62
|
+
const opened = new EventSource(`${target}${cursor}`);
|
|
63
|
+
source = opened;
|
|
64
|
+
openedUrl = target;
|
|
65
|
+
opened.onopen = ()=>{
|
|
66
|
+
router.connected();
|
|
67
|
+
};
|
|
68
|
+
opened.onmessage = (message)=>{
|
|
69
|
+
if (message.lastEventId !== '') lastEventId = message.lastEventId;
|
|
70
|
+
const frame = parse(message.data, decodeEventFrame);
|
|
71
|
+
if (Result.isFailure(frame)) {
|
|
72
|
+
dropped += 1;
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
router.deliver(frame.success.topics, frame.success.event);
|
|
76
|
+
};
|
|
77
|
+
opened.addEventListener('resync', (message)=>{
|
|
78
|
+
const frame = parse(message.data, Schema.decodeUnknownEffect(ResyncFrame));
|
|
79
|
+
if (Result.isFailure(frame)) {
|
|
80
|
+
dropped += 1;
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
router.resync(frame.success.topics);
|
|
84
|
+
});
|
|
85
|
+
opened.addEventListener('reauth', ()=>{
|
|
86
|
+
close();
|
|
87
|
+
refreshing = true;
|
|
88
|
+
refresh().then(()=>{
|
|
89
|
+
refreshing = false;
|
|
90
|
+
sync();
|
|
91
|
+
}, ()=>{
|
|
92
|
+
refreshing = false;
|
|
93
|
+
});
|
|
94
|
+
});
|
|
95
|
+
};
|
|
96
|
+
// Brings the stream in line with the subscribed topics: closes it when
|
|
97
|
+
// nothing listens, reopens it when the topics or capabilities moved.
|
|
98
|
+
const sync = ()=>{
|
|
99
|
+
// Guarded because a server-rendered pass has no `EventSource` at all.
|
|
100
|
+
if (refreshing || typeof EventSource === 'undefined') return;
|
|
101
|
+
const target = streamUrl();
|
|
102
|
+
if (target === openedUrl) return;
|
|
103
|
+
close();
|
|
104
|
+
if (target !== undefined) open(target);
|
|
105
|
+
};
|
|
106
|
+
router.onTopicsChange(()=>{
|
|
107
|
+
clearTimeout(timer);
|
|
108
|
+
timer = setTimeout(sync, reopenDelayMs);
|
|
109
|
+
});
|
|
110
|
+
return {
|
|
111
|
+
subscribe: router.subscribe,
|
|
112
|
+
onConnect: router.onConnect,
|
|
113
|
+
onResync: router.onResync,
|
|
114
|
+
dropped: ()=>dropped
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
//# sourceMappingURL=event-source-push-channel.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/reactive/event-source-push-channel.ts"],"sourcesContent":["import { decodeEvent, type DomainEvent } from '@entifix/core';\nimport { Effect, Result, Schema } from 'effect';\n\nimport type { PushChannel } from './push-channel.js';\nimport { makePushRouter } from './push-router.js';\n\n/** The stream URL's repeated parameter naming one subscribed topic. */\nexport const PUSH_TOPIC_PARAM = 'topic';\n/** The stream URL's repeated parameter carrying one flow capability. */\nexport const PUSH_CAPABILITY_PARAM = 'capability';\n/**\n * The stream URL's parameter carrying the last event id seen, on a reopen. A\n * new `EventSource` cannot set the `Last-Event-ID` header itself.\n */\nexport const PUSH_CURSOR_PARAM = 'lastEventId';\n\nexport interface EventSourcePushChannelOptions {\n /** The stream's same-origin URL, without the topic parameters. */\n readonly url: string;\n /**\n * Refreshes the session when the server asks for a reauth. The stream stays\n * closed until it resolves; a rejection leaves it closed until the next\n * change of interest, because reopening on a credential known to be dead is\n * a `401`, which an `EventSource` never retries.\n */\n readonly refresh: () => Promise<void>;\n /**\n * The flow capabilities to present, read at every open. A host that hands\n * an anonymous holder a capability returns it here.\n */\n readonly capabilities?: () => readonly string[];\n /**\n * How long a change of interest waits before reopening, in milliseconds, so\n * a screen mounting five subscriptions reopens once. Defaults to 25.\n */\n readonly reopenDelayMs?: number;\n}\n\nexport interface EventSourcePushChannel extends PushChannel {\n /**\n * How many frames this channel dropped because they did not decode. A frame\n * is dropped rather than thrown, so the count is the only trace a drifted\n * server leaves in the browser.\n */\n dropped(): number;\n}\n\nconst EventFrame = Schema.Struct({\n topics: Schema.Array(Schema.String),\n envelope: Schema.Unknown,\n});\n\nconst ResyncFrame = Schema.Struct({ topics: Schema.Array(Schema.String) });\n\nconst parse = <A>(\n raw: string,\n decode: (body: unknown) => Effect.Effect<A, unknown>,\n): Result.Result<A, unknown> =>\n Effect.runSync(\n Effect.result(\n Effect.flatMap(\n Effect.try(() => JSON.parse(raw) as unknown),\n decode,\n ),\n ),\n );\n\nconst decodeEventFrame = (\n body: unknown,\n): Effect.Effect<\n { readonly topics: readonly string[]; readonly event: DomainEvent },\n unknown\n> =>\n Effect.flatMap(Schema.decodeUnknownEffect(EventFrame)(body), frame =>\n Effect.map(decodeEvent(frame.envelope), event => ({\n topics: frame.topics,\n event,\n })),\n );\n\n/**\n * The push channel's browser end: **one** `EventSource` per tab per base URL,\n * multiplexing every subscribed topic\n * ([ADR 0021](../../../../../docs/adr/0021-server-push-and-the-multiplexed-channel.md)).\n *\n * The topic set is the stream's URL, so a change of interest closes the stream\n * and opens a new one, carrying the last event id so the server can resume.\n * The reopen is debounced; a stream nobody listens to is closed on the same\n * delay. Every frame is decoded through the message registry, and one that\n * does not decode is dropped and counted.\n *\n * On `event: reauth` the stream is closed at once — before the server's EOF\n * could make the browser reconnect on the expiring cookie — and reopened only\n * once `refresh` resolves.\n */\nexport function makeEventSourcePushChannel({\n url,\n refresh,\n capabilities = () => [],\n reopenDelayMs = 25,\n}: EventSourcePushChannelOptions): EventSourcePushChannel {\n const router = makePushRouter();\n let source: EventSource | undefined;\n let openedUrl: string | undefined;\n let lastEventId: string | undefined;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let refreshing = false;\n let dropped = 0;\n\n const streamUrl = (): string | undefined => {\n const topics = router.topics();\n if (topics.length === 0) return undefined;\n const params = new URLSearchParams();\n for (const topic of topics) params.append(PUSH_TOPIC_PARAM, topic);\n for (const capability of [...capabilities()].sort())\n params.append(PUSH_CAPABILITY_PARAM, capability);\n return `${url}${url.includes('?') ? '&' : '?'}${params.toString()}`;\n };\n\n const close = (): void => {\n source?.close();\n source = undefined;\n openedUrl = undefined;\n router.disconnected();\n };\n\n const open = (target: string): void => {\n const cursor =\n lastEventId === undefined\n ? ''\n : `&${PUSH_CURSOR_PARAM}=${encodeURIComponent(lastEventId)}`;\n const opened = new EventSource(`${target}${cursor}`);\n source = opened;\n openedUrl = target;\n opened.onopen = () => {\n router.connected();\n };\n opened.onmessage = message => {\n if (message.lastEventId !== '') lastEventId = message.lastEventId;\n const frame = parse(message.data as string, decodeEventFrame);\n if (Result.isFailure(frame)) {\n dropped += 1;\n return;\n }\n router.deliver(frame.success.topics, frame.success.event);\n };\n opened.addEventListener('resync', message => {\n const frame = parse(\n (message as MessageEvent).data as string,\n Schema.decodeUnknownEffect(ResyncFrame),\n );\n if (Result.isFailure(frame)) {\n dropped += 1;\n return;\n }\n router.resync(frame.success.topics);\n });\n opened.addEventListener('reauth', () => {\n close();\n refreshing = true;\n refresh().then(\n () => {\n refreshing = false;\n sync();\n },\n () => {\n refreshing = false;\n },\n );\n });\n };\n\n // Brings the stream in line with the subscribed topics: closes it when\n // nothing listens, reopens it when the topics or capabilities moved.\n const sync = (): void => {\n // Guarded because a server-rendered pass has no `EventSource` at all.\n if (refreshing || typeof EventSource === 'undefined') return;\n const target = streamUrl();\n if (target === openedUrl) return;\n close();\n if (target !== undefined) open(target);\n };\n\n router.onTopicsChange(() => {\n clearTimeout(timer);\n timer = setTimeout(sync, reopenDelayMs);\n });\n\n return {\n subscribe: router.subscribe,\n onConnect: router.onConnect,\n onResync: router.onResync,\n dropped: () => dropped,\n };\n}\n"],"names":["decodeEvent","Effect","Result","Schema","makePushRouter","PUSH_TOPIC_PARAM","PUSH_CAPABILITY_PARAM","PUSH_CURSOR_PARAM","EventFrame","Struct","topics","Array","String","envelope","Unknown","ResyncFrame","parse","raw","decode","runSync","result","flatMap","try","JSON","decodeEventFrame","body","decodeUnknownEffect","frame","map","event","makeEventSourcePushChannel","url","refresh","capabilities","reopenDelayMs","router","source","openedUrl","lastEventId","timer","refreshing","dropped","streamUrl","length","undefined","params","URLSearchParams","topic","append","capability","sort","includes","toString","close","disconnected","open","target","cursor","encodeURIComponent","opened","EventSource","onopen","connected","onmessage","message","data","isFailure","deliver","success","addEventListener","resync","then","sync","onTopicsChange","clearTimeout","setTimeout","subscribe","onConnect","onResync"],"mappings":"AAAA,SAASA,WAAW,QAA0B,gBAAgB;AAC9D,SAASC,MAAM,EAAEC,MAAM,EAAEC,MAAM,Q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,IAAI,CACZ;gBACE/B,aAAa;gBACbgC;YACF,GACA;gBACEhC,aAAa;YACf;QAEJ;IACF;IAEA,uEAAuE;IACvE,qEAAqE;IACrE,MAAMgC,OAAO;QACX,sEAAsE;QACtE,IAAIhC,cAAc,OAAOoB,gBAAgB,aAAa;QACtD,MAAMJ,SAASd;QACf,IAAIc,WAAWnB,WAAW;QAC1BgB;QACA,IAAIG,WAAWZ,WAAWW,KAAKC;IACjC;IAEArB,OAAOsC,cAAc,CAAC;QACpBC,aAAanC;QACbA,QAAQoC,WAAWH,MAAMtC;IAC3B;IAEA,OAAO;QACL0C,WAAWzC,OAAOyC,SAAS;QAC3BC,WAAW1C,OAAO0C,SAAS;QAC3BC,UAAU3C,OAAO2C,QAAQ;QACzBrC,SAAS,IAAMA;IACjB;AACF"}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import type { DomainEvent, EntityId } from '@entifix/core';
|
|
2
|
+
import { Context } from 'effect';
|
|
3
|
+
/**
|
|
4
|
+
* What a tab can listen to: every change to one entity, one record, or one
|
|
5
|
+
* flow's outcome
|
|
6
|
+
* ([ADR 0021](../../../../../docs/adr/0021-server-push-and-the-multiplexed-channel.md)).
|
|
7
|
+
*/
|
|
8
|
+
export type PushTopic = `entity:${string}` | `record:${string}:${string}` | `flow:${string}`;
|
|
9
|
+
/** Every change to the entity whose `key ?? name` is `key`. */
|
|
10
|
+
export declare const entityTopic: (key: string) => PushTopic;
|
|
11
|
+
/** Every change to one record of an entity. */
|
|
12
|
+
export declare const recordTopic: (key: string, id: EntityId) => PushTopic;
|
|
13
|
+
/** The outcome of one flow: its `flow.*` events. */
|
|
14
|
+
export declare const flowTopic: (flowId: string) => PushTopic;
|
|
15
|
+
/** Receives each event pushed on a topic it subscribed to, decoded. */
|
|
16
|
+
export type PushListener = (event: DomainEvent) => void;
|
|
17
|
+
/**
|
|
18
|
+
* Receives the subscribed topics the server could not replay after a
|
|
19
|
+
* reconnect. Whatever the listener shows for them must be read again.
|
|
20
|
+
*/
|
|
21
|
+
export type ResyncListener = (topics: readonly PushTopic[]) => void;
|
|
22
|
+
/**
|
|
23
|
+
* The browser half of push: topics in, decoded events out.
|
|
24
|
+
*
|
|
25
|
+
* Commands never travel here; the stream is one-way and every write stays
|
|
26
|
+
* HTTP. Each subscribe returns its own unsubscribe.
|
|
27
|
+
*/
|
|
28
|
+
export interface PushChannel {
|
|
29
|
+
/**
|
|
30
|
+
* Listens to one topic. A listener subscribed to several topics an event
|
|
31
|
+
* names hears that event once.
|
|
32
|
+
*/
|
|
33
|
+
subscribe(topic: PushTopic, listener: PushListener): () => void;
|
|
34
|
+
/**
|
|
35
|
+
* Runs whenever the stream is (re)connected, and **immediately if it is
|
|
36
|
+
* already connected when the listener registers**. A consumer that may have
|
|
37
|
+
* missed something while disconnected re-reads here; without the replay, one
|
|
38
|
+
* mounting after the stream opened would wait for a drop that may never come.
|
|
39
|
+
*/
|
|
40
|
+
onConnect(listener: () => void): () => void;
|
|
41
|
+
/** Runs when the server asks for subscribed topics to be read again. */
|
|
42
|
+
onResync(listener: ResyncListener): () => void;
|
|
43
|
+
}
|
|
44
|
+
declare const PushChannelTag_base: Context.ServiceClass<PushChannelTag, "@entifix/react-integration/PushChannel", PushChannel>;
|
|
45
|
+
export declare class PushChannelTag extends PushChannelTag_base {
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* A channel that never connects and never emits: the default until a host
|
|
49
|
+
* provides a transport. Its consumers reconcile never, which is the honest
|
|
50
|
+
* behaviour for a transport that is not there.
|
|
51
|
+
*/
|
|
52
|
+
export declare const NoopPushChannel: PushChannel;
|
|
53
|
+
export interface InMemoryPushChannel extends PushChannel {
|
|
54
|
+
/** Delivers `event` as a server would, naming the topics it matched. */
|
|
55
|
+
emit(topics: readonly PushTopic[], event: DomainEvent): void;
|
|
56
|
+
/** Announces a (re)connection and marks the channel connected. */
|
|
57
|
+
connect(): void;
|
|
58
|
+
/** Asks for `topics` to be read again, as a server's `resync` does. */
|
|
59
|
+
resync(topics: readonly PushTopic[]): void;
|
|
60
|
+
/** The topics something is subscribed to, sorted. */
|
|
61
|
+
topics(): readonly PushTopic[];
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* A synchronous channel for specs and mocks. It routes exactly as the
|
|
65
|
+
* `EventSource` adapter does, because both run on the same router.
|
|
66
|
+
*/
|
|
67
|
+
export declare function makeInMemoryPushChannel(): InMemoryPushChannel;
|
|
68
|
+
export {};
|
|
69
|
+
//# sourceMappingURL=push-channel.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"push-channel.d.ts","sourceRoot":"","sources":["../../src/reactive/push-channel.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAC3D,OAAO,EAAE,OAAO,EAAE,MAAM,QAAQ,CAAC;AAIjC;;;;GAIG;AACH,MAAM,MAAM,SAAS,GACnB,UAAU,MAAM,EAAE,GAAG,UAAU,MAAM,IAAI,MAAM,EAAE,GAAG,QAAQ,MAAM,EAAE,CAAC;AAEvE,+DAA+D;AAC/D,eAAO,MAAM,WAAW,GAAI,KAAK,MAAM,KAAG,SAA4B,CAAC;AAEvE,+CAA+C;AAC/C,eAAO,MAAM,WAAW,GAAI,KAAK,MAAM,EAAE,IAAI,QAAQ,KAAG,SACzB,CAAC;AAEhC,oDAAoD;AACpD,eAAO,MAAM,SAAS,GAAI,QAAQ,MAAM,KAAG,SAA6B,CAAC;AAEzE,uEAAuE;AACvE,MAAM,MAAM,YAAY,GAAG,CAAC,KAAK,EAAE,WAAW,KAAK,IAAI,CAAC;AAExD;;;GAGG;AACH,MAAM,MAAM,cAAc,GAAG,CAAC,MAAM,EAAE,SAAS,SAAS,EAAE,KAAK,IAAI,CAAC;AAEpE;;;;;GAKG;AACH,MAAM,WAAW,WAAW;IAC1B;;;OAGG;IACH,SAAS,CAAC,KAAK,EAAE,SAAS,EAAE,QAAQ,EAAE,YAAY,GAAG,MAAM,IAAI,CAAC;IAChE;;;;;OAKG;IACH,SAAS,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC;IAC5C,wEAAwE;IACxE,QAAQ,CAAC,QAAQ,EAAE,cAAc,GAAG,MAAM,IAAI,CAAC;CAChD;;AAED,qBAAa,cAAe,SAAQ,mBAGS;CAAG;AAEhD;;;;GAIG;AACH,eAAO,MAAM,eAAe,EAAE,WAI7B,CAAC;AAEF,MAAM,WAAW,mBAAoB,SAAQ,WAAW;IACtD,wEAAwE;IACxE,IAAI,CAAC,MAAM,EAAE,SAAS,SAAS,EAAE,EAAE,KAAK,EAAE,WAAW,GAAG,IAAI,CAAC;IAC7D,kEAAkE;IAClE,OAAO,IAAI,IAAI,CAAC;IAChB,uEAAuE;IACvE,MAAM,CAAC,MAAM,EAAE,SAAS,SAAS,EAAE,GAAG,IAAI,CAAC;IAC3C,qDAAqD;IACrD,MAAM,IAAI,SAAS,SAAS,EAAE,CAAC;CAChC;AAED;;;GAGG;AACH,wBAAgB,uBAAuB,IAAI,mBAAmB,CAW7D"}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { Context } from 'effect';
|
|
2
|
+
import { makePushRouter } from './push-router.js';
|
|
3
|
+
/** Every change to the entity whose `key ?? name` is `key`. */ export const entityTopic = (key)=>`entity:${key}`;
|
|
4
|
+
/** Every change to one record of an entity. */ export const recordTopic = (key, id)=>`record:${key}:${String(id)}`;
|
|
5
|
+
/** The outcome of one flow: its `flow.*` events. */ export const flowTopic = (flowId)=>`flow:${flowId}`;
|
|
6
|
+
export class PushChannelTag extends Context.Service()('@entifix/react-integration/PushChannel') {
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* A channel that never connects and never emits: the default until a host
|
|
10
|
+
* provides a transport. Its consumers reconcile never, which is the honest
|
|
11
|
+
* behaviour for a transport that is not there.
|
|
12
|
+
*/ export const NoopPushChannel = {
|
|
13
|
+
subscribe: ()=>()=>undefined,
|
|
14
|
+
onConnect: ()=>()=>undefined,
|
|
15
|
+
onResync: ()=>()=>undefined
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* A synchronous channel for specs and mocks. It routes exactly as the
|
|
19
|
+
* `EventSource` adapter does, because both run on the same router.
|
|
20
|
+
*/ export function makeInMemoryPushChannel() {
|
|
21
|
+
const router = makePushRouter();
|
|
22
|
+
return {
|
|
23
|
+
subscribe: router.subscribe,
|
|
24
|
+
onConnect: router.onConnect,
|
|
25
|
+
onResync: router.onResync,
|
|
26
|
+
emit: router.deliver,
|
|
27
|
+
connect: router.connected,
|
|
28
|
+
resync: router.resync,
|
|
29
|
+
topics: router.topics
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
//# sourceMappingURL=push-channel.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/reactive/push-channel.ts"],"sourcesContent":["import type { DomainEvent, EntityId } from '@entifix/core';\nimport { Context } from 'effect';\n\nimport { makePushRouter } from './push-router.js';\n\n/**\n * What a tab can listen to: every change to one entity, one record, or one\n * flow's outcome\n * ([ADR 0021](../../../../../docs/adr/0021-server-push-and-the-multiplexed-channel.md)).\n */\nexport type PushTopic =\n `entity:${string}` | `record:${string}:${string}` | `flow:${string}`;\n\n/** Every change to the entity whose `key ?? name` is `key`. */\nexport const entityTopic = (key: string): PushTopic => `entity:${key}`;\n\n/** Every change to one record of an entity. */\nexport const recordTopic = (key: string, id: EntityId): PushTopic =>\n `record:${key}:${String(id)}`;\n\n/** The outcome of one flow: its `flow.*` events. */\nexport const flowTopic = (flowId: string): PushTopic => `flow:${flowId}`;\n\n/** Receives each event pushed on a topic it subscribed to, decoded. */\nexport type PushListener = (event: DomainEvent) => void;\n\n/**\n * Receives the subscribed topics the server could not replay after a\n * reconnect. Whatever the listener shows for them must be read again.\n */\nexport type ResyncListener = (topics: readonly PushTopic[]) => void;\n\n/**\n * The browser half of push: topics in, decoded events out.\n *\n * Commands never travel here; the stream is one-way and every write stays\n * HTTP. Each subscribe returns its own unsubscribe.\n */\nexport interface PushChannel {\n /**\n * Listens to one topic. A listener subscribed to several topics an event\n * names hears that event once.\n */\n subscribe(topic: PushTopic, listener: PushListener): () => void;\n /**\n * Runs whenever the stream is (re)connected, and **immediately if it is\n * already connected when the listener registers**. A consumer that may have\n * missed something while disconnected re-reads here; without the replay, one\n * mounting after the stream opened would wait for a drop that may never come.\n */\n onConnect(listener: () => void): () => void;\n /** Runs when the server asks for subscribed topics to be read again. */\n onResync(listener: ResyncListener): () => void;\n}\n\nexport class PushChannelTag extends Context.Service<\n PushChannelTag,\n PushChannel\n>()('@entifix/react-integration/PushChannel') {}\n\n/**\n * A channel that never connects and never emits: the default until a host\n * provides a transport. Its consumers reconcile never, which is the honest\n * behaviour for a transport that is not there.\n */\nexport const NoopPushChannel: PushChannel = {\n subscribe: () => () => undefined,\n onConnect: () => () => undefined,\n onResync: () => () => undefined,\n};\n\nexport interface InMemoryPushChannel extends PushChannel {\n /** Delivers `event` as a server would, naming the topics it matched. */\n emit(topics: readonly PushTopic[], event: DomainEvent): void;\n /** Announces a (re)connection and marks the channel connected. */\n connect(): void;\n /** Asks for `topics` to be read again, as a server's `resync` does. */\n resync(topics: readonly PushTopic[]): void;\n /** The topics something is subscribed to, sorted. */\n topics(): readonly PushTopic[];\n}\n\n/**\n * A synchronous channel for specs and mocks. It routes exactly as the\n * `EventSource` adapter does, because both run on the same router.\n */\nexport function makeInMemoryPushChannel(): InMemoryPushChannel {\n const router = makePushRouter();\n return {\n subscribe: router.subscribe,\n onConnect: router.onConnect,\n onResync: router.onResync,\n emit: router.deliver,\n connect: router.connected,\n resync: router.resync,\n topics: router.topics,\n };\n}\n"],"names":["Context","makePushRouter","entityTopic","key","recordTopic","id","String","flowTopic","flowId","PushChannelTag","Service","NoopPushChannel","subscribe","undefined","onConnect","onResync","makeInMemoryPushChannel","router","emit","deliver","connect","connected","resync","topics"],"mappings":"AACA,SAASA,OAAO,QAAQ,SAAS;AAEjC,SAASC,cAAc,QAAQ,mBAAmB;AAUlD,6DAA6D,GAC7D,OAAO,MAAMC,cAAc,CAACC,MAA2B,CAAC,OAAO,EAAEA,KAAK,CAAC;AAEvE,6CAA6C,GAC7C,OAAO,MAAMC,cAAc,CAACD,KAAaE,KACvC,CAAC,OAAO,EAAEF,IAAI,CAAC,EAAEG,OAAOD,KAAK,CAAC;AAEhC,kDAAkD,GAClD,OAAO,MAAME,YAAY,CAACC,SAA8B,CAAC,KAAK,EAAEA,QAAQ,CAAC;AAkCzE,OAAO,MAAMC,uBAAuBT,QAAQU,OAAO,GAG/C;AAA2C;AAE/C;;;;CAIC,GACD,OAAO,MAAMC,kBAA+B;IAC1CC,WAAW,IAAM,IAAMC;IACvBC,WAAW,IAAM,IAAMD;IACvBE,UAAU,IAAM,IAAMF;AACxB,EAAE;AAaF;;;CAGC,GACD,OAAO,SAASG;IACd,MAAMC,SAAShB;IACf,OAAO;QACLW,WAAWK,OAAOL,SAAS;QAC3BE,WAAWG,OAAOH,SAAS;QAC3BC,UAAUE,OAAOF,QAAQ;QACzBG,MAAMD,OAAOE,OAAO;QACpBC,SAASH,OAAOI,SAAS;QACzBC,QAAQL,OAAOK,MAAM;QACrBC,QAAQN,OAAOM,MAAM;IACvB;AACF"}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { DomainEvent } from '@entifix/core';
|
|
2
|
+
import type { PushListener, PushTopic, ResyncListener } from './push-channel.js';
|
|
3
|
+
/**
|
|
4
|
+
* The listener bookkeeping every `PushChannel` shares: who listens to which
|
|
5
|
+
* topic, and who wants to hear about a connection or a resync. A transport
|
|
6
|
+
* decides when those happen; this decides who hears.
|
|
7
|
+
*/
|
|
8
|
+
export interface PushRouter {
|
|
9
|
+
subscribe(topic: PushTopic, listener: PushListener): () => void;
|
|
10
|
+
onConnect(listener: () => void): () => void;
|
|
11
|
+
onResync(listener: ResyncListener): () => void;
|
|
12
|
+
/** Hands `event` to each listener of the named topics, once each. */
|
|
13
|
+
deliver(topics: readonly string[], event: DomainEvent): void;
|
|
14
|
+
/** Marks the channel connected and tells every connect listener. */
|
|
15
|
+
connected(): void;
|
|
16
|
+
/** Marks the channel disconnected; a late connect listener then waits. */
|
|
17
|
+
disconnected(): void;
|
|
18
|
+
/** Tells every resync listener, about the named topics still subscribed. */
|
|
19
|
+
resync(topics: readonly string[]): void;
|
|
20
|
+
/** The topics something is subscribed to, sorted. */
|
|
21
|
+
topics(): readonly PushTopic[];
|
|
22
|
+
/** Runs whenever the set of subscribed topics changes. */
|
|
23
|
+
onTopicsChange(listener: () => void): void;
|
|
24
|
+
}
|
|
25
|
+
export declare function makePushRouter(): PushRouter;
|
|
26
|
+
//# sourceMappingURL=push-router.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"push-router.d.ts","sourceRoot":"","sources":["../../src/reactive/push-router.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAEjD,OAAO,KAAK,EACV,YAAY,EACZ,SAAS,EACT,cAAc,EACf,MAAM,mBAAmB,CAAC;AAE3B;;;;GAIG;AACH,MAAM,WAAW,UAAU;IACzB,SAAS,CAAC,KAAK,EAAE,SAAS,EAAE,QAAQ,EAAE,YAAY,GAAG,MAAM,IAAI,CAAC;IAChE,SAAS,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC;IAC5C,QAAQ,CAAC,QAAQ,EAAE,cAAc,GAAG,MAAM,IAAI,CAAC;IAC/C,qEAAqE;IACrE,OAAO,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,EAAE,KAAK,EAAE,WAAW,GAAG,IAAI,CAAC;IAC7D,oEAAoE;IACpE,SAAS,IAAI,IAAI,CAAC;IAClB,0EAA0E;IAC1E,YAAY,IAAI,IAAI,CAAC;IACrB,4EAA4E;IAC5E,MAAM,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,GAAG,IAAI,CAAC;IACxC,qDAAqD;IACrD,MAAM,IAAI,SAAS,SAAS,EAAE,CAAC;IAC/B,0DAA0D;IAC1D,cAAc,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,IAAI,CAAC;CAC5C;AAED,wBAAgB,cAAc,IAAI,UAAU,CAkE3C"}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
export function makePushRouter() {
|
|
2
|
+
const byTopic = new Map();
|
|
3
|
+
const connectListeners = new Set();
|
|
4
|
+
const resyncListeners = new Set();
|
|
5
|
+
let isConnected = false;
|
|
6
|
+
let topicsChanged = ()=>undefined;
|
|
7
|
+
const subscribed = (topics)=>topics.filter((topic)=>byTopic.has(topic));
|
|
8
|
+
return {
|
|
9
|
+
subscribe (topic, listener) {
|
|
10
|
+
let listeners = byTopic.get(topic);
|
|
11
|
+
if (listeners === undefined) {
|
|
12
|
+
listeners = new Set();
|
|
13
|
+
byTopic.set(topic, listeners);
|
|
14
|
+
topicsChanged();
|
|
15
|
+
}
|
|
16
|
+
listeners.add(listener);
|
|
17
|
+
return ()=>{
|
|
18
|
+
const current = byTopic.get(topic);
|
|
19
|
+
if ((current == null ? void 0 : current.delete(listener)) !== true || current.size > 0) return;
|
|
20
|
+
byTopic.delete(topic);
|
|
21
|
+
topicsChanged();
|
|
22
|
+
};
|
|
23
|
+
},
|
|
24
|
+
onConnect (listener) {
|
|
25
|
+
connectListeners.add(listener);
|
|
26
|
+
if (isConnected) listener();
|
|
27
|
+
return ()=>{
|
|
28
|
+
connectListeners.delete(listener);
|
|
29
|
+
};
|
|
30
|
+
},
|
|
31
|
+
onResync (listener) {
|
|
32
|
+
resyncListeners.add(listener);
|
|
33
|
+
return ()=>{
|
|
34
|
+
resyncListeners.delete(listener);
|
|
35
|
+
};
|
|
36
|
+
},
|
|
37
|
+
deliver (topics, event) {
|
|
38
|
+
const named = new Set(topics);
|
|
39
|
+
const listeners = new Set();
|
|
40
|
+
for (const [topic, topicListeners] of byTopic)if (named.has(topic)) for (const listener of topicListeners)listeners.add(listener);
|
|
41
|
+
for (const listener of listeners)listener(event);
|
|
42
|
+
},
|
|
43
|
+
connected () {
|
|
44
|
+
isConnected = true;
|
|
45
|
+
for (const listener of connectListeners)listener();
|
|
46
|
+
},
|
|
47
|
+
disconnected () {
|
|
48
|
+
isConnected = false;
|
|
49
|
+
},
|
|
50
|
+
resync (topics) {
|
|
51
|
+
const still = subscribed(topics);
|
|
52
|
+
if (still.length === 0) return;
|
|
53
|
+
for (const listener of resyncListeners)listener(still);
|
|
54
|
+
},
|
|
55
|
+
topics: ()=>[
|
|
56
|
+
...byTopic.keys()
|
|
57
|
+
].sort(),
|
|
58
|
+
onTopicsChange (listener) {
|
|
59
|
+
topicsChanged = listener;
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
//# sourceMappingURL=push-router.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/reactive/push-router.ts"],"sourcesContent":["import type { DomainEvent } from '@entifix/core';\n\nimport type {\n PushListener,\n PushTopic,\n ResyncListener,\n} from './push-channel.js';\n\n/**\n * The listener bookkeeping every `PushChannel` shares: who listens to which\n * topic, and who wants to hear about a connection or a resync. A transport\n * decides when those happen; this decides who hears.\n */\nexport interface PushRouter {\n subscribe(topic: PushTopic, listener: PushListener): () => void;\n onConnect(listener: () => void): () => void;\n onResync(listener: ResyncListener): () => void;\n /** Hands `event` to each listener of the named topics, once each. */\n deliver(topics: readonly string[], event: DomainEvent): void;\n /** Marks the channel connected and tells every connect listener. */\n connected(): void;\n /** Marks the channel disconnected; a late connect listener then waits. */\n disconnected(): void;\n /** Tells every resync listener, about the named topics still subscribed. */\n resync(topics: readonly string[]): void;\n /** The topics something is subscribed to, sorted. */\n topics(): readonly PushTopic[];\n /** Runs whenever the set of subscribed topics changes. */\n onTopicsChange(listener: () => void): void;\n}\n\nexport function makePushRouter(): PushRouter {\n const byTopic = new Map<PushTopic, Set<PushListener>>();\n const connectListeners = new Set<() => void>();\n const resyncListeners = new Set<ResyncListener>();\n let isConnected = false;\n let topicsChanged = (): void => undefined;\n\n const subscribed = (topics: readonly string[]): PushTopic[] =>\n topics.filter((topic): topic is PushTopic =>\n byTopic.has(topic as PushTopic),\n );\n\n return {\n subscribe(topic, listener) {\n let listeners = byTopic.get(topic);\n if (listeners === undefined) {\n listeners = new Set();\n byTopic.set(topic, listeners);\n topicsChanged();\n }\n listeners.add(listener);\n return () => {\n const current = byTopic.get(topic);\n if (current?.delete(listener) !== true || current.size > 0) return;\n byTopic.delete(topic);\n topicsChanged();\n };\n },\n onConnect(listener) {\n connectListeners.add(listener);\n if (isConnected) listener();\n return () => {\n connectListeners.delete(listener);\n };\n },\n onResync(listener) {\n resyncListeners.add(listener);\n return () => {\n resyncListeners.delete(listener);\n };\n },\n deliver(topics, event) {\n const named = new Set(topics);\n const listeners = new Set<PushListener>();\n for (const [topic, topicListeners] of byTopic)\n if (named.has(topic))\n for (const listener of topicListeners) listeners.add(listener);\n for (const listener of listeners) listener(event);\n },\n connected() {\n isConnected = true;\n for (const listener of connectListeners) listener();\n },\n disconnected() {\n isConnected = false;\n },\n resync(topics) {\n const still = subscribed(topics);\n if (still.length === 0) return;\n for (const listener of resyncListeners) listener(still);\n },\n topics: () => [...byTopic.keys()].sort(),\n onTopicsChange(listener) {\n topicsChanged = listener;\n },\n };\n}\n"],"names":["makePushRouter","byTopic","Map","connectListeners","Set","resyncListeners","isConnected","topicsChanged","undefined","subscribed","topics","filter","topic","has","subscribe","listener","listeners","get","set","add","current","delete","size","onConnect","onResync","deliver","event","named","topicListeners","connected","disconnected","resync","still","length","keys","sort","onTopicsChange"],"mappings":"AA+BA,OAAO,SAASA;IACd,MAAMC,UAAU,IAAIC;IACpB,MAAMC,mBAAmB,IAAIC;IAC7B,MAAMC,kBAAkB,IAAID;IAC5B,IAAIE,cAAc;IAClB,IAAIC,gBAAgB,IAAYC;IAEhC,MAAMC,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AAM;mBAAIT,QAAQiC,IAAI;aAAG,CAACC,IAAI;QACtCC,gBAAerB,QAAQ;YACrBR,gBAAgBQ;QAClB;IACF;AACF"}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { type DomainEvent, type EntityId } from '@entifix/core';
|
|
2
|
+
import type { PushChannel, PushTopic } from './push-channel.js';
|
|
3
|
+
/**
|
|
4
|
+
* What one pushed event means for the cache.
|
|
5
|
+
*
|
|
6
|
+
* - A **snapshot** is the record as it now is, at a version: it replaces the
|
|
7
|
+
* cached record unless the cache already holds that version or a newer one.
|
|
8
|
+
* - A **hint** says something changed: the affected queries are read again.
|
|
9
|
+
*/
|
|
10
|
+
export type ReactiveCacheUpdate = {
|
|
11
|
+
readonly kind: 'snapshot';
|
|
12
|
+
readonly entity: string;
|
|
13
|
+
readonly id: EntityId;
|
|
14
|
+
readonly version: number;
|
|
15
|
+
readonly record: unknown;
|
|
16
|
+
} | {
|
|
17
|
+
readonly kind: 'hint';
|
|
18
|
+
readonly entity: string;
|
|
19
|
+
};
|
|
20
|
+
/** A record held in the cache by a snapshot, with the version it is at. */
|
|
21
|
+
export interface VersionedRecord<T = unknown> {
|
|
22
|
+
readonly version: number;
|
|
23
|
+
readonly record: T;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* The cache key of one record pushed as a snapshot. It sits under the entity's
|
|
27
|
+
* invalidation scope, so a hint for the entity reaches it too.
|
|
28
|
+
*/
|
|
29
|
+
export declare const entityRecordQueryKey: (entity: string, id: EntityId) => readonly ["entity", string, "record", string];
|
|
30
|
+
/**
|
|
31
|
+
* The default reading of a pushed event: an entity change is a hint, and an
|
|
32
|
+
* event naming an aggregate and a version whose `data` is a record is a
|
|
33
|
+
* snapshot of that aggregate. Anything else means nothing to the cache.
|
|
34
|
+
*/
|
|
35
|
+
export declare function readReactiveUpdate(event: DomainEvent): ReactiveCacheUpdate | undefined;
|
|
36
|
+
export interface UseReactiveCacheOptions {
|
|
37
|
+
/** Reads what an event means for the cache. Defaults to {@link readReactiveUpdate}. */
|
|
38
|
+
readonly read?: (event: DomainEvent) => ReactiveCacheUpdate | undefined;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Keeps the query cache in step with what the server pushes on `topics`.
|
|
42
|
+
*
|
|
43
|
+
* A snapshot is written into the cache, guarded by its version, and a hint
|
|
44
|
+
* invalidates the entity's queries. A `resync` for one of `topics` invalidates
|
|
45
|
+
* that entity's queries, since what changed while the stream was down cannot
|
|
46
|
+
* be replayed. Flow topics are left to the settlement of pending writes.
|
|
47
|
+
*/
|
|
48
|
+
export declare function useReactiveCache(channel: PushChannel, topics: readonly PushTopic[], { read }?: UseReactiveCacheOptions): void;
|
|
49
|
+
//# sourceMappingURL=use-reactive-cache.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-reactive-cache.d.ts","sourceRoot":"","sources":["../../src/reactive/use-reactive-cache.tsx"],"names":[],"mappings":"AAEA,OAAO,EACL,KAAK,WAAW,EAEhB,KAAK,QAAQ,EACd,MAAM,eAAe,CAAC;AAMvB,OAAO,KAAK,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAEhE;;;;;;GAMG;AACH,MAAM,MAAM,mBAAmB,GAC3B;IACE,QAAQ,CAAC,IAAI,EAAE,UAAU,CAAC;IAC1B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,EAAE,EAAE,QAAQ,CAAC;IACtB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;CAC1B,GACD;IAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAEvD,2EAA2E;AAC3E,MAAM,WAAW,eAAe,CAAC,CAAC,GAAG,OAAO;IAC1C,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;CACpB;AAED;;;GAGG;AACH,eAAO,MAAM,oBAAoB,GAAI,QAAQ,MAAM,EAAE,IAAI,QAAQ,kDACA,CAAC;AAOlE;;;;GAIG;AACH,wBAAgB,kBAAkB,CAChC,KAAK,EAAE,WAAW,GACjB,mBAAmB,GAAG,SAAS,CAgBjC;AA8BD,MAAM,WAAW,uBAAuB;IACtC,uFAAuF;IACvF,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC,KAAK,EAAE,WAAW,KAAK,mBAAmB,GAAG,SAAS,CAAC;CACzE;AAED;;;;;;;GAOG;AACH,wBAAgB,gBAAgB,CAC9B,OAAO,EAAE,WAAW,EACpB,MAAM,EAAE,SAAS,SAAS,EAAE,EAC5B,EAAE,IAAyB,EAAE,GAAE,uBAA4B,GAC1D,IAAI,CAmCN"}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { EntityChangeEventSchema } from '@entifix/core';
|
|
3
|
+
import { useQueryClient } from '@tanstack/react-query';
|
|
4
|
+
import { Schema } from 'effect';
|
|
5
|
+
import { useEffect, useRef } from 'react';
|
|
6
|
+
import { entityQueryScopeFor } from '../query/entity-query-key.js';
|
|
7
|
+
/**
|
|
8
|
+
* The cache key of one record pushed as a snapshot. It sits under the entity's
|
|
9
|
+
* invalidation scope, so a hint for the entity reaches it too.
|
|
10
|
+
*/ export const entityRecordQueryKey = (entity, id)=>[
|
|
11
|
+
...entityQueryScopeFor(entity),
|
|
12
|
+
'record',
|
|
13
|
+
String(id)
|
|
14
|
+
];
|
|
15
|
+
const isEntityChange = Schema.is(EntityChangeEventSchema);
|
|
16
|
+
const isRecord = (data)=>typeof data === 'object' && data !== null && !Array.isArray(data);
|
|
17
|
+
/**
|
|
18
|
+
* The default reading of a pushed event: an entity change is a hint, and an
|
|
19
|
+
* event naming an aggregate and a version whose `data` is a record is a
|
|
20
|
+
* snapshot of that aggregate. Anything else means nothing to the cache.
|
|
21
|
+
*/ export function readReactiveUpdate(event) {
|
|
22
|
+
if (isEntityChange(event.data)) return {
|
|
23
|
+
kind: 'hint',
|
|
24
|
+
entity: event.data.entity
|
|
25
|
+
};
|
|
26
|
+
if (event.aggregate !== undefined && event.version !== undefined && isRecord(event.data)) return {
|
|
27
|
+
kind: 'snapshot',
|
|
28
|
+
entity: event.aggregate.type,
|
|
29
|
+
id: event.aggregate.id,
|
|
30
|
+
version: event.version,
|
|
31
|
+
record: event.data
|
|
32
|
+
};
|
|
33
|
+
return undefined;
|
|
34
|
+
}
|
|
35
|
+
const apply = (queryClient, update)=>{
|
|
36
|
+
const scope = entityQueryScopeFor(update.entity);
|
|
37
|
+
if (update.kind === 'hint') {
|
|
38
|
+
void queryClient.invalidateQueries({
|
|
39
|
+
queryKey: scope
|
|
40
|
+
});
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
const key = entityRecordQueryKey(update.entity, update.id);
|
|
44
|
+
const cached = queryClient.getQueryData(key);
|
|
45
|
+
// A late frame for a version the cache already moved past changes nothing.
|
|
46
|
+
if (cached !== undefined && cached.version >= update.version) return;
|
|
47
|
+
queryClient.setQueryData(key, {
|
|
48
|
+
version: update.version,
|
|
49
|
+
record: update.record
|
|
50
|
+
});
|
|
51
|
+
// The lists that may show the record are read again; the record itself is
|
|
52
|
+
// what was just written.
|
|
53
|
+
void queryClient.invalidateQueries({
|
|
54
|
+
queryKey: scope,
|
|
55
|
+
predicate: (query)=>query.queryKey[2] !== 'record'
|
|
56
|
+
});
|
|
57
|
+
};
|
|
58
|
+
// The entity a topic belongs to; a flow topic belongs to none.
|
|
59
|
+
const entityOf = (topic)=>{
|
|
60
|
+
const [kind, key] = topic.split(':');
|
|
61
|
+
return kind === 'flow' ? undefined : key;
|
|
62
|
+
};
|
|
63
|
+
/**
|
|
64
|
+
* Keeps the query cache in step with what the server pushes on `topics`.
|
|
65
|
+
*
|
|
66
|
+
* A snapshot is written into the cache, guarded by its version, and a hint
|
|
67
|
+
* invalidates the entity's queries. A `resync` for one of `topics` invalidates
|
|
68
|
+
* that entity's queries, since what changed while the stream was down cannot
|
|
69
|
+
* be replayed. Flow topics are left to the settlement of pending writes.
|
|
70
|
+
*/ export function useReactiveCache(channel, topics, { read = readReactiveUpdate } = {}) {
|
|
71
|
+
const queryClient = useQueryClient();
|
|
72
|
+
// Keyed on the topics' value: a caller building the array inline would
|
|
73
|
+
// otherwise resubscribe on every render.
|
|
74
|
+
const key = [
|
|
75
|
+
...topics
|
|
76
|
+
].sort().join(' ');
|
|
77
|
+
// Held in a ref for the same reason: an inline `read` is a new function on
|
|
78
|
+
// every render.
|
|
79
|
+
const readRef = useRef(read);
|
|
80
|
+
useEffect(()=>{
|
|
81
|
+
readRef.current = read;
|
|
82
|
+
});
|
|
83
|
+
useEffect(()=>{
|
|
84
|
+
const own = key === '' ? [] : key.split(' ');
|
|
85
|
+
const onEvent = (event)=>{
|
|
86
|
+
const update = readRef.current(event);
|
|
87
|
+
if (update !== undefined) apply(queryClient, update);
|
|
88
|
+
};
|
|
89
|
+
const unsubscribes = own.map((topic)=>channel.subscribe(topic, onEvent));
|
|
90
|
+
unsubscribes.push(channel.onResync((resynced)=>{
|
|
91
|
+
const entities = new Set(resynced.filter((topic)=>own.includes(topic)).map(entityOf));
|
|
92
|
+
for (const entity of entities)if (entity !== undefined) void queryClient.invalidateQueries({
|
|
93
|
+
queryKey: entityQueryScopeFor(entity)
|
|
94
|
+
});
|
|
95
|
+
}));
|
|
96
|
+
return ()=>{
|
|
97
|
+
for (const unsubscribe of unsubscribes)unsubscribe();
|
|
98
|
+
};
|
|
99
|
+
}, [
|
|
100
|
+
channel,
|
|
101
|
+
key,
|
|
102
|
+
queryClient
|
|
103
|
+
]);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
//# sourceMappingURL=use-reactive-cache.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/reactive/use-reactive-cache.tsx"],"sourcesContent":["'use client';\n\nimport {\n type DomainEvent,\n EntityChangeEventSchema,\n type EntityId,\n} from '@entifix/core';\nimport { type QueryClient, useQueryClient } from '@tanstack/react-query';\nimport { Schema } from 'effect';\nimport { useEffect, useRef } from 'react';\n\nimport { entityQueryScopeFor } from '../query/entity-query-key.js';\nimport type { PushChannel, PushTopic } from './push-channel.js';\n\n/**\n * What one pushed event means for the cache.\n *\n * - A **snapshot** is the record as it now is, at a version: it replaces the\n * cached record unless the cache already holds that version or a newer one.\n * - A **hint** says something changed: the affected queries are read again.\n */\nexport type ReactiveCacheUpdate =\n | {\n readonly kind: 'snapshot';\n readonly entity: string;\n readonly id: EntityId;\n readonly version: number;\n readonly record: unknown;\n }\n | { readonly kind: 'hint'; readonly entity: string };\n\n/** A record held in the cache by a snapshot, with the version it is at. */\nexport interface VersionedRecord<T = unknown> {\n readonly version: number;\n readonly record: T;\n}\n\n/**\n * The cache key of one record pushed as a snapshot. It sits under the entity's\n * invalidation scope, so a hint for the entity reaches it too.\n */\nexport const entityRecordQueryKey = (entity: string, id: EntityId) =>\n [...entityQueryScopeFor(entity), 'record', String(id)] as const;\n\nconst isEntityChange = Schema.is(EntityChangeEventSchema);\n\nconst isRecord = (data: unknown): data is Record<string, unknown> =>\n typeof data === 'object' && data !== null && !Array.isArray(data);\n\n/**\n * The default reading of a pushed event: an entity change is a hint, and an\n * event naming an aggregate and a version whose `data` is a record is a\n * snapshot of that aggregate. Anything else means nothing to the cache.\n */\nexport function readReactiveUpdate(\n event: DomainEvent,\n): ReactiveCacheUpdate | undefined {\n if (isEntityChange(event.data))\n return { kind: 'hint', entity: event.data.entity };\n if (\n event.aggregate !== undefined &&\n event.version !== undefined &&\n isRecord(event.data)\n )\n return {\n kind: 'snapshot',\n entity: event.aggregate.type,\n id: event.aggregate.id,\n version: event.version,\n record: event.data,\n };\n return undefined;\n}\n\nconst apply = (queryClient: QueryClient, update: ReactiveCacheUpdate): void => {\n const scope = entityQueryScopeFor(update.entity);\n if (update.kind === 'hint') {\n void queryClient.invalidateQueries({ queryKey: scope });\n return;\n }\n const key = entityRecordQueryKey(update.entity, update.id);\n const cached = queryClient.getQueryData<VersionedRecord>(key);\n // A late frame for a version the cache already moved past changes nothing.\n if (cached !== undefined && cached.version >= update.version) return;\n queryClient.setQueryData<VersionedRecord>(key, {\n version: update.version,\n record: update.record,\n });\n // The lists that may show the record are read again; the record itself is\n // what was just written.\n void queryClient.invalidateQueries({\n queryKey: scope,\n predicate: query => query.queryKey[2] !== 'record',\n });\n};\n\n// The entity a topic belongs to; a flow topic belongs to none.\nconst entityOf = (topic: PushTopic): string | undefined => {\n const [kind, key] = topic.split(':');\n return kind === 'flow' ? undefined : key;\n};\n\nexport interface UseReactiveCacheOptions {\n /** Reads what an event means for the cache. Defaults to {@link readReactiveUpdate}. */\n readonly read?: (event: DomainEvent) => ReactiveCacheUpdate | undefined;\n}\n\n/**\n * Keeps the query cache in step with what the server pushes on `topics`.\n *\n * A snapshot is written into the cache, guarded by its version, and a hint\n * invalidates the entity's queries. A `resync` for one of `topics` invalidates\n * that entity's queries, since what changed while the stream was down cannot\n * be replayed. Flow topics are left to the settlement of pending writes.\n */\nexport function useReactiveCache(\n channel: PushChannel,\n topics: readonly PushTopic[],\n { read = readReactiveUpdate }: UseReactiveCacheOptions = {},\n): void {\n const queryClient = useQueryClient();\n // Keyed on the topics' value: a caller building the array inline would\n // otherwise resubscribe on every render.\n const key = [...topics].sort().join(' ');\n // Held in a ref for the same reason: an inline `read` is a new function on\n // every render.\n const readRef = useRef(read);\n useEffect(() => {\n readRef.current = read;\n });\n\n useEffect(() => {\n const own = key === '' ? [] : (key.split(' ') as PushTopic[]);\n const onEvent = (event: DomainEvent) => {\n const update = readRef.current(event);\n if (update !== undefined) apply(queryClient, update);\n };\n const unsubscribes = own.map(topic => channel.subscribe(topic, onEvent));\n unsubscribes.push(\n channel.onResync(resynced => {\n const entities = new Set(\n resynced.filter(topic => own.includes(topic)).map(entityOf),\n );\n for (const entity of entities)\n if (entity !== undefined)\n void queryClient.invalidateQueries({\n queryKey: entityQueryScopeFor(entity),\n });\n }),\n );\n return () => {\n for (const unsubscribe of unsubscribes) unsubscribe();\n };\n }, [channel, key, queryClient]);\n}\n"],"names":["EntityChangeEventSchema","useQueryClient","Schema","useEffect","useRef","entityQueryScopeFor","entityRecordQueryKey","entity","id","String","isEntityChange","is","isRecord","data","Array","isArray","readReactiveUpdate","event","kind","aggregate","undefined","version","type","record","apply","queryClient","update","scope","invalidateQueries","queryKey","key","cached","getQueryData","setQueryData","predicate","query","entityOf","topic","split","useReactiveCache","channel","topics","read","sort","join","readRef","current","own","onEvent","unsubscribes","map","subscribe","push","onResync","resynced","entities","Set","filter","includes","unsubscribe"],"mappings":"AAAA;AAEA,SAEEA,uBAAuB,QAElB,gBAAgB;AACvB,SAA2BC,cAAc,QAAQ,wBAAwB;AACzE,SAASC,MAAM,QAAQ,SAAS;AAChC,SAASC,SAAS,EAAEC,MAAM,QAAQ,QAAQ;AAE1C,SAASC,mBAAmB,QAAQ,+BAA+B;AA0BnE;;;CAGC,GACD,OAAO,MAAMC,uBAAuB,CAACC,QAAgBC,KACnD;WAAIH,oBAAoBE;QAAS;QAAUE,OAAOD;KAAI,CAAU;AAElE,MAAME,iBAAiBR,OAAOS,EAAE,CAACX;AAEjC,MAAMY,WAAW,CAACC,OAChB,OAAOA,SAAS,YAAYA,SAAS,QAAQ,CAACC,MAAMC,OAAO,CAACF;AAE9D;;;;CAIC,GACD,OAAO,SAASG,mBACdC,KAAkB;IAElB,IAAIP,eAAeO,MAAMJ,IAAI,GAC3B,OAAO;QAAEK,MAAM;QAAQX,QAAQU,MAAMJ,IAAI,CAACN,MAAM;IAAC;IACnD,IACEU,MAAME,SAAS,KAAKC,aACpBH,MAAMI,OAAO,KAAKD,aAClBR,SAASK,MAAMJ,IAAI,GAEnB,OAAO;QACLK,MAAM;QACNX,QAAQU,MAAME,SAAS,CAACG,IAAI;QAC5Bd,IAAIS,MAAME,SAAS,CAACX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