@midsummer-ai/sdk 0.1.0-staging.4480 → 0.1.0-staging.4486

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.
@@ -1,6 +1,6 @@
1
1
  import { n as AuthStore } from "../store-B3KJ3e83.mjs";
2
2
  import { SignInMail } from "./mail.mjs";
3
- import { a as Auth } from "../index-CkyNDcba.mjs";
3
+ import { a as Auth } from "../index-BmjcZfRb.mjs";
4
4
  //#region src/auth/contract.d.ts
5
5
  interface AuthHarness {
6
6
  /** Sign-in over a store with no users, made with `scopes: CONTRACT_SCOPES`. */
package/auth/contract.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { c as AuthError } from "../auth-C7yU9QWZ.mjs";
2
- import { d as SETTINGS_TTL_MS, n as LIMIT_WINDOW_MS, t as LIMITS } from "../guard-Br3K8CVx.mjs";
1
+ import { c as AuthError } from "../auth-BH2Lfguc.mjs";
2
+ import { d as SETTINGS_TTL_MS, n as LIMIT_WINDOW_MS, t as LIMITS } from "../guard-VPI6xq4z.mjs";
3
3
  import { IMPERSONATION_TOKEN_MS, startImpersonation } from "./impersonate.mjs";
4
4
  //#region src/auth/contract.ts
5
5
  /**
package/auth/index.d.mts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { n as AuthStore, r as databaseStore, t as AuthCall } from "../store-B3KJ3e83.mjs";
2
2
  import { i as SignUpPolicy, n as CaptchaProvider, r as PublicSettings, t as AuthSettings } from "../settings-Dz3irtlu.mjs";
3
3
  import { SignInMail, SignInMailKind, checkSignInMail, signInWords } from "./mail.mjs";
4
- import { _ as AuthEvent, a as Auth, b as EventSend, c as AuthUserRecord, d as SignedIn, f as SignedInAgent, g as AuthErrorCode, h as AuthError, i as AgentKey, l as IMPERSONATION_S, m as createAuth, n as AUTH_ROUTES, o as AuthOptions, p as auth, r as AgentGrant, s as AuthUser, t as AUTH_PATH, u as SESSION_CACHE_S, v as AuthEventBatch, y as AuthEventType } from "../index-CkyNDcba.mjs";
4
+ import { _ as AuthEvent, a as Auth, b as EventSend, c as AuthUserRecord, d as SignedIn, f as SignedInAgent, g as AuthErrorCode, h as AuthError, i as AgentKey, l as IMPERSONATION_S, m as createAuth, n as AUTH_ROUTES, o as AuthOptions, p as auth, r as AgentGrant, s as AuthUser, t as AUTH_PATH, u as SESSION_CACHE_S, v as AuthEventBatch, y as AuthEventType } from "../index-BmjcZfRb.mjs";
5
5
  import { i as authFiles } from "../files-CLuPkXhj.mjs";
6
6
  export { AUTH_PATH, AUTH_ROUTES, AgentGrant, AgentKey, Auth, type AuthCall, AuthError, type AuthErrorCode, type AuthEvent, type AuthEventBatch, type AuthEventType, AuthOptions, type AuthSettings, type AuthStore, AuthUser, AuthUserRecord, type CaptchaProvider, type EventSend, IMPERSONATION_S, type PublicSettings, SESSION_CACHE_S, type SignInMail, type SignInMailKind, type SignUpPolicy, SignedIn, SignedInAgent, auth, authFiles, checkSignInMail, createAuth, databaseStore, signInWords };
package/auth/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { a as auth, c as AuthError, i as SESSION_CACHE_S, n as AUTH_ROUTES, o as createAuth, r as IMPERSONATION_S, s as databaseStore, t as AUTH_PATH } from "../auth-C7yU9QWZ.mjs";
1
+ import { a as auth, c as AuthError, i as SESSION_CACHE_S, n as AUTH_ROUTES, o as createAuth, r as IMPERSONATION_S, s as databaseStore, t as AUTH_PATH } from "../auth-BH2Lfguc.mjs";
2
2
  import { checkSignInMail, signInWords } from "./mail.mjs";
3
3
  import { n as authFiles } from "../files-ZySaprII.mjs";
4
4
  export { AUTH_PATH, AUTH_ROUTES, AuthError, IMPERSONATION_S, SESSION_CACHE_S, auth, authFiles, checkSignInMail, createAuth, databaseStore, signInWords };
package/auth/password.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { n as hashPassword$1, r as verifyPassword$1 } from "../engine-Be7yur9O.mjs";
1
+ import { n as hashPassword$1, r as verifyPassword$1 } from "../engine-CmTP59GT.mjs";
2
2
  import { isBcrypt as isBcrypt$1 } from "./import.mjs";
3
3
  //#region src/auth/password.ts
4
4
  /**
package/auth/react.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { t as DATABASE_TOKEN_PATH, u as signedInDatabase } from "../client-5gJ-6h4y.mjs";
2
2
  import { DatabaseProvider } from "../database/react.mjs";
3
- import { a as WORDS, c as deviceOf, i as CAPTCHA_WIDGETS, l as screenName, n as textOn, o as ago, t as authCss, u as setupKeyOf } from "../style-BJzVvUKV.mjs";
3
+ import { a as WORDS, c as deviceOf, i as CAPTCHA_WIDGETS, l as screenName, n as textOn, o as ago, t as authCss, u as setupKeyOf } from "../style-DXd-0Cxo.mjs";
4
4
  import { a as shapeAttributes, r as ICONS, t as qrPath } from "../qr-BySxqLW6.mjs";
5
5
  import { AuthClientError, authClient } from "./client.mjs";
6
6
  import { Fragment, createContext, createElement, useCallback, useContext, useEffect, useId, useMemo, useRef, useState } from "react";
@@ -1,11 +1,12 @@
1
1
  import { a as processEnv, i as platformApi, n as here } from "./here-C2jhTheQ.mjs";
2
2
  import { DatabaseError } from "./database/errors.mjs";
3
3
  import { d as userToken, o as connect, s as databaseUrl } from "./client-5gJ-6h4y.mjs";
4
+ import { CALL_STATUS } from "./calls/protocol.mjs";
4
5
  import { sendSignInMail } from "./auth/mail.mjs";
5
6
  import "./files-ZySaprII.mjs";
6
7
  import { standIn } from "./auth/stand-in.mjs";
7
- import { a as WORDS, c as deviceOf, i as CAPTCHA_WIDGETS, l as screenName, n as textOn, o as ago, r as GEIST_WOFF2, s as defaultAppName, t as authCss, u as setupKeyOf } from "./style-BJzVvUKV.mjs";
8
- import { _ as challenge, a as leakedPassword, b as remembering, c as refusal, f as mayJoin, g as agentOfKey, i as guard, l as verifyHuman, m as settingsReader, o as ourWords, p as publicSettings, r as REFUSALS, s as rateLimiter, u as JoinRefused, v as consentPage, x as resourceOf, y as credentialOf } from "./guard-Br3K8CVx.mjs";
8
+ import { a as WORDS, c as deviceOf, i as CAPTCHA_WIDGETS, l as screenName, n as textOn, o as ago, r as GEIST_WOFF2, s as defaultAppName, t as authCss, u as setupKeyOf } from "./style-DXd-0Cxo.mjs";
9
+ import { _ as challenge, a as leakedPassword, b as remembering, c as refusal, f as mayJoin, g as agentOfKey, i as guard, l as verifyHuman, m as settingsReader, o as ourWords, p as publicSettings, r as REFUSALS, s as rateLimiter, u as JoinRefused, v as consentPage, x as resourceOf, y as credentialOf } from "./guard-VPI6xq4z.mjs";
9
10
  import { i as iconSvg, n as qrSvg } from "./qr-BySxqLW6.mjs";
10
11
  //#region src/auth/errors.ts
11
12
  var AuthError = class extends Error {
@@ -1071,6 +1072,8 @@ ${kind === "sign-in" ? `const o=await p("/passkey/generate-authenticate-options"
1071
1072
  * https). Signing up signs the person in at once unless the settings' `confirmEmail` is on (`./settings.ts`).
1072
1073
  * `GET /api/auth/database-token` returns `{ url, token, expiresAt }`: the app's database and a token for the person
1073
1074
  * signed in, which the page's `signedInDatabase()` (`<AuthProvider database>`) connects with, or `{ url }` for no one.
1075
+ * `GET /api/auth/call-token?room=<name>` returns a call token for the person signed in (`callToken`), when the app
1076
+ * passed `createAuth({ calls: { allow } })` and `allow` lets them join that room.
1074
1077
  *
1075
1078
  * Email and password, codes and sign-in links by mail, Google and GitHub when their keys are set, organizations with
1076
1079
  * roles and invitations, two-factor codes, passkeys and bans. Browsers talk to it with `@midsummer-ai/sdk/auth/client`,
@@ -1103,6 +1106,8 @@ ${kind === "sign-in" ? `const o=await p("/passkey/generate-authenticate-options"
1103
1106
  */
1104
1107
  /** Where sign-in is served, under every address of the app. */
1105
1108
  const AUTH_PATH = "/api/auth";
1109
+ /** Where a signed-in person gets a call token, under `AUTH_PATH`. */
1110
+ const CALL_TOKEN_PATH = "/call-token";
1106
1111
  /** How long a session is kept in its cookie before its row is read again, in seconds. */
1107
1112
  const SESSION_CACHE_S = 300;
1108
1113
  /** How long a session the platform's "sign in as" makes lasts, in seconds. */
@@ -1265,7 +1270,7 @@ const DAY_S = 86400;
1265
1270
  * the engine (a session with no cookie, the settings, the hosted pages), never load it. Loaded at import, it added 0.2
1266
1271
  * to 0.6 s to the first answer of each new copy of a Next.js app's server on Midsummer.
1267
1272
  */
1268
- const engineAdapter = () => import("./engine-Be7yur9O.mjs").then((n) => n.t);
1273
+ const engineAdapter = () => import("./engine-CmTP59GT.mjs").then((n) => n.t);
1269
1274
  const keyOf = (row) => ({
1270
1275
  id: row.id,
1271
1276
  name: row.name,
@@ -1857,6 +1862,46 @@ function createAuth(options = {}) {
1857
1862
  }
1858
1863
  }));
