@cplieger/sse 1.0.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/LICENSE +202 -0
- package/README.md +77 -0
- package/THIRD_PARTY_NOTICES.md +37 -0
- package/jsr.json +12 -0
- package/package.json +71 -0
- package/src/digest.ts +248 -0
- package/src/fold.ts +225 -0
- package/src/index.ts +102 -0
- package/src/lifecycle.ts +48 -0
- package/src/online.ts +98 -0
- package/src/parser.ts +193 -0
- package/src/port-protocol.ts +100 -0
- package/src/reducer.ts +548 -0
- package/src/stream.ts +737 -0
- package/src/tab.ts +458 -0
- package/src/timing.ts +98 -0
- package/src/transport.ts +278 -0
- package/src/versions.ts +134 -0
- package/src/visibility.ts +137 -0
- package/src/wire.ts +156 -0
- package/src/worker.ts +480 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
202
|
+
|
package/README.md
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
# @cplieger/sse
|
|
2
|
+
|
|
3
|
+
> A Server-Sent-Events client that resumes exactly where it stopped, notices a dead stream, and reconciles after a sleep.
|
|
4
|
+
|
|
5
|
+
The TypeScript half of [cplieger/sse](https://github.com/cplieger/sse), speaking the wire the Go `sse` package serves: every frame carries an `epoch:offset` cursor, every connection opens with a hello that says whether that cursor was honoured, and the client turns both into a projection an application can trust across a page hide, a phone lock or a network change. A native `EventSource` cannot set a request header, cannot tell a silent stream from an idle one, and reconnects on its own schedule with whatever `Last-Event-ID` it last saw; this client owns the connection over `fetch` and `ReadableStream` instead, presents the cursor it holds, measures liveness on bytes, closes a hidden tab's stream after a minute and reopens it on return, backs off with full jitter, and holds incoming frames while the application asks the server what changed. It has no runtime dependencies, and the DOM readers (`document.visibilityState`, `navigator.onLine`) are injectable, so the same runtime runs in Node against the Go test fixture.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npx jsr add @cplieger/sse
|
|
11
|
+
# or
|
|
12
|
+
npm i @cplieger/sse
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Usage
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
import { createStream, createVersionMap } from "@cplieger/sse";
|
|
19
|
+
|
|
20
|
+
const versions = createVersionMap();
|
|
21
|
+
|
|
22
|
+
const stream = createStream({
|
|
23
|
+
url: "/api/events",
|
|
24
|
+
headers: { "SSE-Client": profileTag },
|
|
25
|
+
alive: { url: "/api/alive" },
|
|
26
|
+
versions,
|
|
27
|
+
onFrame: (frame) => {
|
|
28
|
+
applyToStore(frame.type, frame.data);
|
|
29
|
+
},
|
|
30
|
+
revalidate: async (ctx) => {
|
|
31
|
+
// Runs once per hello and once per wake, never concurrently. Every fetch in
|
|
32
|
+
// here takes ctx.signal; ctx.full means the map was cleared, so skip the digest.
|
|
33
|
+
await reconcile(versions.snapshot(), ctx);
|
|
34
|
+
},
|
|
35
|
+
onLifecycle: (ev) => {
|
|
36
|
+
log.debug("sse", ev);
|
|
37
|
+
},
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
stream.start();
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
The first frame of every connection is a hello: it names the server epoch, the ring's floor and head, the keepalive interval and event name, and whether the cursor the client presented was resumed; a hello whose `wire` is outside `[minWire, maxWire]` (both default to the package's `WIRE`) ends the connection with a `wire_unsupported` record and keeps the cursor.
|
|
44
|
+
|
|
45
|
+
The client keeps its cursor as `epoch:offset`, presents it as `Last-Event-ID` on every connect, and advances it only as frames are delivered to `onFrame`, so a reconnect after a gap either replays exactly the missed frames or reports through the hello that the gap could not be covered, and the application reconciles instead of trusting the replay.
|
|
46
|
+
|
|
47
|
+
While `revalidate` runs, incoming frames are held and delivered in order once it settles; runs are single-flight, a second cause queues at most one more run, and a held queue past 2000 frames or 64 MiB ends the connection so the next connect resumes from the cursor instead.
|
|
48
|
+
|
|
49
|
+
With `alive` set, every keepalive (or every `everyBeats`-th) is acknowledged with a `POST` to that URL carrying the stream's headers, so a server-side presence table keyed on `SSE-Client` sees which clients are still reading; a failed acknowledgement is reported as an `alive_ack` record.
|
|
50
|
+
|
|
51
|
+
`createWorkerHost` runs one stream per browser profile inside a `SharedWorker`, and `attachToWorker` connects each tab to it over a `MessagePort`, folding the tabs' visibility and network readings into that one connection; where `SharedWorker` is absent or the worker never answers, the tab falls back to its own stream and reports the switch. The `fallback` option returns a `TabFallback`: the `createStream` result together with the `versions` map and the `headers` record it was built on, which is what lets the `TabAttachment` work the same in both modes. `observe(subject, version, epoch)` reports a stamp the tab applied, into the host's version map or the fallback's; `reconnect({ resetCursor })` reconnects the stream the tab is attached to; `setTag(tag)` presents a new `SSE-Client` value with one reconnect, written into the host's headers or the fallback's; and `detach("logout")` ends the profile's stream. The tab writes its `tag` into the fallback's headers before the first connect, so a consumer never fills `SSE-Client` itself.
|
|
52
|
+
|
|
53
|
+
The host presents the first non-empty tag a tab attaches with and replaces it, reconnecting once, when a later attach or `setTag` carries a different one; the empty tag is ignored.
|
|
54
|
+
|
|
55
|
+
The host's `revalidate(ctx, tabs)` body performs one digest for the profile and fans the verdict to every tab through `tabs.run(ctx, { changed, removed })`, so each tab's `revalidate` receives a `TabRevalidateContext` carrying `changed` and `removed` beside its own `signal`. A `state` message reaches a tab before the `lifecycle` record of the same transition, so `attachment.state()` is current inside the handler, and a tab attaching to a live stream receives `state` and then a `tab_attached` record naming that state.
|
|
56
|
+
|
|
57
|
+
The package typechecks under `lib: ["ESNext", "WebWorker"]` as well as under the DOM lib (`tsconfig.worker.json` is the check), so a consumer's worker entry can import `createWorkerHost` from a worker-only program: the DOM visibility and online sources read `document` and `window` through `globalThis` and are inert where they are absent.
|
|
58
|
+
|
|
59
|
+
`onLifecycle` receives every state change and diagnostic as one `LifecycleEvent` record (`state`, `hello`, `watchdog`, `reset`, `revalidate`, `hidden_closed`, `alive_ack`, `worker_dead` and the rest of the union), which is the surface to log and to count.
|
|
60
|
+
|
|
61
|
+
## Browser floor
|
|
62
|
+
|
|
63
|
+
`Response.body` as a readable stream (Firefox 65, Chrome 43, Safari 10.1), `AbortSignal.reason` (Firefox 97, Chrome 98, Safari 15.4), `visibilitychange` (Chrome 62, Firefox 56, Safari 14.1), `pagehide` and `pageshow`, and `BigInt` (Chrome 67, Firefox 68, Safari 14). `AbortSignal.any` is not used; two signals are composed by hand. `SharedWorker` is needed by the worker host only and is not part of the floor: where it is absent (Chrome for Android before 148, Samsung Internet) the tab runs its own stream through the fallback.
|
|
64
|
+
|
|
65
|
+
## Full documentation
|
|
66
|
+
|
|
67
|
+
The Go server API, the hub options, the hello's verdicts, the digest and the presence hook are in the [repository README](https://github.com/cplieger/sse#readme). The shared timing constants both halves pin are in the repository's `timing.json`.
|
|
68
|
+
|
|
69
|
+
## Disclaimer
|
|
70
|
+
|
|
71
|
+
This project is built with care and follows security best practices, but it is intended for personal / self-hosted use. No guarantees of fitness for production environments. Use at your own risk.
|
|
72
|
+
|
|
73
|
+
This project was built with AI-assisted tooling using [Claude](https://claude.com), [GPT](https://openai.com), and [Kiro](https://kiro.dev). The human maintainer defines architecture, supervises implementation, and makes all final decisions.
|
|
74
|
+
|
|
75
|
+
## License
|
|
76
|
+
|
|
77
|
+
Apache-2.0. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
# Third-party notices
|
|
2
|
+
|
|
3
|
+
This package has no runtime dependencies. The parse loop in `src/parser.ts` follows the structure of `eventsource-parser`, whose license is reproduced below.
|
|
4
|
+
|
|
5
|
+
Three further designs are followed without any of their code being included; each is named at the line that follows it:
|
|
6
|
+
|
|
7
|
+
- The silence watchdog in `src/timing.ts` (`max(3 keepalive beats, 15 s)`) follows [Yaffle/EventSource](https://github.com/Yaffle/EventSource).
|
|
8
|
+
- The resume handshake's structural pessimism in `src/wire.ts` (only `resumed === true` resumes; every other verdict reconciles), and the matching cursor and verdict shape on the Go side, follow [Centrifugo](https://github.com/centrifugal/centrifugo)'s recovery handshake.
|
|
9
|
+
- The epoch-bound version map in `src/versions.ts` follows IMAP CONDSTORE ([RFC 7162](https://www.rfc-editor.org/rfc/rfc7162)): a change of the server's epoch discards every cached version, as a `UIDVALIDITY` change discards cached mod-sequences.
|
|
10
|
+
|
|
11
|
+
## eventsource-parser
|
|
12
|
+
|
|
13
|
+
<https://github.com/rexxars/eventsource-parser>
|
|
14
|
+
|
|
15
|
+
```text
|
|
16
|
+
MIT License
|
|
17
|
+
|
|
18
|
+
Copyright (c) 2026 Espen Hovlandsdal <espen@hovlandsdal.com>
|
|
19
|
+
|
|
20
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
21
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
22
|
+
in the Software without restriction, including without limitation the rights
|
|
23
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
24
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
25
|
+
furnished to do so, subject to the following conditions:
|
|
26
|
+
|
|
27
|
+
The above copyright notice and this permission notice shall be included in all
|
|
28
|
+
copies or substantial portions of the Software.
|
|
29
|
+
|
|
30
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
31
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
32
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
33
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
34
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
35
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
36
|
+
SOFTWARE.
|
|
37
|
+
```
|
package/jsr.json
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@cplieger/sse",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"license": "Apache-2.0",
|
|
5
|
+
"exports": {
|
|
6
|
+
".": "./src/index.ts"
|
|
7
|
+
},
|
|
8
|
+
"publish": {
|
|
9
|
+
"include": ["LICENSE", "README.md", "THIRD_PARTY_NOTICES.md", "src/**/*.ts", "jsr.json"],
|
|
10
|
+
"exclude": ["src/**/*.test.ts", "src/**/*-setup.ts", "src/**/test-helpers/**"]
|
|
11
|
+
}
|
|
12
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@cplieger/sse",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Server-Sent Events hub and client that resume from an exact cursor and reconcile after sleep",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/cplieger/sse.git",
|
|
11
|
+
"directory": "web"
|
|
12
|
+
},
|
|
13
|
+
"homepage": "https://github.com/cplieger/sse",
|
|
14
|
+
"bugs": {
|
|
15
|
+
"url": "https://github.com/cplieger/sse/issues"
|
|
16
|
+
},
|
|
17
|
+
"author": "cplieger <917744+cplieger@users.noreply.github.com>",
|
|
18
|
+
"keywords": [
|
|
19
|
+
"sse",
|
|
20
|
+
"server-sent-events",
|
|
21
|
+
"eventsource",
|
|
22
|
+
"reconnect",
|
|
23
|
+
"resume",
|
|
24
|
+
"sharedworker",
|
|
25
|
+
"typescript"
|
|
26
|
+
],
|
|
27
|
+
"exports": {
|
|
28
|
+
".": "./src/index.ts"
|
|
29
|
+
},
|
|
30
|
+
"files": [
|
|
31
|
+
"src/",
|
|
32
|
+
"!src/**/*.test.ts",
|
|
33
|
+
"!src/**/*-setup.ts",
|
|
34
|
+
"!src/**/test-helpers/**",
|
|
35
|
+
"!src/**/*.golden.json",
|
|
36
|
+
"jsr.json",
|
|
37
|
+
"THIRD_PARTY_NOTICES.md"
|
|
38
|
+
],
|
|
39
|
+
"sseFixture": "./ssetest/cmd",
|
|
40
|
+
"browserEngines": [
|
|
41
|
+
"firefox",
|
|
42
|
+
"webkit"
|
|
43
|
+
],
|
|
44
|
+
"scripts": {
|
|
45
|
+
"typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.worker.json && tsc -p tsconfig.tests.json",
|
|
46
|
+
"typecheck:tests": "tsc -p tsconfig.tests.json",
|
|
47
|
+
"test": "vitest --run",
|
|
48
|
+
"test:browser": "vitest --run --project browser",
|
|
49
|
+
"lint:eslint": "eslint .",
|
|
50
|
+
"lint:prettier": "prettier --check ."
|
|
51
|
+
},
|
|
52
|
+
"devDependencies": {
|
|
53
|
+
"@eslint/js": "10.0.1",
|
|
54
|
+
"@types/node": "24.13.4",
|
|
55
|
+
"@typescript/native": "npm:typescript@7.0.2",
|
|
56
|
+
"@vitest/browser": "5.0.0",
|
|
57
|
+
"@vitest/browser-playwright": "5.0.0",
|
|
58
|
+
"@vitest/coverage-v8": "5.0.0",
|
|
59
|
+
"eslint": "10.10.0",
|
|
60
|
+
"eventsource-parser": "4.1.0",
|
|
61
|
+
"fast-check": "4.9.0",
|
|
62
|
+
"playwright": "1.63.0",
|
|
63
|
+
"prettier": "3.9.6",
|
|
64
|
+
"typescript": "npm:@typescript/typescript6@6.0.2",
|
|
65
|
+
"typescript-eslint": "8.70.0",
|
|
66
|
+
"vitest": "5.0.0"
|
|
67
|
+
},
|
|
68
|
+
"overrides": {
|
|
69
|
+
"qs": "^6.15.2"
|
|
70
|
+
}
|
|
71
|
+
}
|
package/src/digest.ts
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
import { DEFAULT_TIMING, DIGEST_MAX_SUBJECTS } from "./timing.js";
|
|
2
|
+
import type { Held, Subject } from "./versions.js";
|
|
3
|
+
import { compareOffset } from "./wire.js";
|
|
4
|
+
|
|
5
|
+
/** A subject the server reports at a version other than the presented one: a fetch instruction. */
|
|
6
|
+
export type State = Held;
|
|
7
|
+
|
|
8
|
+
/** A subject the server no longer answers for. */
|
|
9
|
+
export interface Removed extends Subject {
|
|
10
|
+
readonly reason: "gone" | "forbidden";
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export type DigestResult =
|
|
14
|
+
| { kind: "must_refetch"; epoch: string; head: string }
|
|
15
|
+
| { kind: "ok"; epoch: string; head: string; changed: State[]; removed: Removed[] };
|
|
16
|
+
|
|
17
|
+
export interface DigestSnapshot {
|
|
18
|
+
readonly epoch: string | null;
|
|
19
|
+
readonly held: readonly Held[];
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface DigestClient {
|
|
23
|
+
/** Asks the server which held versions moved; the optional signal cancels every POST. */
|
|
24
|
+
check(snapshot: DigestSnapshot, signal?: AbortSignal): Promise<DigestResult>;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface DigestClientOptions {
|
|
28
|
+
readonly url: string;
|
|
29
|
+
readonly fetch?: typeof fetch;
|
|
30
|
+
readonly headers?: Record<string, string>;
|
|
31
|
+
readonly timeoutMs?: number;
|
|
32
|
+
readonly maxSubjects?: number;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** A digest POST answered with a status other than 200; `status` lets a host recognise a 401. */
|
|
36
|
+
export class DigestStatusError extends Error {
|
|
37
|
+
readonly status: number;
|
|
38
|
+
|
|
39
|
+
constructor(status: number) {
|
|
40
|
+
super(`digest: unexpected status ${String(status)}`);
|
|
41
|
+
this.name = "DigestStatusError";
|
|
42
|
+
this.status = status;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const EPOCH_RE = /^[0-9a-f]{16}$/;
|
|
47
|
+
const OFFSET_RE = /^(0|[1-9][0-9]*)$/;
|
|
48
|
+
|
|
49
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
50
|
+
return typeof value === "object" && value !== null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function isOffset(value: unknown): value is string {
|
|
54
|
+
return (
|
|
55
|
+
typeof value === "string" &&
|
|
56
|
+
OFFSET_RE.test(value) &&
|
|
57
|
+
compareOffset(value, "9007199254740991") <= 0
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function subjectKey(subject: Subject): string {
|
|
62
|
+
return `${subject.kind}\0${subject.ref}`;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
interface Position {
|
|
66
|
+
readonly epoch: string;
|
|
67
|
+
readonly head: string;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
type BatchAnswer =
|
|
71
|
+
| { kind: "must_refetch"; position: Position }
|
|
72
|
+
| { kind: "ok"; position: Position; changed: State[]; removed: Removed[] };
|
|
73
|
+
|
|
74
|
+
/** Reads the position; null when the body is not even a positioned digest answer. */
|
|
75
|
+
function readPosition(body: unknown): Position | null {
|
|
76
|
+
if (!isRecord(body)) {
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
const epoch = body["epoch"];
|
|
80
|
+
const head = body["head"];
|
|
81
|
+
if (typeof epoch !== "string" || !EPOCH_RE.test(epoch) || !isOffset(head)) {
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
return { epoch, head };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function readAnswer(
|
|
88
|
+
body: Record<string, unknown>,
|
|
89
|
+
position: Position,
|
|
90
|
+
batch: readonly Held[],
|
|
91
|
+
): BatchAnswer {
|
|
92
|
+
const refuse: BatchAnswer = { kind: "must_refetch", position };
|
|
93
|
+
if (body["must_refetch"] === true) {
|
|
94
|
+
return refuse;
|
|
95
|
+
}
|
|
96
|
+
if (body["must_refetch"] !== false || body["checked"] !== batch.length) {
|
|
97
|
+
return refuse;
|
|
98
|
+
}
|
|
99
|
+
const changedRaw = body["changed"] ?? [];
|
|
100
|
+
const removedRaw = body["removed"] ?? [];
|
|
101
|
+
if (!Array.isArray(changedRaw) || !Array.isArray(removedRaw)) {
|
|
102
|
+
return refuse;
|
|
103
|
+
}
|
|
104
|
+
const requested = new Set(batch.map(subjectKey));
|
|
105
|
+
const seen = new Set<string>();
|
|
106
|
+
const changed: State[] = [];
|
|
107
|
+
const removed: Removed[] = [];
|
|
108
|
+
for (const entry of changedRaw as unknown[]) {
|
|
109
|
+
if (!isRecord(entry)) {
|
|
110
|
+
return refuse;
|
|
111
|
+
}
|
|
112
|
+
const kind = entry["kind"];
|
|
113
|
+
const ref = entry["ref"];
|
|
114
|
+
const version = entry["version"];
|
|
115
|
+
if (typeof kind !== "string" || typeof ref !== "string" || typeof version !== "string") {
|
|
116
|
+
return refuse;
|
|
117
|
+
}
|
|
118
|
+
const k = subjectKey({ kind, ref });
|
|
119
|
+
if (!requested.has(k) || seen.has(k)) {
|
|
120
|
+
return refuse;
|
|
121
|
+
}
|
|
122
|
+
seen.add(k);
|
|
123
|
+
changed.push({ kind, ref, version });
|
|
124
|
+
}
|
|
125
|
+
for (const entry of removedRaw as unknown[]) {
|
|
126
|
+
if (!isRecord(entry)) {
|
|
127
|
+
return refuse;
|
|
128
|
+
}
|
|
129
|
+
const kind = entry["kind"];
|
|
130
|
+
const ref = entry["ref"];
|
|
131
|
+
const reason = entry["reason"];
|
|
132
|
+
if (typeof kind !== "string" || typeof ref !== "string") {
|
|
133
|
+
return refuse;
|
|
134
|
+
}
|
|
135
|
+
if (reason !== "gone" && reason !== "forbidden") {
|
|
136
|
+
return refuse;
|
|
137
|
+
}
|
|
138
|
+
const k = subjectKey({ kind, ref });
|
|
139
|
+
if (!requested.has(k) || seen.has(k)) {
|
|
140
|
+
return refuse;
|
|
141
|
+
}
|
|
142
|
+
seen.add(k);
|
|
143
|
+
removed.push({ kind, ref, reason });
|
|
144
|
+
}
|
|
145
|
+
return { kind: "ok", position, changed, removed };
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
interface Deadline {
|
|
149
|
+
readonly signal: AbortSignal;
|
|
150
|
+
release(): void;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function composeSignal(signal: AbortSignal | undefined, timeoutMs: number): Deadline {
|
|
154
|
+
const controller = new AbortController();
|
|
155
|
+
if (signal !== undefined) {
|
|
156
|
+
if (signal.aborted) {
|
|
157
|
+
controller.abort(signal.reason);
|
|
158
|
+
} else {
|
|
159
|
+
signal.addEventListener(
|
|
160
|
+
"abort",
|
|
161
|
+
() => {
|
|
162
|
+
controller.abort(signal.reason);
|
|
163
|
+
},
|
|
164
|
+
{ once: true, signal: controller.signal },
|
|
165
|
+
);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
const timer = setTimeout(() => {
|
|
169
|
+
controller.abort(new DOMException("digest request timed out", "TimeoutError"));
|
|
170
|
+
}, timeoutMs);
|
|
171
|
+
return {
|
|
172
|
+
signal: controller.signal,
|
|
173
|
+
release: () => {
|
|
174
|
+
clearTimeout(timer);
|
|
175
|
+
},
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Creates the client of the state-digest route. It never touches a version map. */
|
|
180
|
+
export function createDigestClient(opts: DigestClientOptions): DigestClient {
|
|
181
|
+
const doFetch: typeof fetch = opts.fetch ?? ((input, init) => globalThis.fetch(input, init));
|
|
182
|
+
const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMING.digestTimeoutMs;
|
|
183
|
+
const maxSubjects = opts.maxSubjects ?? DIGEST_MAX_SUBJECTS;
|
|
184
|
+
const headers: Record<string, string> = {
|
|
185
|
+
...opts.headers,
|
|
186
|
+
Accept: "application/json",
|
|
187
|
+
"Content-Type": "application/json",
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
async function post(
|
|
191
|
+
epoch: string | null,
|
|
192
|
+
batch: readonly Held[],
|
|
193
|
+
signal: AbortSignal | undefined,
|
|
194
|
+
): Promise<BatchAnswer> {
|
|
195
|
+
const body: Record<string, unknown> = { subjects: batch };
|
|
196
|
+
if (epoch !== null) {
|
|
197
|
+
body["epoch"] = epoch;
|
|
198
|
+
}
|
|
199
|
+
const deadline = composeSignal(signal, timeoutMs);
|
|
200
|
+
let response: Response;
|
|
201
|
+
try {
|
|
202
|
+
response = await doFetch(opts.url, {
|
|
203
|
+
method: "POST",
|
|
204
|
+
headers,
|
|
205
|
+
body: JSON.stringify(body),
|
|
206
|
+
credentials: "same-origin",
|
|
207
|
+
cache: "no-store",
|
|
208
|
+
signal: deadline.signal,
|
|
209
|
+
});
|
|
210
|
+
} finally {
|
|
211
|
+
deadline.release();
|
|
212
|
+
}
|
|
213
|
+
if (response.status !== 200) {
|
|
214
|
+
throw new DigestStatusError(response.status);
|
|
215
|
+
}
|
|
216
|
+
const parsed: unknown = await response.json();
|
|
217
|
+
const position = readPosition(parsed);
|
|
218
|
+
if (position === null || !isRecord(parsed)) {
|
|
219
|
+
throw new Error("digest: malformed response");
|
|
220
|
+
}
|
|
221
|
+
return readAnswer(parsed, position, batch);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
return {
|
|
225
|
+
async check(snapshot, signal) {
|
|
226
|
+
const batches: Held[][] = [];
|
|
227
|
+
for (let i = 0; i < snapshot.held.length; i += maxSubjects) {
|
|
228
|
+
batches.push(snapshot.held.slice(i, i + maxSubjects));
|
|
229
|
+
}
|
|
230
|
+
const [first = [], ...rest] = batches;
|
|
231
|
+
const changed: State[] = [];
|
|
232
|
+
const removed: Removed[] = [];
|
|
233
|
+
let answer = await post(snapshot.epoch, first, signal);
|
|
234
|
+
for (let i = 0; ; i++) {
|
|
235
|
+
if (answer.kind === "must_refetch") {
|
|
236
|
+
return { kind: "must_refetch", ...answer.position };
|
|
237
|
+
}
|
|
238
|
+
changed.push(...answer.changed);
|
|
239
|
+
removed.push(...answer.removed);
|
|
240
|
+
const batch = rest[i];
|
|
241
|
+
if (batch === undefined) {
|
|
242
|
+
return { kind: "ok", ...answer.position, changed, removed };
|
|
243
|
+
}
|
|
244
|
+
answer = await post(snapshot.epoch, batch, signal);
|
|
245
|
+
}
|
|
246
|
+
},
|
|
247
|
+
};
|
|
248
|
+
}
|