effect-cloudflare-webrtc 0.0.0-stage → 0.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/README.md +439 -2
- package/dist/AudioSink-BybkMP2y.d.ts +54 -0
- package/dist/Readable-CJPSx6Uq.js +65 -0
- package/dist/Readable-CJPSx6Uq.js.map +1 -0
- package/dist/Realtime-B5OIHlLR.d.ts +129 -0
- package/dist/Realtime-B6TjV8su.js +195 -0
- package/dist/Realtime-B6TjV8su.js.map +1 -0
- package/dist/RealtimeClient-Bl0Tun5r.js +2488 -0
- package/dist/RealtimeClient-Bl0Tun5r.js.map +1 -0
- package/dist/RealtimeClient-ESFO5vfF.d.ts +412 -0
- package/dist/RealtimeClient-K7oKgsB9.d.ts +1000 -0
- package/dist/chunk-pbuEa-1d.js +13 -0
- package/dist/client/index.d.ts +275 -0
- package/dist/client/index.js +493 -0
- package/dist/client/index.js.map +1 -0
- package/dist/effect/client/index.d.ts +434 -0
- package/dist/effect/client/index.js +2 -0
- package/dist/effect/server/index.d.ts +2 -0
- package/dist/effect/server/index.js +2 -0
- package/dist/react/index.d.ts +44 -0
- package/dist/react/index.js +107 -0
- package/dist/react/index.js.map +1 -0
- package/dist/server/index.d.ts +23 -0
- package/dist/server/index.js +12 -0
- package/dist/server/index.js.map +1 -0
- package/package.json +92 -4
package/README.md
CHANGED
|
@@ -1,3 +1,440 @@
|
|
|
1
|
-
|
|
1
|
+
<!-- Made from the README of the repository by scripts/readme.ts. Edit that file. -->
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
# effect-cloudflare-webrtc
|
|
4
|
+
|
|
5
|
+
`effect-cloudflare-webrtc` lets browsers send and receive audio and video
|
|
6
|
+
through the [Cloudflare Realtime SFU](https://developers.cloudflare.com/realtime/sfu/).
|
|
7
|
+
It handles WebRTC negotiation, reconnects, and device selection with
|
|
8
|
+
fallbacks. You can mute the microphone or turn off the camera without
|
|
9
|
+
interrupting the call.
|
|
10
|
+
|
|
11
|
+
**Your app decides who sees and hears whom.** Each browser can pull
|
|
12
|
+
individual tracks, such as someone's microphone without their camera.
|
|
13
|
+
You can build rooms, one-to-one calls, or broadcasts.
|
|
14
|
+
|
|
15
|
+
You can also skip rooms entirely. In a game with proximity voice chat,
|
|
16
|
+
each player hears only nearby players. As players move, your app changes
|
|
17
|
+
which microphone tracks each browser pulls.
|
|
18
|
+
|
|
19
|
+
Suppose Alice shares her camera with Bob. To push or pull a track, each
|
|
20
|
+
browser sends setup requests through your server.
|
|
21
|
+
|
|
22
|
+
**Either browser → your server → Cloudflare Realtime API**
|
|
23
|
+
|
|
24
|
+
On your server, [`routeRealtimeRequest`](#server) adds the SFU app token
|
|
25
|
+
and forwards each request. The token stays on the server.
|
|
26
|
+
|
|
27
|
+
The video and the information Bob needs to find it take separate paths.
|
|
28
|
+
|
|
29
|
+
```mermaid
|
|
30
|
+
flowchart LR
|
|
31
|
+
A["Alice's browser"] -->|Video| S["Cloudflare Realtime SFU"]
|
|
32
|
+
S -->|Video| B["Bob's browser"]
|
|
33
|
+
A -.->|Track metadata| D["Your app"]
|
|
34
|
+
D -.->|Track metadata| B
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Alice sends her video to the SFU once, even if many people watch. Your app
|
|
38
|
+
passes the track metadata to Bob, for example over a WebSocket. Bob uses
|
|
39
|
+
that metadata to pull the video from the SFU.
|
|
40
|
+
|
|
41
|
+
## Install
|
|
42
|
+
|
|
43
|
+
```sh
|
|
44
|
+
npm install effect-cloudflare-webrtc effect
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
`effect` (version 4) is a peer dependency, also for the plain client API.
|
|
48
|
+
|
|
49
|
+
The package is not on npm yet. Until it is, build it from this repository
|
|
50
|
+
and install the tarball:
|
|
51
|
+
|
|
52
|
+
```sh
|
|
53
|
+
git clone https://github.com/third774/effect-cloudflare-webrtc.git
|
|
54
|
+
cd effect-cloudflare-webrtc
|
|
55
|
+
pnpm install
|
|
56
|
+
pnpm build:packages
|
|
57
|
+
pnpm --dir packages/effect-cloudflare-webrtc pack --pack-destination <your project>
|
|
58
|
+
cd <your project>
|
|
59
|
+
npm install ./effect-cloudflare-webrtc-0.0.0.tgz effect
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## Create the SFU app and the TURN key
|
|
63
|
+
|
|
64
|
+
The server route needs a Realtime SFU app. A TURN key is optional, but we
|
|
65
|
+
recommend setting one up. When a firewall blocks a browser's direct
|
|
66
|
+
connection to the SFU, a TURN server can relay the media so the user can
|
|
67
|
+
still join the call.
|
|
68
|
+
|
|
69
|
+
[Cloudflare bills SFU and TURN usage together](https://developers.cloudflare.com/realtime/sfu/pricing/).
|
|
70
|
+
When Cloudflare TURN relays traffic for the Cloudflare SFU, you pay for
|
|
71
|
+
that traffic only once.
|
|
72
|
+
|
|
73
|
+
Create both with the [Cloudflare CLI](https://developers.cloudflare.com/cf/)
|
|
74
|
+
(`cf`). Do not use Wrangler or the dashboard.
|
|
75
|
+
|
|
76
|
+
```sh
|
|
77
|
+
npm install --global cf
|
|
78
|
+
cf auth login
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
`cf` returns each one as JSON with a `uid` (the ID) and a `secret` (the
|
|
82
|
+
token). Cloudflare shows the secret only when it creates the app or the
|
|
83
|
+
key. These commands write both values to `.dev.vars`, and they never show
|
|
84
|
+
the secret in the terminal, so a coding agent can run them:
|
|
85
|
+
|
|
86
|
+
```sh
|
|
87
|
+
save='let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{const{uid,secret}=JSON.parse(s);require("node:fs").appendFileSync(".dev.vars",`${process.argv[1]}_ID=${uid}\n${process.argv[1]}_TOKEN=${secret}\n`,{mode:0o600})})'
|
|
88
|
+
cf realtime sfu apps create --name my-app | node -e "$save" SFU_APP # SFU_APP_ID, SFU_APP_TOKEN
|
|
89
|
+
cf realtime turn keys create --name my-app | node -e "$save" TURN_SERVER_APP # TURN_SERVER_APP_ID, TURN_SERVER_APP_TOKEN
|
|
90
|
+
cut -d= -f1 .dev.vars # shows only the names
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
- Add `.dev.vars` to `.gitignore`. A coding agent must not read it.
|
|
94
|
+
- `cf dev` reads `.dev.vars` as the Worker's local secrets. To upload them
|
|
95
|
+
to the deployed Worker, run `cf deploy --secrets-file .dev.vars`.
|
|
96
|
+
- `cf` uses the account in the `CLOUDFLARE_ACCOUNT_ID` environment
|
|
97
|
+
variable, or `accountId` in `cloudflare.config.ts`, or else the only
|
|
98
|
+
account of your login. If your login can access more than one account,
|
|
99
|
+
`cf` asks which one to use. In a pipe, in an agent's shell or in CI, it
|
|
100
|
+
cannot ask: it stops and lists the accounts. Then set
|
|
101
|
+
`CLOUDFLARE_ACCOUNT_ID`. See
|
|
102
|
+
[Select an account](https://developers.cloudflare.com/cf/get-started/#select-an-account).
|
|
103
|
+
- A coding agent finds other `cf` commands with `cf cli search "<task>"`.
|
|
104
|
+
See [Use cf with coding agents](https://developers.cloudflare.com/cf/agents/).
|
|
105
|
+
|
|
106
|
+
## Package entry points
|
|
107
|
+
|
|
108
|
+
The examples use the plain client API. If your app uses Effect, see the
|
|
109
|
+
[Effect API](#effect-api).
|
|
110
|
+
|
|
111
|
+
| Entry point | For |
|
|
112
|
+
| ---------------------------------------- | -------------------------------------------------------------- |
|
|
113
|
+
| `effect-cloudflare-webrtc/client` | The plain client API, for applications that do not use Effect. |
|
|
114
|
+
| `effect-cloudflare-webrtc/react` | React hooks for the plain client API. |
|
|
115
|
+
| `effect-cloudflare-webrtc/server` | The route that adds the SFU app token. |
|
|
116
|
+
| `effect-cloudflare-webrtc/effect/client` | The Effect client API. |
|
|
117
|
+
| `effect-cloudflare-webrtc/effect/server` | The Effect handler and router layer for the SFU proxy. |
|
|
118
|
+
|
|
119
|
+
## Server
|
|
120
|
+
|
|
121
|
+
The browser must not have the SFU app token. The client sends each request
|
|
122
|
+
to a route on your server, which adds the token.
|
|
123
|
+
|
|
124
|
+
> [!IMPORTANT]
|
|
125
|
+
> **Your app controls access to this route.** Before calling
|
|
126
|
+
> `routeRealtimeRequest`, check who is making the request and whether
|
|
127
|
+
> they may perform the requested action. The default session lock protects
|
|
128
|
+
> existing sessions, but anyone who can reach an unguarded route can create
|
|
129
|
+
> a session or request TURN credentials if you configured TURN.
|
|
130
|
+
|
|
131
|
+
This Cloudflare Worker example shows where to add those checks.
|
|
132
|
+
|
|
133
|
+
```ts
|
|
134
|
+
import { routeRealtimeRequest } from "effect-cloudflare-webrtc/server";
|
|
135
|
+
|
|
136
|
+
interface Env {
|
|
137
|
+
SFU_APP_ID: string;
|
|
138
|
+
SFU_APP_TOKEN: string;
|
|
139
|
+
TURN_SERVER_APP_ID: string;
|
|
140
|
+
TURN_SERVER_APP_TOKEN: string;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export default {
|
|
144
|
+
async fetch(request, env) {
|
|
145
|
+
const url = new URL(request.url);
|
|
146
|
+
if (url.pathname.startsWith("/realtime/")) {
|
|
147
|
+
// Apply your app's access rules here. Reject unauthorized requests
|
|
148
|
+
// before passing them to routeRealtimeRequest.
|
|
149
|
+
return routeRealtimeRequest({
|
|
150
|
+
appId: env.SFU_APP_ID,
|
|
151
|
+
token: env.SFU_APP_TOKEN,
|
|
152
|
+
turnServerAppId: env.TURN_SERVER_APP_ID,
|
|
153
|
+
turnServerAppToken: env.TURN_SERVER_APP_TOKEN,
|
|
154
|
+
request
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
return new Response("Not found", { status: 404 });
|
|
158
|
+
}
|
|
159
|
+
} satisfies ExportedHandler<Env>;
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
`routeRealtimeRequest` takes a standard `Request` and returns a `Response`,
|
|
163
|
+
so it works in each framework, for example
|
|
164
|
+
`app.all("/realtime/*", (c) => routeRealtimeRequest({ ..., request: c.req.raw }))`
|
|
165
|
+
in Hono. The route must accept all methods.
|
|
166
|
+
|
|
167
|
+
- By default, changing a session requires its session token
|
|
168
|
+
(`lockSessionToInitiator`). The response of `sessions/new`
|
|
169
|
+
has a `sessionToken`, and the client sends it in the
|
|
170
|
+
`X-RealtimeClient-Session-Token` header. There is no cookie.
|
|
171
|
+
- Only `Content-Type` and `Accept` go to the Realtime API. Add more with
|
|
172
|
+
`forwardHeaders`.
|
|
173
|
+
- Without `turnServerAppId` and `turnServerAppToken`, the client gets only
|
|
174
|
+
public STUN servers.
|
|
175
|
+
- For a route other than `/realtime/*`, set `prefix` on the server and on
|
|
176
|
+
the client. With a `prefix` on a different origin, your CORS configuration
|
|
177
|
+
must permit the `X-RealtimeClient-Session-Token` and `Content-Type` headers.
|
|
178
|
+
- The route gives TURN credentials to anyone who can reach it. Put your
|
|
179
|
+
application behind authentication, for example Cloudflare Access, before
|
|
180
|
+
you share it widely.
|
|
181
|
+
|
|
182
|
+
## Client
|
|
183
|
+
|
|
184
|
+
```ts
|
|
185
|
+
import {
|
|
186
|
+
createAudioSink,
|
|
187
|
+
createRealtimeClient,
|
|
188
|
+
createMediaSources,
|
|
189
|
+
writable,
|
|
190
|
+
type TrackMetadata
|
|
191
|
+
} from "effect-cloudflare-webrtc/client";
|
|
192
|
+
|
|
193
|
+
const client = createRealtimeClient(); // prefix: "/realtime"
|
|
194
|
+
const media = createMediaSources({
|
|
195
|
+
microphone: { broadcasting: true },
|
|
196
|
+
camera: { broadcasting: true }
|
|
197
|
+
});
|
|
198
|
+
const { microphone: mic, camera } = media;
|
|
199
|
+
startButton.onclick = () => media.acquire().catch(console.error);
|
|
200
|
+
|
|
201
|
+
// The buttons
|
|
202
|
+
micButton.onclick = () => mic.toggleBroadcasting().catch(console.error);
|
|
203
|
+
mic.isBroadcasting.subscribe((isBroadcasting) => {
|
|
204
|
+
micButton.innerText = isBroadcasting ? "Mute" : "Unmute";
|
|
205
|
+
});
|
|
206
|
+
mic.onError((error) => console.error(error));
|
|
207
|
+
|
|
208
|
+
// Push. The track is published until `close()`.
|
|
209
|
+
const pushedMic = client.push(mic.broadcastTrack);
|
|
210
|
+
const pushedCamera = client.push(camera.broadcastTrack);
|
|
211
|
+
|
|
212
|
+
// Send the metadata to the other users, for example with a WebSocket.
|
|
213
|
+
pushedMic.metadata.subscribe((metadata) => {
|
|
214
|
+
if (metadata) websocket.send(JSON.stringify({ type: "mic", metadata }));
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
// Pull, on the computer of a different user.
|
|
218
|
+
const remoteCamera = writable<TrackMetadata | undefined>(undefined);
|
|
219
|
+
websocket.onmessage = (event) =>
|
|
220
|
+
remoteCamera.set(JSON.parse(event.data).metadata);
|
|
221
|
+
|
|
222
|
+
const pulledCamera = client.pull(remoteCamera, { preferredRid: "h" });
|
|
223
|
+
pulledCamera.track.subscribe((track) => {
|
|
224
|
+
video.srcObject = track ? new MediaStream([track]) : null;
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
// Audio of all remote users in one element
|
|
228
|
+
const sink = createAudioSink({ audioElement });
|
|
229
|
+
const detach = sink.attach(client.pull(remoteMic).track);
|
|
230
|
+
|
|
231
|
+
// Later
|
|
232
|
+
await pushedCamera.close();
|
|
233
|
+
await media.dispose();
|
|
234
|
+
await client.dispose();
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
`createScreenShareSource()` gives the screen share. It has a `video` and an `audio`
|
|
238
|
+
track, and each one has its own `broadcastTrack` to push:
|
|
239
|
+
`client.push(screenshare.video.broadcastTrack)`. Its
|
|
240
|
+
`startBroadcasting()` shows the browser's prompt.
|
|
241
|
+
|
|
242
|
+
### `Readable`
|
|
243
|
+
|
|
244
|
+
Each value that changes is a `Readable<T>`:
|
|
245
|
+
|
|
246
|
+
```ts
|
|
247
|
+
interface Readable<T> {
|
|
248
|
+
get(): T; // the current value
|
|
249
|
+
subscribe(listener: (value: T) => void): () => void; // calls immediately
|
|
250
|
+
}
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
It works with `useSyncExternalStore`, it is a Svelte store, and
|
|
254
|
+
`rxjs.from(readable)` works. `writable(initial)` makes one that you set.
|
|
255
|
+
|
|
256
|
+
### States
|
|
257
|
+
|
|
258
|
+
`client.sessionState`, `pushed.state`, and `pulled.state` are tagged unions.
|
|
259
|
+
Use them to show the user what occurs:
|
|
260
|
+
|
|
261
|
+
```ts
|
|
262
|
+
pushedMic.state.subscribe((state) => {
|
|
263
|
+
if (state._tag === "Retrying") console.warn("mic push failed", state.error);
|
|
264
|
+
});
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
| Push state | Meaning |
|
|
268
|
+
| ------------------- | -------------------------------------------------------------------- |
|
|
269
|
+
| `WaitingForTrack` | The source has given no track. |
|
|
270
|
+
| `WaitingForSession` | The session is not open, for example during a reconnect. |
|
|
271
|
+
| `Negotiating` | The request is in progress. |
|
|
272
|
+
| `WaitingForData` | The SFU accepted the track. The track has sent no data yet. |
|
|
273
|
+
| `Published` | Other users can pull the track. The state has the `metadata`. |
|
|
274
|
+
| `Retrying` | The last attempt failed (`error`). The next one comes after a delay. |
|
|
275
|
+
| `Failed` | No more attempts are made. |
|
|
276
|
+
| `Closed` | `close()` was called. |
|
|
277
|
+
|
|
278
|
+
A push stays in `WaitingForData` while its track sends no data. The fallback
|
|
279
|
+
audio track of `createMicrophoneSource()` sends no data before the first click or key press
|
|
280
|
+
of the user, because the browser does not start an audio context earlier.
|
|
281
|
+
|
|
282
|
+
### Muting the microphone and turning off the camera
|
|
283
|
+
|
|
284
|
+
The microphone and camera sources each expose a `broadcastTrack`. The screen
|
|
285
|
+
share source exposes one on each of its audio and video tracks. Each `broadcastTrack`
|
|
286
|
+
changes between the content track and a fallback track (silence, or
|
|
287
|
+
black video). The change uses `replaceTrack`, so other users do not pull
|
|
288
|
+
again.
|
|
289
|
+
|
|
290
|
+
For microphones and cameras, capture and broadcasting have separate controls.
|
|
291
|
+
|
|
292
|
+
- Use `stopBroadcasting()` to mute outgoing audio or video while keeping capture active.
|
|
293
|
+
Use `startBroadcasting()` to resume sending audio or video.
|
|
294
|
+
- Call `media.acquire()` from a user action to request both idle devices in one
|
|
295
|
+
browser call. The browser controls how many prompts appear. Handle rejection
|
|
296
|
+
in the button handler and let the user try either device separately.
|
|
297
|
+
- For one device, call `media.microphone.acquire()` or `media.camera.acquire()`.
|
|
298
|
+
Standalone `createMicrophoneSource()` and `createCameraSource()` work the same way.
|
|
299
|
+
Subscribing and setting the initial broadcast preference leave capture idle.
|
|
300
|
+
Calling `startBroadcasting()` or toggling on starts that device if needed.
|
|
301
|
+
Both return promises that reject if capture fails.
|
|
302
|
+
- Capture continues while muted or unsubscribed. Call `camera.release()` to
|
|
303
|
+
release the camera, `media.release()` to release both, or `media.dispose()`
|
|
304
|
+
when finished. Reacquiring preserves the broadcast settings.
|
|
305
|
+
- Read `isAcquiring` while waiting for permission or the first track.
|
|
306
|
+
`isAcquired` becomes true when the track is available and stays true while muted.
|
|
307
|
+
- Use `localMonitorTrack` for a local level meter or a “you're muted”
|
|
308
|
+
reminder. It can carry live audio while muted. Push `broadcastTrack`
|
|
309
|
+
for the call. Pushing `localMonitorTrack` would bypass mute.
|
|
310
|
+
- `broadcastTrack` and `localMonitorTrack` are active only while they have a
|
|
311
|
+
subscriber. A push is a subscriber.
|
|
312
|
+
|
|
313
|
+
When migrating device controls, replace `enable()` with `await acquire()` and
|
|
314
|
+
`disable()` with `await release()`. Remove the old `enabled` and `keepSourceAlive`
|
|
315
|
+
options. To unmute directly, `await mic.startBroadcasting()` is sufficient.
|
|
316
|
+
Screen sharing retains its existing controls.
|
|
317
|
+
|
|
318
|
+
### Connection statistics
|
|
319
|
+
|
|
320
|
+
`onStats` gives a sample of the statistics of the open session every
|
|
321
|
+
2 seconds. Each count and each rate is for the time since the previous
|
|
322
|
+
sample. Nothing comes while no session is open, and `onStats` does not keep a
|
|
323
|
+
session open.
|
|
324
|
+
|
|
325
|
+
```ts
|
|
326
|
+
const stop = client.onStats((stats) => {
|
|
327
|
+
// The round trip to the SFU, from the selected ICE candidate pair.
|
|
328
|
+
console.log(stats.transport?.roundTripTimeMillis);
|
|
329
|
+
// The packets of a pushed track that did not arrive at the SFU, from the
|
|
330
|
+
// receiver reports of the SFU. One entry for each simulcast layer.
|
|
331
|
+
for (const track of stats.sent) console.log(track.trackName, track.streams);
|
|
332
|
+
// The packets of a pulled track that did not arrive from the SFU.
|
|
333
|
+
for (const track of stats.received)
|
|
334
|
+
console.log(track.metadata.sessionId, track.packetsLost);
|
|
335
|
+
});
|
|
336
|
+
```
|
|
337
|
+
|
|
338
|
+
A value that the browser does not give is `null`. For example, Firefox does
|
|
339
|
+
not give `availableOutgoingBitrate` and `qualityLimitationReason`, and no
|
|
340
|
+
browser gives `availableIncomingBitrate` for a connection to the SFU.
|
|
341
|
+
|
|
342
|
+
## React
|
|
343
|
+
|
|
344
|
+
```tsx
|
|
345
|
+
import {
|
|
346
|
+
usePulledTrack,
|
|
347
|
+
usePushedTrack,
|
|
348
|
+
useReadable
|
|
349
|
+
} from "effect-cloudflare-webrtc/react";
|
|
350
|
+
|
|
351
|
+
function RemoteVideo({ metadata }: { metadata: TrackMetadata | undefined }) {
|
|
352
|
+
const { track, state } = usePulledTrack(client, metadata, {
|
|
353
|
+
preferredRid: "h"
|
|
354
|
+
});
|
|
355
|
+
return <Video track={track} />;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
function MicButton() {
|
|
359
|
+
const isBroadcasting = useReadable(mic.isBroadcasting);
|
|
360
|
+
return (
|
|
361
|
+
<button onClick={() => mic.toggleBroadcasting().catch(console.error)}>
|
|
362
|
+
{isBroadcasting ? "Mute" : "Unmute"}
|
|
363
|
+
</button>
|
|
364
|
+
);
|
|
365
|
+
}
|
|
366
|
+
```
|
|
367
|
+
|
|
368
|
+
Make the client and the devices outside the components, or in a context.
|
|
369
|
+
|
|
370
|
+
## Effect API
|
|
371
|
+
|
|
372
|
+
On the server, mount the proxy on your Effect router. The JavaScript
|
|
373
|
+
`routeRealtimeRequest` wrapper runs the same implementation with Fetch.
|
|
374
|
+
|
|
375
|
+
```ts
|
|
376
|
+
import { FetchHttpClient, HttpRouter } from "effect/http";
|
|
377
|
+
import { Realtime } from "effect-cloudflare-webrtc/effect/server";
|
|
378
|
+
|
|
379
|
+
const RealtimeLive = Realtime.layer({
|
|
380
|
+
appId: env.SFU_APP_ID,
|
|
381
|
+
token: env.SFU_APP_TOKEN,
|
|
382
|
+
turnServerAppId: env.TURN_SERVER_APP_ID,
|
|
383
|
+
turnServerAppToken: env.TURN_SERVER_APP_TOKEN
|
|
384
|
+
}).pipe(HttpRouter.provideRequest(FetchHttpClient.layer));
|
|
385
|
+
```
|
|
386
|
+
|
|
387
|
+
Protect this route with your application's access checks. See the
|
|
388
|
+
[Effect server guide](https://github.com/third774/effect-cloudflare-webrtc/blob/main/packages/effect-cloudflare-webrtc/docs/effect-api.md#server)
|
|
389
|
+
for custom handlers and HttpApi integration.
|
|
390
|
+
|
|
391
|
+
For an application that is built with Effect, use
|
|
392
|
+
`effect-cloudflare-webrtc/effect/client` instead of the plain client API.
|
|
393
|
+
The plain client API is a wrapper around it. The Effect API gives services,
|
|
394
|
+
layers, scopes and streams in place of callbacks and `Readable` values:
|
|
395
|
+
|
|
396
|
+
```ts
|
|
397
|
+
import * as Effect from "effect/Effect";
|
|
398
|
+
import * as Stream from "effect/Stream";
|
|
399
|
+
import { MicrophoneSource, RealtimeClient } from "effect-cloudflare-webrtc/effect/client";
|
|
400
|
+
|
|
401
|
+
const program = Effect.gen(function* () {
|
|
402
|
+
const client = yield* RealtimeClient;
|
|
403
|
+
const mic = yield* MicrophoneSource.make({ broadcasting: true });
|
|
404
|
+
yield* mic.acquire;
|
|
405
|
+
// The track is published while the scope is open.
|
|
406
|
+
const pushed = yield* client.push(mic.broadcastTrack);
|
|
407
|
+
yield* pushed.metadata.pipe(Stream.runForEach(sendToOtherUsers));
|
|
408
|
+
});
|
|
409
|
+
|
|
410
|
+
program.pipe(
|
|
411
|
+
Effect.scoped,
|
|
412
|
+
Effect.provide(RealtimeClient.layerBrowser({ prefix: "/realtime" })),
|
|
413
|
+
Effect.runFork
|
|
414
|
+
);
|
|
415
|
+
```
|
|
416
|
+
|
|
417
|
+
The guide to the Effect API is
|
|
418
|
+
[`docs/effect-api.md`](https://github.com/third774/effect-cloudflare-webrtc/blob/main/packages/effect-cloudflare-webrtc/docs/effect-api.md).
|
|
419
|
+
It tells about the layers and their options, push and pull, the states, the
|
|
420
|
+
microphone, the camera, the screen share, the audio sink, the statistics,
|
|
421
|
+
the typed errors, and how to replace the services in tests.
|
|
422
|
+
|
|
423
|
+
## This repository
|
|
424
|
+
|
|
425
|
+
This library is inspired by
|
|
426
|
+
[`partytracks`](https://github.com/cloudflare/partykit/tree/main/packages/partytracks).
|
|
427
|
+
|
|
428
|
+
| Folder | What it is |
|
|
429
|
+
| -------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
430
|
+
| [`packages/effect-cloudflare-webrtc`](https://github.com/third774/effect-cloudflare-webrtc/tree/main/packages/effect-cloudflare-webrtc) | The library. Its [`DEVELOPMENT.md`](https://github.com/third774/effect-cloudflare-webrtc/blob/main/packages/effect-cloudflare-webrtc/DEVELOPMENT.md) tells how to develop and test it. Its `wiki/` has the design and the decisions. |
|
|
431
|
+
| [`apps/effect-cloudflare-realtime`](https://github.com/third774/effect-cloudflare-webrtc/tree/main/apps/effect-cloudflare-realtime) | A video call app that uses the library, as an example and a playground. Its README tells how to set it up and run it. |
|
|
432
|
+
|
|
433
|
+
From the repository root:
|
|
434
|
+
|
|
435
|
+
```sh
|
|
436
|
+
pnpm install
|
|
437
|
+
pnpm typecheck # builds the library, then type-checks the library and the app
|
|
438
|
+
pnpm test # the tests of the library and the app
|
|
439
|
+
pnpm build # builds the library and the app
|
|
440
|
+
```
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import {
|
|
2
|
+
Y as SinkError,
|
|
3
|
+
k as MediaDevices,
|
|
4
|
+
rt as Subscribable
|
|
5
|
+
} from "./RealtimeClient-K7oKgsB9.js";
|
|
6
|
+
import * as Effect from "effect/Effect";
|
|
7
|
+
import * as Scope from "effect/Scope";
|
|
8
|
+
import * as Stream from "effect/Stream";
|
|
9
|
+
|
|
10
|
+
//#region src/effect/client/AudioSink.d.ts
|
|
11
|
+
/** The part of `HTMLAudioElement` that the audio sink uses. */
|
|
12
|
+
interface AudioSinkElement {
|
|
13
|
+
addEventListener(type: string, listener: (event: Event) => void): void;
|
|
14
|
+
removeEventListener(type: string, listener: (event: Event) => void): void;
|
|
15
|
+
srcObject: MediaProvider | null;
|
|
16
|
+
play(): Promise<void>;
|
|
17
|
+
/** Safari does not have this method. */
|
|
18
|
+
setSinkId?(sinkId: string): Promise<void>;
|
|
19
|
+
}
|
|
20
|
+
interface AudioSinkOptions {
|
|
21
|
+
/** An `<audio>` element. */
|
|
22
|
+
readonly audioElement: AudioSinkElement;
|
|
23
|
+
/** The audio output device at the start. */
|
|
24
|
+
readonly sinkId?: string;
|
|
25
|
+
}
|
|
26
|
+
interface AudioSink {
|
|
27
|
+
/**
|
|
28
|
+
* Plays each track of the stream while the scope is open. A new track
|
|
29
|
+
* replaces the track before it.
|
|
30
|
+
*/
|
|
31
|
+
readonly attach: <E, R>(
|
|
32
|
+
track: Stream.Stream<MediaStreamTrack, E, R>
|
|
33
|
+
) => Effect.Effect<void, never, R | Scope.Scope>;
|
|
34
|
+
/** False in a browser that cannot select the audio output device. */
|
|
35
|
+
readonly isSinkIdSupported: boolean;
|
|
36
|
+
/** Selects the audio output device. */
|
|
37
|
+
readonly setSinkId: (sinkId: string) => Effect.Effect<void, SinkError>;
|
|
38
|
+
/** The audio output devices. */
|
|
39
|
+
readonly availableDevices: Subscribable<ReadonlyArray<MediaDeviceInfo>>;
|
|
40
|
+
/**
|
|
41
|
+
* False when the element does not play, for example because the browser
|
|
42
|
+
* blocked it. The application can then call `play()` of the element from
|
|
43
|
+
* a user gesture.
|
|
44
|
+
*/
|
|
45
|
+
readonly isPlaying: Subscribable<boolean>;
|
|
46
|
+
}
|
|
47
|
+
declare const AudioSink: {
|
|
48
|
+
make: (
|
|
49
|
+
options: AudioSinkOptions
|
|
50
|
+
) => Effect.Effect<AudioSink, never, Scope.Scope | MediaDevices>;
|
|
51
|
+
};
|
|
52
|
+
//#endregion
|
|
53
|
+
export { AudioSinkElement as n, AudioSinkOptions as r, AudioSink as t };
|
|
54
|
+
//# sourceMappingURL=AudioSink-BybkMP2y.d.ts.map
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
//#region src/client/Readable.ts
|
|
2
|
+
const observableKey = (() => {
|
|
3
|
+
const symbol = Reflect.get(Symbol, "observable");
|
|
4
|
+
return typeof symbol === "symbol" ? symbol : "@@observable";
|
|
5
|
+
})();
|
|
6
|
+
/** The implementation of `Readable` and `Writable`. */
|
|
7
|
+
var Store = class {
|
|
8
|
+
listeners = /* @__PURE__ */ new Set();
|
|
9
|
+
deactivate;
|
|
10
|
+
/** Goes up with each change of the value. */
|
|
11
|
+
version = 0;
|
|
12
|
+
constructor(value, options = {}) {
|
|
13
|
+
this.value = value;
|
|
14
|
+
this.options = options;
|
|
15
|
+
Object.defineProperty(this, observableKey, { value: () => this.observable() });
|
|
16
|
+
}
|
|
17
|
+
get = () => this.value;
|
|
18
|
+
set = (value) => {
|
|
19
|
+
if (Object.is(value, this.value)) return;
|
|
20
|
+
this.value = value;
|
|
21
|
+
const version = ++this.version;
|
|
22
|
+
for (const listener of [...this.listeners]) {
|
|
23
|
+
if (version !== this.version) return;
|
|
24
|
+
if (!this.listeners.has(listener)) continue;
|
|
25
|
+
listener(value);
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
subscribe = (listener) => {
|
|
29
|
+
const entry = (value) => listener(value);
|
|
30
|
+
this.listeners.add(entry);
|
|
31
|
+
if (this.listeners.size === 1) this.deactivate = this.options.onActive?.();
|
|
32
|
+
listener(this.value);
|
|
33
|
+
return () => {
|
|
34
|
+
if (!this.listeners.delete(entry)) return;
|
|
35
|
+
if (this.listeners.size === 0) {
|
|
36
|
+
this.deactivate?.();
|
|
37
|
+
this.deactivate = void 0;
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
};
|
|
41
|
+
[Symbol.observable]() {
|
|
42
|
+
return this.observable();
|
|
43
|
+
}
|
|
44
|
+
observable() {
|
|
45
|
+
const interop = { subscribe: (observer) => {
|
|
46
|
+
return { unsubscribe: this.subscribe((value) => {
|
|
47
|
+
if (typeof observer === "function") observer(value);
|
|
48
|
+
else observer.next?.(value);
|
|
49
|
+
}) };
|
|
50
|
+
} };
|
|
51
|
+
Object.defineProperty(interop, observableKey, { value: () => interop });
|
|
52
|
+
return interop;
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
/** A `Readable` that the application sets, for example from a WebSocket. */
|
|
56
|
+
function writable(initial) {
|
|
57
|
+
return new Store(initial);
|
|
58
|
+
}
|
|
59
|
+
function isReadable(value) {
|
|
60
|
+
return typeof value === "object" && value !== null && "get" in value && "subscribe" in value && typeof value.get === "function" && typeof value.subscribe === "function";
|
|
61
|
+
}
|
|
62
|
+
//#endregion
|
|
63
|
+
export { isReadable as n, writable as r, Store as t };
|
|
64
|
+
|
|
65
|
+
//# sourceMappingURL=Readable-CJPSx6Uq.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Readable-CJPSx6Uq.js","names":[],"sources":["../src/client/Readable.ts"],"sourcesContent":["declare global {\n interface SymbolConstructor {\n /** The interoperability symbol of observable libraries, for example RxJS. */\n readonly observable: symbol;\n }\n}\n\n/** What `rxjs.from()` and other observable libraries accept. */\nexport interface InteropObservable<T> {\n subscribe(observer: ((value: T) => void) | { next?: (value: T) => void }): {\n unsubscribe(): void;\n };\n}\n\n/** A value that changes. It always has a current value. */\nexport interface Readable<T> {\n /** The current value. */\n get(): T;\n /**\n * Calls the listener immediately with the current value, then for each\n * change. Returns a function that stops the subscription.\n */\n subscribe(listener: (value: T) => void): () => void;\n /** For observable libraries: `rxjs.from(readable)` works. */\n [Symbol.observable](): InteropObservable<T>;\n}\n\n/** A `Readable` that the application sets. */\nexport interface Writable<T> extends Readable<T> {\n set(value: T): void;\n}\n\n// The symbol exists only when an observable library defined it. The string\n// is the name that the libraries use when it does not exist.\nconst observableKey: PropertyKey = (() => {\n const symbol: unknown = Reflect.get(Symbol, \"observable\");\n return typeof symbol === \"symbol\" ? symbol : \"@@observable\";\n})();\n\nexport interface StoreOptions {\n /**\n * Called when the store gets its first subscriber. The function that it\n * returns is called when the last subscriber goes away.\n */\n readonly onActive?: () => () => void;\n}\n\n/** The implementation of `Readable` and `Writable`. */\nexport class Store<T> implements Writable<T> {\n private readonly listeners = new Set<(value: T) => void>();\n private deactivate: (() => void) | undefined;\n /** Goes up with each change of the value. */\n private version = 0;\n\n constructor(\n private value: T,\n private readonly options: StoreOptions = {}\n ) {\n Object.defineProperty(this, observableKey, {\n value: () => this.observable()\n });\n }\n\n get = (): T => this.value;\n\n set = (value: T): void => {\n if (Object.is(value, this.value)) return;\n this.value = value;\n const version = ++this.version;\n for (const listener of [...this.listeners]) {\n // A listener set a newer value, and each listener got it.\n if (version !== this.version) return;\n // A listener stopped the subscription of this listener.\n if (!this.listeners.has(listener)) continue;\n listener(value);\n }\n };\n\n subscribe = (listener: (value: T) => void): (() => void) => {\n // Each subscription is separate, also for the same function.\n const entry = (value: T) => listener(value);\n this.listeners.add(entry);\n if (this.listeners.size === 1) {\n this.deactivate = this.options.onActive?.();\n }\n listener(this.value);\n return () => {\n if (!this.listeners.delete(entry)) return;\n if (this.listeners.size === 0) {\n this.deactivate?.();\n this.deactivate = undefined;\n }\n };\n };\n\n [Symbol.observable](): InteropObservable<T> {\n return this.observable();\n }\n\n private observable(): InteropObservable<T> {\n const interop: InteropObservable<T> = {\n subscribe: (observer) => {\n const unsubscribe = this.subscribe((value) => {\n if (typeof observer === \"function\") observer(value);\n else observer.next?.(value);\n });\n return { unsubscribe };\n }\n };\n // An observable must give itself for the same key.\n Object.defineProperty(interop, observableKey, { value: () => interop });\n return interop;\n }\n}\n\n/** A `Readable` that the application sets, for example from a WebSocket. */\nexport function writable<T>(initial: T): Writable<T> {\n return new Store(initial);\n}\n\nexport function isReadable(value: unknown): value is Readable<unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"get\" in value &&\n \"subscribe\" in value &&\n typeof value.get === \"function\" &&\n typeof value.subscribe === \"function\"\n );\n}\n"],"mappings":";AAkCA,MAAM,uBAAoC;CACxC,MAAM,SAAkB,QAAQ,IAAI,QAAQ,aAAa;AACzD,QAAO,OAAO,WAAW,WAAW,SAAS;IAC3C;;AAWJ,IAAa,QAAb,MAA6C;CAC3C,4BAA6B,IAAI,KAAyB;CAC1D;;CAEA,UAAkB;CAElB,YACE,OACA,UAAyC,EAAE,EAC3C;AAFQ,OAAA,QAAA;AACS,OAAA,UAAA;AAEjB,SAAO,eAAe,MAAM,eAAe,EACzC,aAAa,KAAK,YAAY,EAC/B,CAAC;;CAGJ,YAAe,KAAK;CAEpB,OAAO,UAAmB;AACxB,MAAI,OAAO,GAAG,OAAO,KAAK,MAAM,CAAE;AAClC,OAAK,QAAQ;EACb,MAAM,UAAU,EAAE,KAAK;AACvB,OAAK,MAAM,YAAY,CAAC,GAAG,KAAK,UAAU,EAAE;AAE1C,OAAI,YAAY,KAAK,QAAS;AAE9B,OAAI,CAAC,KAAK,UAAU,IAAI,SAAS,CAAE;AACnC,YAAS,MAAM;;;CAInB,aAAa,aAA+C;EAE1D,MAAM,SAAS,UAAa,SAAS,MAAM;AAC3C,OAAK,UAAU,IAAI,MAAM;AACzB,MAAI,KAAK,UAAU,SAAS,EAC1B,MAAK,aAAa,KAAK,QAAQ,YAAY;AAE7C,WAAS,KAAK,MAAM;AACpB,eAAa;AACX,OAAI,CAAC,KAAK,UAAU,OAAO,MAAM,CAAE;AACnC,OAAI,KAAK,UAAU,SAAS,GAAG;AAC7B,SAAK,cAAc;AACnB,SAAK,aAAa,KAAA;;;;CAKxB,CAAC,OAAO,cAAoC;AAC1C,SAAO,KAAK,YAAY;;CAG1B,aAA2C;EACzC,MAAM,UAAgC,EACpC,YAAY,aAAa;AAKvB,UAAO,EAAE,aAJW,KAAK,WAAW,UAAU;AAC5C,QAAI,OAAO,aAAa,WAAY,UAAS,MAAM;QAC9C,UAAS,OAAO,MAAM;KAET,EAAE;KAEzB;AAED,SAAO,eAAe,SAAS,eAAe,EAAE,aAAa,SAAS,CAAC;AACvE,SAAO;;;;AAKX,SAAgB,SAAY,SAAyB;AACnD,QAAO,IAAI,MAAM,QAAQ;;AAG3B,SAAgB,WAAW,OAA4C;AACrE,QACE,OAAO,UAAU,YACjB,UAAU,QACV,SAAS,SACT,eAAe,SACf,OAAO,MAAM,QAAQ,cACrB,OAAO,MAAM,cAAc"}
|