1859
1864
  }
1865
+ /** `GET /api/auth/call-token?room=<name>`: a call token for the person signed in, for a room `calls.allow` lets them join. */
1866
+ async function callTokenOf(request) {
1867
+ const answer = (status, body) => Response.json(body, {
1868
+ status,
1869
+ headers: { "Cache-Control": "no-store" }
1870
+ });
1871
+ if (!options.calls) return answer(404, {
1872
+ code: "NOT_FOUND",
1873
+ message: "This app hands out no call tokens. Pass createAuth({ calls: { allow } }) to choose who joins which room."
1874
+ });
1875
+ const room = new URL(request.url).searchParams.get("room") ?? "";
1876
+ const { callToken, CallError, roomProblem } = await import("./calls/index.mjs");
1877
+ const problem = roomProblem(room);
1878
+ if (problem) return answer(400, {
1879
+ code: "INVALID",
1880
+ message: problem
1881
+ });
1882
+ const signedIn = await person(request);
1883
+ if (!signedIn) return answer(401, {
1884
+ code: "FORBIDDEN",
1885
+ message: "Sign in to join this call."
1886
+ });
1887
+ if (!await options.calls.allow(signedIn.user, room)) return answer(403, {
1888
+ code: "FORBIDDEN",
1889
+ message: "You can't join this call."
1890
+ });
1891
+ try {
1892
+ return answer(200, await callToken({
1893
+ room,
1894
+ as: signedIn.user.id,
1895
+ name: signedIn.user.name
1896
+ }));
1897
+ } catch (error) {
1898
+ if (error instanceof CallError) return answer(CALL_STATUS[error.code], {
1899
+ code: error.code.toUpperCase().replace(/-/g, "_"),
1900
+ message: error.message
1901
+ });
1902
+ throw error;
1903
+ }
1904
+ }
1860
1905
  /** Serves one request under `/api/auth`: settings, account calls, hosted pages, the guard, then the engine. */
1861
1906
  async function serve(request) {
1862
1907
  const origin = originOf(request), { pathname } = new URL(request.url);
@@ -1884,6 +1929,7 @@ function createAuth(options = {}) {
1884
1929
  scopes: settingsOfAgents.scopes
1885
1930
  }, { headers: { "Cache-Control": "no-store" } });
1886
1931
  if (`/api/auth${path}` === "/api/auth/database-token" && request.method === "GET") return databaseToken(request);
1932
+ if (path === CALL_TOKEN_PATH && request.method === "GET") return callTokenOf(request);
1887
1933
  if (path.startsWith("/account/")) return account(request, path.slice(8), origin);
1888
1934
  if (path.startsWith("/ui/")) return hostedPage(request, path.slice(3), {
1889
1935
  auth,
@@ -0,0 +1,23 @@
1
+ import { a as CallToken } from "../protocol-BeBvbfKf.mjs";
2
+ import { CallTokenInput } from "./index.mjs";
3
+ //#region src/calls/contract.d.ts
4
+ interface CallsWorld {
5
+ /** Serves the call wire: the platform's route, or the Stand-in's `fetch`. */
6
+ fetch(request: Request): Promise<Response>;
7
+ /** A token for a room, as the app's server makes one. */
8
+ token(input: CallTokenInput): Promise<CallToken>;
9
+ /** Ends a room, as `midsummer call room end` does. */
10
+ end(room: string): Promise<void>;
11
+ /** `relay` when no media server runs, as in the Stand-in. */
12
+ readonly media: "sfu" | "relay";
13
+ }
14
+ interface CallCase {
15
+ /** A line of the specification. */
16
+ readonly name: string;
17
+ /** Run it only where media goes this way. */
18
+ readonly needs?: "relay";
19
+ run(world: CallsWorld): Promise<void>;
20
+ }
21
+ declare const callsContract: ReadonlyArray<CallCase>;
22
+ //#endregion
23
+ export { CallCase, CallsWorld, callsContract };
@@ -0,0 +1,293 @@
1
+ //#region src/calls/contract.ts
2
+ async function caller(world, input) {
3
+ return holding(world, await world.token(input));
4
+ }
5
+ function holding(world, token) {
6
+ const send = async (op, body) => {
7
+ const response = await world.fetch(new Request(`${token.url}/${op}`, {
8
+ method: "POST",
9
+ headers: {
10
+ authorization: `Bearer ${token.token}`,
11
+ "content-type": "application/json"
12
+ },
13
+ body: JSON.stringify(body)
14
+ }));
15
+ return {
16
+ status: response.status,
17
+ body: await response.json()
18
+ };
19
+ };
20
+ return {
21
+ token,
22
+ async call(op, body) {
23
+ const { status, body: answer } = await send(op, body);
24
+ if (status !== 200) throw new Error(`${op}: expected 200, got ${status} ${JSON.stringify(answer)}`);
25
+ return answer;
26
+ },
27
+ async refused(op, body, code, what) {
28
+ const { status, body: answer } = await send(op, body);
29
+ const statuses = {
30
+ invalid: 400,
31
+ quota: 402,
32
+ forbidden: 403,
33
+ "not-found": 404,
34
+ full: 409,
35
+ ended: 410,
36
+ unavailable: 503
37
+ };
38
+ if (status !== statuses[code] || answer.error?.code !== code || typeof answer.error.message !== "string" || !answer.error.message) throw new Error(`${what}: expected ${statuses[code]} ${code} with words, got ${status} ${JSON.stringify(answer)}`);
39
+ }
40
+ };
41
+ }
42
+ /** A room of the case's own. */
43
+ const roomFor = (what) => `${what}-${Math.random().toString(36).slice(2, 10)}`;
44
+ const callsContract = [
45
+ {
46
+ name: "a first join opens the room, with nothing made first, and you're the one participant in it",
47
+ async run(world) {
48
+ const room = roomFor("support");
49
+ const joined = await (await caller(world, {
50
+ room,
51
+ as: "ada",
52
+ name: "Ada Lovelace"
53
+ })).call("join", {});
54
+ equal({
55
+ as: joined.participant.as,
56
+ name: joined.participant.name,
57
+ kind: joined.participant.kind,
58
+ state: joined.participant.state,
59
+ tracks: joined.participant.tracks
60
+ }, {
61
+ as: "ada",
62
+ name: "Ada Lovelace",
63
+ kind: "person",
64
+ state: "joined",
65
+ tracks: []
66
+ }, "the participant");
67
+ equal({
68
+ name: joined.room.name,
69
+ state: joined.room.state,
70
+ participants: joined.room.participants.map((each) => each.id)
71
+ }, {
72
+ name: room,
73
+ state: "open",
74
+ participants: [joined.participant.id]
75
+ }, "the room");
76
+ equal(joined.media === "sfu" || joined.media === "relay", true, "the media is sfu or relay");
77
+ }
78
+ },
79
+ {
80
+ name: "a second join sees the first in the room",
81
+ async run(world) {
82
+ const room = roomFor("pair");
83
+ const ada = await caller(world, {
84
+ room,
85
+ as: "ada"
86
+ }), bob = await caller(world, {
87
+ room,
88
+ as: "bob"
89
+ });
90
+ await ada.call("join", {});
91
+ equal((await bob.call("join", {})).room.participants.map((each) => each.as).sort(), ["ada", "bob"], "who bob sees");
92
+ }
93
+ },
94
+ {
95
+ name: "a watch waiting on the room returns when someone joins",
96
+ async run(world) {
97
+ const room = roomFor("watch");
98
+ const ada = await caller(world, {
99
+ room,
100
+ as: "ada"
101
+ }), bob = await caller(world, {
102
+ room,
103
+ as: "bob"
104
+ });
105
+ const joined = await ada.call("join", {});
106
+ const watching = ada.call("watch", {
107
+ participant: joined.participant.id,
108
+ after: joined.room.changed,
109
+ waitMs: 25e3
110
+ });
111
+ await bob.call("join", {});
112
+ const { room: seen } = await watching;
113
+ equal(seen.participants.map((each) => each.as).sort(), ["ada", "bob"], "who ada's watch sees");
114
+ }
115
+ },
116
+ {
117
+ name: "tracks a participant publishes show to the others by name and kind, and one is published once",
118
+ needs: "relay",
119
+ async run(world) {
120
+ const room = roomFor("publish");
121
+ const ada = await caller(world, {
122
+ room,
123
+ as: "ada"
124
+ }), bob = await caller(world, {
125
+ room,
126
+ as: "bob"
127
+ });
128
+ const { participant } = await ada.call("join", {});
129
+ const { participant: watcher } = await bob.call("join", {});
130
+ await ada.call("publish", {
131
+ participant: participant.id,
132
+ tracks: [{ name: "mic" }, { name: "camera" }]
133
+ });
134
+ const { room: seen } = await bob.call("watch", {
135
+ participant: watcher.id,
136
+ after: -1,
137
+ waitMs: 0
138
+ });
139
+ equal(seen.participants.find((each) => each.as === "ada")?.tracks, [{
140
+ name: "mic",
141
+ kind: "audio"
142
+ }, {
143
+ name: "camera",
144
+ kind: "video"
145
+ }], "ada's tracks as bob sees them");
146
+ await ada.refused("publish", {
147
+ participant: participant.id,
148
+ tracks: [{ name: "mic" }]
149
+ }, "invalid", "publishing mic again");
150
+ await ada.refused("publish", {
151
+ participant: participant.id,
152
+ tracks: [{ name: "speaker" }]
153
+ }, "invalid", "publishing a track with no such name");
154
+ }
155
+ },
156
+ {
157
+ name: "a token for another room can't act in this one, and what isn't a token is refused",
158
+ async run(world) {
159
+ const here = roomFor("here"), there = roomFor("there");
160
+ const ada = await caller(world, {
161
+ room: here,
162
+ as: "ada"
163
+ }), elsewhere = await caller(world, {
164
+ room: there,
165
+ as: "ada"
166
+ });
167
+ const { participant } = await ada.call("join", {});
168
+ await elsewhere.call("join", {});
169
+ await elsewhere.refused("watch", {
170
+ participant: participant.id,
171
+ after: -1,
172
+ waitMs: 0
173
+ }, "forbidden", "watching this room with the other room's token");
174
+ await elsewhere.refused("leave", { participant: participant.id }, "forbidden", "leaving this room with the other room's token");
175
+ await holding(world, {
176
+ ...ada.token,
177
+ token: "mcall_e30.bm90LWEtc2lnbmF0dXJl"
178
+ }).refused("join", {}, "forbidden", "joining with what isn't a token");
179
+ }
180
+ },
181
+ {
182
+ name: "leaving removes you: the others see you go, and leaving again changes nothing",
183
+ async run(world) {
184
+ const room = roomFor("leave");
185
+ const ada = await caller(world, {
186
+ room,
187
+ as: "ada"
188
+ }), bob = await caller(world, {
189
+ room,
190
+ as: "bob"
191
+ });
192
+ const { participant } = await ada.call("join", {});
193
+ const { participant: leaving } = await bob.call("join", {});
194
+ await bob.call("leave", { participant: leaving.id });
195
+ const { room: seen } = await ada.call("watch", {
196
+ participant: participant.id,
197
+ after: -1,
198
+ waitMs: 0
199
+ });
200
+ equal(seen.participants.map((each) => each.as), ["ada"], "who ada sees once bob left");
201
+ await bob.call("leave", { participant: leaving.id });
202
+ }
203
+ },
204
+ {
205
+ name: "a room that has ended says so to a watch, and a token made before its end joins it no more",
206
+ async run(world) {
207
+ const room = roomFor("ended");
208
+ const ada = await caller(world, {
209
+ room,
210
+ as: "ada"
211
+ });
212
+ const { participant } = await ada.call("join", {});
213
+ await world.end(room);
214
+ const { room: seen } = await ada.call("watch", {
215
+ participant: participant.id,
216
+ after: -1,
217
+ waitMs: 0
218
+ });
219
+ equal({
220
+ state: seen.state,
221
+ participants: seen.participants
222
+ }, {
223
+ state: "ended",
224
+ participants: []
225
+ }, "the room as the watch sees it");
226
+ await ada.refused("join", {}, "ended", "joining with a token made before the end");
227
+ }
228
+ },
229
+ {
230
+ name: "a signal reaches its participant through their watch, and is gone once acked",
231
+ needs: "relay",
232
+ async run(world) {
233
+ const room = roomFor("signal");
234
+ const ada = await caller(world, {
235
+ room,
236
+ as: "ada"
237
+ }), bob = await caller(world, {
238
+ room,
239
+ as: "bob"
240
+ });
241
+ const { participant: from } = await ada.call("join", {});
242
+ const { participant: to, room: joined } = await bob.call("join", {});
243
+ await ada.call("signal", {
244
+ participant: from.id,
245
+ to: to.id,
246
+ sdp: {
247
+ type: "offer",
248
+ sdp: "v=0\r\n"
249
+ }
250
+ });
251
+ const { signals } = await bob.call("watch", {
252
+ participant: to.id,
253
+ after: joined.changed,
254
+ waitMs: 25e3
255
+ });
256
+ equal(signals.map((signal) => ({
257
+ from: signal.from,
258
+ sdp: signal.sdp
259
+ })), [{
260
+ from: from.id,
261
+ sdp: {
262
+ type: "offer",
263
+ sdp: "v=0\r\n"
264
+ }
265
+ }], "the signals bob's watch returns");
266
+ equal((await bob.call("watch", {
267
+ participant: to.id,
268
+ after: -1,
269
+ ack: signals[0].seq,
270
+ waitMs: 0
271
+ })).signals, [], "the signals once acked");
272
+ await ada.refused("signal", {
273
+ participant: from.id,
274
+ to: "p_nobody",
275
+ sdp: {
276
+ type: "offer",
277
+ sdp: "v=0\r\n"
278
+ }
279
+ }, "not-found", "a signal to someone not in the call");
280
+ }
281
+ }
282
+ ];
283
+ function equal(actual, expected, what) {
284
+ const a = JSON.stringify(sorted(actual)), e = JSON.stringify(sorted(expected));
285
+ if (a !== e) throw new Error(`${what}: expected ${e}, got ${a}`);
286
+ }
287
+ function sorted(value) {
288
+ if (Array.isArray(value)) return value.map(sorted);
289
+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a < b ? -1 : 1).map(([k, v]) => [k, sorted(v)]));
290
+ return value;
291
+ }
292
+ //#endregion
293
+ export { callsContract };
@@ -0,0 +1,147 @@
1
+ import { s as Json } from "../index-c616Dbux.mjs";
2
+ import { a as CallToken, c as Layer, d as TrackName, r as CallErrorCode } from "../protocol-BeBvbfKf.mjs";
3
+ //#region src/calls/index.d.ts
4
+ /** The most a message sent with `send` carries, as JSON. */
5
+ declare const MAX_MESSAGE_BYTES: number;
6
+ /** The most videos a participant receives at once, and how many of them at the full layer. */
7
+ declare const MAX_VIDEOS = 9;
8
+ declare const MAX_FULL_VIDEOS = 2;
9
+ /** Why a call or a call's request failed, in words a person reads; `code` is the one the wire carries. */
10
+ declare class CallError extends Error {
11
+ readonly code: CallErrorCode;
12
+ constructor(code: CallErrorCode, why: string);
13
+ }
14
+ /** Why a name can't be a room's, or undefined: 1 to 64 letters, digits, `-`, `_` and `.`, starting with a letter or digit. */
15
+ declare function roomProblem(name: unknown): string | undefined;
16
+ /** Why `as` can't name a participant, or undefined: 1 to 128 printable characters. */
17
+ declare function identityProblem(as: unknown): string | undefined;
18
+ /** What a token is made for: a room, who joins it as `as`, the name others see, and how long it lasts (3,600 seconds unless asked). */
19
+ interface CallTokenInput {
20
+ readonly room: string;
21
+ readonly as: string;
22
+ readonly name?: string;
23
+ readonly ttlSeconds?: number;
24
+ }
25
+ /**
26
+ * A token for one person in one room, made on the app's server: in a deployment on Midsummer with no key, and under
27
+ * `midsummer dev` by its stand-in. Hand it to the page, which joins with it.
28
+ *
29
+ * const token = await callToken({ room: "support-42", as: user.id, name: user.name })
30
+ */
31
+ declare function callToken(input: CallTokenInput): Promise<CallToken>;
32
+ /** Where a call is: joining, alone in the room, with someone, joining again after a drop, over, or failed with `error`. */
33
+ type CallState = "connecting" | "waiting" | "in-call" | "reconnecting" | "ended" | "failed";
34
+ /** Someone in the call. */
35
+ interface Participant {
36
+ readonly id: string;
37
+ /** Who the app says they are: a user id, `guest-…` or an agent's name. */
38
+ readonly as: string;
39
+ readonly name: string;
40
+ /** `voice`: an agent heard through its own address, with no WebRTC. */
41
+ readonly kind: "person" | "voice";
42
+ /** `away` while they haven't been heard from for 15 seconds; they come back or leave. */
43
+ readonly state: "joined" | "away" | "left";
44
+ readonly joinedAt: number;
45
+ /** What they publish, by name. */
46
+ readonly tracks: ReadonlyArray<{
47
+ readonly name: TrackName;
48
+ readonly kind: "audio" | "video";
49
+ }>;
50
+ /** Their tracks this call receives now, by name. */
51
+ readonly received: Readonly<Partial<Record<TrackName, MediaStreamTrack>>>;
52
+ }
53
+ /** A track this call publishes, and whether it is muted, so nothing of it is sent. */
54
+ interface LocalTrack {
55
+ readonly name: TrackName;
56
+ readonly track: MediaStreamTrack;
57
+ readonly muted: boolean;
58
+ }
59
+ /** What `on` listens to, and what each gives. */
60
+ interface CallEvents {
61
+ state: CallState;
62
+ participants: ReadonlyArray<Participant>;
63
+ /** The tracks this call publishes, after each publish, unpublish, mute and unmute. */
64
+ local: ReadonlyArray<LocalTrack>;
65
+ track: {
66
+ readonly participant: Participant;
67
+ readonly name: TrackName;
68
+ readonly track: MediaStreamTrack;
69
+ };
70
+ "track-ended": {
71
+ readonly participant: Participant;
72
+ readonly name: TrackName;
73
+ readonly track: MediaStreamTrack;
74
+ };
75
+ data: {
76
+ readonly from: Participant;
77
+ readonly data: Json;
78
+ };
79
+ /** Something done in the background failed without ending the call, such as receiving a track or renewing the token. */
80
+ error: CallError;
81
+ }
82
+ /** WebRTC, for code outside a browser: a library's `RTCPeerConnection`, and devices to capture from if it has them. */
83
+ interface Rtc {
84
+ readonly RTCPeerConnection: new (configuration?: RTCConfiguration) => RTCPeerConnection;
85
+ readonly MediaStream?: new (tracks?: MediaStreamTrack[]) => MediaStream;
86
+ readonly mediaDevices?: Pick<MediaDevices, "getUserMedia" | "getDisplayMedia">;
87
+ }
88
+ /** A token, or a function that asks the app's server for one (again before each runs out). */
89
+ type TokenSource = string | CallToken | (() => Promise<string | CallToken>);
90
+ interface JoinOptions {
91
+ readonly token: TokenSource;
92
+ /** Where the call wire is served: the token's `url` when it has one, else Midsummer's. */
93
+ readonly url?: string;
94
+ /** WebRTC outside a browser; the browser's when left out. */
95
+ readonly rtc?: Rtc;
96
+ /** Receive others' videos as they publish them, up to 9 at the half layer: true unless you choose them with `receive`. */
97
+ readonly autoVideo?: boolean;
98
+ }
99
+ /** A call joined with `join`. */
100
+ interface Call {
101
+ readonly room: string;
102
+ readonly state: CallState;
103
+ readonly error: CallError | undefined;
104
+ /** You, as the others see you. */
105
+ readonly me: Participant;
106
+ /** Everyone else in the room, each with the tracks received from them. */
107
+ readonly participants: ReadonlyArray<Participant>;
108
+ /** What you publish. */
109
+ readonly local: ReadonlyArray<LocalTrack>;
110
+ /** Calls `fn` with each event of that kind; returns what stops it. */
111
+ on<Event extends keyof CallEvents>(event: Event, fn: (value: CallEvents[Event]) => void): () => void;
112
+ /** Publishes the microphone and the camera (`true` captures them) or tracks of your own. Publishing one again replaces it. */
113
+ publish(tracks: {
114
+ readonly mic?: boolean | MediaStreamTrack;
115
+ readonly camera?: boolean | MediaStreamTrack;
116
+ }): Promise<void>;
117
+ /** Stops publishing a track, and stops the device when the call captured it. */
118
+ unpublish(name: TrackName): Promise<void>;
119
+ /** Sends nothing of a track until `unmute`; others still see it published. */
120
+ mute(name: TrackName): Promise<void>;
121
+ unmute(name: TrackName): Promise<void>;
122
+ /** Shares a screen, window or tab the person picks, as `screen`, and its sound as `screen-audio` when there is any. */
123
+ readonly screen: {
124
+ share(): Promise<void>;
125
+ stop(): Promise<void>;
126
+ };
127
+ /** Receives one of someone's tracks, a video at `layer` (`h` unless asked). */
128
+ receive(participantId: string, name: TrackName, options?: {
129
+ readonly layer?: Layer;
130
+ }): Promise<void>;
131
+ /** Switches a video received to another layer. */
132
+ setLayer(participantId: string, name: TrackName, layer: Layer): Promise<void>;
133
+ /** Stops receiving one of someone's tracks, as a grid does for a tile out of view; it isn't received again until `receive`. */
134
+ stopReceiving(participantId: string, name: TrackName): Promise<void>;
135
+ /** Sends a message to everyone else in the call, at most 16 KiB as JSON. */
136
+ send(data: Json): void;
137
+ /** Leaves the call: your tracks stop, the devices the call captured are released, and the state is `ended`. */
138
+ leave(): Promise<void>;
139
+ }
140
+ /**
141
+ * Joins a room with a token the app's server made for it, and resolves once you're in: `waiting` or `in-call`. A
142
+ * refusal rejects with a `CallError`: `forbidden` for a token that isn't good, ran out or is for someone removed,
143
+ * `full`, `ended` for a room ended since the token was made, `unavailable` when the call can't be reached.
144
+ */
145
+ declare function join(room: string, options: JoinOptions): Promise<Call>;
146
+ //#endregion
147
+ export { Call, CallError, type CallErrorCode, CallEvents, CallState, type CallToken, CallTokenInput, JoinOptions, type Json, type Layer, LocalTrack, MAX_FULL_VIDEOS, MAX_MESSAGE_BYTES, MAX_VIDEOS, Participant, Rtc, TokenSource, type TrackName, callToken, identityProblem, join, roomProblem };