@burdenoff/microfe-stewards 2026.1201.2 → 2026.1201.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/dev/liveDeskMocks.d.ts +2 -0
- package/dist/dev/shellGateway.d.ts +9 -0
- package/dist/dev/shellPermissions.d.ts +9 -0
- package/dist/generated/global-types.d.ts +398 -7
- package/dist/generated/wspace-operations.d.ts +183 -0
- package/dist/generated/wspace-operations.js +107 -39
- package/dist/generated/wspace-operations.js.map +1 -1
- package/dist/generated/wspace-types.d.ts +1789 -15
- package/dist/generated/wspace-types.js +7 -5
- package/dist/generated/wspace-types.js.map +1 -1
- package/dist/stewards/components/ControlBanner.d.ts +7 -0
- package/dist/stewards/components/ControlBanner.js +21 -0
- package/dist/stewards/components/ControlBanner.js.map +1 -0
- package/dist/stewards/components/LiveDeskPanel.d.ts +17 -0
- package/dist/stewards/components/LiveDeskPanel.js +120 -0
- package/dist/stewards/components/LiveDeskPanel.js.map +1 -0
- package/dist/stewards/i18n/en.d.ts +46 -0
- package/dist/stewards/i18n/en.js +46 -0
- package/dist/stewards/i18n/en.js.map +1 -1
- package/dist/stewards/live/DeskCanvas.d.ts +20 -0
- package/dist/stewards/live/DeskCanvas.js +95 -0
- package/dist/stewards/live/DeskCanvas.js.map +1 -0
- package/dist/stewards/live/DeskStreamConnection.d.ts +123 -0
- package/dist/stewards/live/DeskStreamConnection.js +239 -0
- package/dist/stewards/live/DeskStreamConnection.js.map +1 -0
- package/dist/stewards/live/backoff.d.ts +2 -0
- package/dist/stewards/live/backoff.js +8 -0
- package/dist/stewards/live/backoff.js.map +1 -0
- package/dist/stewards/live/browserConnection.d.ts +20 -0
- package/dist/stewards/live/browserConnection.js +40 -0
- package/dist/stewards/live/browserConnection.js.map +1 -0
- package/dist/stewards/live/describeStream.d.ts +15 -0
- package/dist/stewards/live/describeStream.js +78 -0
- package/dist/stewards/live/describeStream.js.map +1 -0
- package/dist/stewards/live/mintPass.d.ts +9 -0
- package/dist/stewards/live/mintPass.js +59 -0
- package/dist/stewards/live/mintPass.js.map +1 -0
- package/dist/stewards/live/protocol.d.ts +81 -0
- package/dist/stewards/live/protocol.js +88 -0
- package/dist/stewards/live/protocol.js.map +1 -0
- package/dist/stewards/live/useDeskStream.d.ts +17 -0
- package/dist/stewards/live/useDeskStream.js +25 -0
- package/dist/stewards/live/useDeskStream.js.map +1 -0
- package/dist/stewards/pages/StewardRunPage.js +26 -20
- package/dist/stewards/pages/StewardRunPage.js.map +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { StreamEndReason, StreamMode } from './protocol';
|
|
2
|
+
export type StreamPhase = 'idle' | 'connecting' | 'live' | 'reconnecting' | 'ended' | 'failed';
|
|
3
|
+
export type DeskHolder = 'steward' | 'person';
|
|
4
|
+
export interface StreamState {
|
|
5
|
+
phase: StreamPhase;
|
|
6
|
+
/** The mode being connected or streamed. */
|
|
7
|
+
mode: StreamMode | null;
|
|
8
|
+
/** Who holds the desk, as the pass said at mint time. */
|
|
9
|
+
holder: DeskHolder | null;
|
|
10
|
+
/** Reconnect attempt number while `reconnecting`, else 0. */
|
|
11
|
+
attempt: number;
|
|
12
|
+
/** Set when `phase` is `ended` or `failed`. */
|
|
13
|
+
reason: StreamEndReason | null;
|
|
14
|
+
/** True once the desk has sent at least one frame on this connection. */
|
|
15
|
+
hasFrame: boolean;
|
|
16
|
+
}
|
|
17
|
+
export declare const INITIAL_STREAM_STATE: StreamState;
|
|
18
|
+
/** What `mint` returns: the API's pass, with the expiry as epoch milliseconds. */
|
|
19
|
+
export interface StreamPass {
|
|
20
|
+
token: string;
|
|
21
|
+
relayPath: string;
|
|
22
|
+
mode: StreamMode;
|
|
23
|
+
expiresAtMs: number;
|
|
24
|
+
holder: DeskHolder;
|
|
25
|
+
}
|
|
26
|
+
/** A refused or failed mint. `retryable` is false for a refusal that asking again will not change. */
|
|
27
|
+
export declare class MintError extends Error {
|
|
28
|
+
readonly retryable: boolean;
|
|
29
|
+
readonly forbidden: boolean;
|
|
30
|
+
constructor(message: string, options: {
|
|
31
|
+
retryable: boolean;
|
|
32
|
+
forbidden?: boolean;
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
export interface SocketLike {
|
|
36
|
+
binaryType: string;
|
|
37
|
+
onopen: (() => void) | null;
|
|
38
|
+
onmessage: ((event: {
|
|
39
|
+
data: unknown;
|
|
40
|
+
}) => void) | null;
|
|
41
|
+
onclose: ((event: {
|
|
42
|
+
code: number;
|
|
43
|
+
}) => void) | null;
|
|
44
|
+
onerror: (() => void) | null;
|
|
45
|
+
send(data: string): void;
|
|
46
|
+
close(code?: number, reason?: string): void;
|
|
47
|
+
}
|
|
48
|
+
export interface Timers {
|
|
49
|
+
setTimeout(fn: () => void, ms: number): unknown;
|
|
50
|
+
clearTimeout(id: unknown): void;
|
|
51
|
+
setInterval(fn: () => void, ms: number): unknown;
|
|
52
|
+
clearInterval(id: unknown): void;
|
|
53
|
+
}
|
|
54
|
+
export interface StreamDeps {
|
|
55
|
+
mint(mode: StreamMode): Promise<StreamPass>;
|
|
56
|
+
/** The gateway origin the relay path hangs off, e.g. `https://graphqlworkspaces.burdenoff.com`. */
|
|
57
|
+
gatewayBaseUrl(): string;
|
|
58
|
+
/** The signed-in session's two tokens, or null when there is none. */
|
|
59
|
+
credentials(): {
|
|
60
|
+
authorization: string;
|
|
61
|
+
workspaceAuthorization: string;
|
|
62
|
+
} | null;
|
|
63
|
+
createSocket(url: string): SocketLike;
|
|
64
|
+
/** A desk frame (binary). Text frames the viewer does not know are dropped. */
|
|
65
|
+
onFrame(data: ArrayBuffer): void;
|
|
66
|
+
now(): number;
|
|
67
|
+
timers: Timers;
|
|
68
|
+
random(): number;
|
|
69
|
+
/** Whether the person can see the page; keepalives stop while it is hidden so idle works. */
|
|
70
|
+
isVisible(): boolean;
|
|
71
|
+
}
|
|
72
|
+
export interface StreamTuning {
|
|
73
|
+
/** No `ready` within this long after the socket opens: treat as a drop. */
|
|
74
|
+
readyTimeoutMs: number;
|
|
75
|
+
keepaliveMs: number;
|
|
76
|
+
/** Consecutive failed attempts before giving up. */
|
|
77
|
+
maxAttempts: number;
|
|
78
|
+
/** A stream that lived this long counts as healthy and resets the attempt count. */
|
|
79
|
+
healthyAfterMs: number;
|
|
80
|
+
/** Close this close to the pass expiry means "renew", not "sign in". */
|
|
81
|
+
expirySlackMs: number;
|
|
82
|
+
/** Renewals in a row (no healthy stream between) before treating it as a failure. */
|
|
83
|
+
maxRenewals: number;
|
|
84
|
+
}
|
|
85
|
+
type Listener = (state: StreamState) => void;
|
|
86
|
+
export declare class DeskStreamConnection {
|
|
87
|
+
private readonly deps;
|
|
88
|
+
private state;
|
|
89
|
+
private readonly listeners;
|
|
90
|
+
private readonly tuning;
|
|
91
|
+
private generation;
|
|
92
|
+
private socket;
|
|
93
|
+
private retryTimer;
|
|
94
|
+
private readyTimer;
|
|
95
|
+
private keepaliveTimer;
|
|
96
|
+
private attempts;
|
|
97
|
+
private signInRetried;
|
|
98
|
+
private renewals;
|
|
99
|
+
private liveSince;
|
|
100
|
+
private passExpiresAtMs;
|
|
101
|
+
constructor(deps: StreamDeps, tuning?: Partial<StreamTuning>);
|
|
102
|
+
getState: () => StreamState;
|
|
103
|
+
subscribe: (listener: Listener) => (() => void);
|
|
104
|
+
/** Start (or restart in another mode). Any running connection is closed first. */
|
|
105
|
+
start(mode: StreamMode): void;
|
|
106
|
+
/** Stop on purpose (leaving the page, handing back). Ends quietly; nothing is retried. */
|
|
107
|
+
stop(): void;
|
|
108
|
+
/** Whether input can be sent right now: a live control stream. */
|
|
109
|
+
canSend(): boolean;
|
|
110
|
+
/** Write one input frame. Returns false (and drops it) when the stream is not live control. */
|
|
111
|
+
send(frame: string): boolean;
|
|
112
|
+
private set;
|
|
113
|
+
private patch;
|
|
114
|
+
private clearTimers;
|
|
115
|
+
private teardown;
|
|
116
|
+
private connect;
|
|
117
|
+
private onReady;
|
|
118
|
+
private dropSocket;
|
|
119
|
+
private onClosed;
|
|
120
|
+
private scheduleRetry;
|
|
121
|
+
private finish;
|
|
122
|
+
}
|
|
123
|
+
export {};
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
import { backoffDelay as e } from "./backoff.js";
|
|
2
|
+
import { KEEPALIVE_FRAME as t, buildRelayUrl as n, classifyClose as r, connectFrame as i, parseReady as a } from "./protocol.js";
|
|
3
|
+
// src/stewards/live/DeskStreamConnection.ts
|
|
4
|
+
var o = {
|
|
5
|
+
phase: "idle",
|
|
6
|
+
mode: null,
|
|
7
|
+
holder: null,
|
|
8
|
+
attempt: 0,
|
|
9
|
+
reason: null,
|
|
10
|
+
hasFrame: !1
|
|
11
|
+
}, s = class extends Error {
|
|
12
|
+
retryable;
|
|
13
|
+
forbidden;
|
|
14
|
+
constructor(e, t) {
|
|
15
|
+
super(e), this.name = "MintError", this.retryable = t.retryable, this.forbidden = t.forbidden ?? !1;
|
|
16
|
+
}
|
|
17
|
+
}, c = {
|
|
18
|
+
readyTimeoutMs: 1e4,
|
|
19
|
+
keepaliveMs: 3e4,
|
|
20
|
+
maxAttempts: 6,
|
|
21
|
+
healthyAfterMs: 1e4,
|
|
22
|
+
expirySlackMs: 5e3,
|
|
23
|
+
maxRenewals: 3
|
|
24
|
+
}, l = class {
|
|
25
|
+
deps;
|
|
26
|
+
state = o;
|
|
27
|
+
listeners = /* @__PURE__ */ new Set();
|
|
28
|
+
tuning;
|
|
29
|
+
generation = 0;
|
|
30
|
+
socket = null;
|
|
31
|
+
retryTimer = null;
|
|
32
|
+
readyTimer = null;
|
|
33
|
+
keepaliveTimer = null;
|
|
34
|
+
attempts = 0;
|
|
35
|
+
signInRetried = !1;
|
|
36
|
+
renewals = 0;
|
|
37
|
+
liveSince = 0;
|
|
38
|
+
passExpiresAtMs = 0;
|
|
39
|
+
constructor(e, t = {}) {
|
|
40
|
+
this.deps = e, this.tuning = {
|
|
41
|
+
...c,
|
|
42
|
+
...t
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
getState = () => this.state;
|
|
46
|
+
subscribe = (e) => (this.listeners.add(e), () => {
|
|
47
|
+
this.listeners.delete(e);
|
|
48
|
+
});
|
|
49
|
+
start(e) {
|
|
50
|
+
this.teardown(), this.generation += 1, this.attempts = 0, this.signInRetried = !1, this.renewals = 0, this.set({
|
|
51
|
+
...o,
|
|
52
|
+
phase: "connecting",
|
|
53
|
+
mode: e
|
|
54
|
+
}), this.connect(this.generation, e);
|
|
55
|
+
}
|
|
56
|
+
stop() {
|
|
57
|
+
this.teardown(), this.generation += 1, this.set(o);
|
|
58
|
+
}
|
|
59
|
+
canSend() {
|
|
60
|
+
return this.state.phase === "live" && this.state.mode === "control" && this.socket !== null;
|
|
61
|
+
}
|
|
62
|
+
send(e) {
|
|
63
|
+
let t = this.socket;
|
|
64
|
+
if (!t || !this.canSend()) return !1;
|
|
65
|
+
try {
|
|
66
|
+
return t.send(e), !0;
|
|
67
|
+
} catch {
|
|
68
|
+
return !1;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
set(e) {
|
|
72
|
+
this.state = e;
|
|
73
|
+
for (let t of this.listeners) t(e);
|
|
74
|
+
}
|
|
75
|
+
patch(e) {
|
|
76
|
+
this.set({
|
|
77
|
+
...this.state,
|
|
78
|
+
...e
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
clearTimers() {
|
|
82
|
+
let { timers: e } = this.deps;
|
|
83
|
+
this.retryTimer !== null && e.clearTimeout(this.retryTimer), this.readyTimer !== null && e.clearTimeout(this.readyTimer), this.keepaliveTimer !== null && e.clearInterval(this.keepaliveTimer), this.retryTimer = null, this.readyTimer = null, this.keepaliveTimer = null;
|
|
84
|
+
}
|
|
85
|
+
teardown() {
|
|
86
|
+
this.clearTimers();
|
|
87
|
+
let e = this.socket;
|
|
88
|
+
if (this.socket = null, e) {
|
|
89
|
+
e.onopen = null, e.onmessage = null, e.onclose = null, e.onerror = null;
|
|
90
|
+
try {
|
|
91
|
+
e.close(1e3, "viewer closed");
|
|
92
|
+
} catch {}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
async connect(e, t) {
|
|
96
|
+
let r;
|
|
97
|
+
try {
|
|
98
|
+
r = await this.deps.mint(t);
|
|
99
|
+
} catch (n) {
|
|
100
|
+
if (e !== this.generation) return;
|
|
101
|
+
if (n instanceof s && !n.retryable) {
|
|
102
|
+
this.finish("failed", n.forbidden ? "forbidden" : "mintFailed");
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
this.scheduleRetry(e, t);
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
if (e !== this.generation) return;
|
|
109
|
+
let o = n(this.deps.gatewayBaseUrl(), r.relayPath), c = this.deps.credentials();
|
|
110
|
+
if (!c) {
|
|
111
|
+
this.finish("failed", "signIn");
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
if (!o) {
|
|
115
|
+
this.finish("failed", "badRequest");
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
this.passExpiresAtMs = r.expiresAtMs, this.patch({
|
|
119
|
+
holder: r.holder,
|
|
120
|
+
mode: r.mode
|
|
121
|
+
});
|
|
122
|
+
let l;
|
|
123
|
+
try {
|
|
124
|
+
l = this.deps.createSocket(o);
|
|
125
|
+
} catch {
|
|
126
|
+
this.scheduleRetry(e, t);
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
l.binaryType = "arraybuffer", this.socket = l;
|
|
130
|
+
let u = !1;
|
|
131
|
+
l.onopen = () => {
|
|
132
|
+
e === this.generation && (l.send(i({
|
|
133
|
+
token: r.token,
|
|
134
|
+
authorization: c.authorization,
|
|
135
|
+
workspaceAuthorization: c.workspaceAuthorization
|
|
136
|
+
})), this.readyTimer = this.deps.timers.setTimeout(() => {
|
|
137
|
+
e !== this.generation || u || (this.dropSocket(), this.scheduleRetry(e, t));
|
|
138
|
+
}, this.tuning.readyTimeoutMs));
|
|
139
|
+
}, l.onmessage = (t) => {
|
|
140
|
+
if (e !== this.generation) return;
|
|
141
|
+
let { data: n } = t;
|
|
142
|
+
if (!u) {
|
|
143
|
+
let t = typeof n == "string" ? a(n) : null;
|
|
144
|
+
if (!t || t.mode !== r.mode) {
|
|
145
|
+
this.dropSocket(), this.finish("failed", "badRequest");
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
u = !0, this.onReady(e, t.expiresAt);
|
|
149
|
+
} else if (n instanceof ArrayBuffer) {
|
|
150
|
+
if (n.byteLength === 0 || n.byteLength > 16777216) return;
|
|
151
|
+
this.state.hasFrame || this.patch({ hasFrame: !0 }), this.deps.onFrame(n);
|
|
152
|
+
}
|
|
153
|
+
}, l.onerror = () => {}, l.onclose = (n) => {
|
|
154
|
+
e === this.generation && this.onClosed(e, t, n.code, u);
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
onReady(e, n) {
|
|
158
|
+
let { timers: r } = this.deps;
|
|
159
|
+
this.readyTimer !== null && r.clearTimeout(this.readyTimer), this.readyTimer = null, this.passExpiresAtMs = n, this.liveSince = this.deps.now(), this.patch({
|
|
160
|
+
phase: "live",
|
|
161
|
+
attempt: 0,
|
|
162
|
+
reason: null,
|
|
163
|
+
hasFrame: !1
|
|
164
|
+
}), this.keepaliveTimer = r.setInterval(() => {
|
|
165
|
+
e === this.generation && this.deps.isVisible() && this.socket?.send(t);
|
|
166
|
+
}, this.tuning.keepaliveMs);
|
|
167
|
+
}
|
|
168
|
+
dropSocket() {
|
|
169
|
+
let e = this.socket;
|
|
170
|
+
if (this.socket = null, e) {
|
|
171
|
+
e.onopen = null, e.onmessage = null, e.onclose = null, e.onerror = null;
|
|
172
|
+
try {
|
|
173
|
+
e.close(1e3, "viewer closed");
|
|
174
|
+
} catch {}
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
onClosed(e, t, n, i) {
|
|
178
|
+
let a = i ? this.deps.now() - this.liveSince : 0;
|
|
179
|
+
this.clearTimers(), this.socket = null, i && a >= this.tuning.healthyAfterMs && (this.attempts = 0, this.renewals = 0);
|
|
180
|
+
let o = r(n);
|
|
181
|
+
switch (o.kind) {
|
|
182
|
+
case "ended":
|
|
183
|
+
this.finish("ended", o.reason);
|
|
184
|
+
return;
|
|
185
|
+
case "failed":
|
|
186
|
+
this.finish("failed", o.reason);
|
|
187
|
+
return;
|
|
188
|
+
case "renewOrSignIn": {
|
|
189
|
+
let n = this.deps.now() >= this.passExpiresAtMs - this.tuning.expirySlackMs;
|
|
190
|
+
if (i && n && this.renewals < this.tuning.maxRenewals) {
|
|
191
|
+
this.renewals += 1, this.patch({
|
|
192
|
+
phase: "reconnecting",
|
|
193
|
+
attempt: 0
|
|
194
|
+
}), this.connect(e, t);
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
if (!this.signInRetried) {
|
|
198
|
+
this.signInRetried = !0, this.patch({
|
|
199
|
+
phase: "reconnecting",
|
|
200
|
+
attempt: 0
|
|
201
|
+
}), this.connect(e, t);
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
this.finish("failed", "signIn");
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
case "reconnect":
|
|
208
|
+
this.scheduleRetry(e, t, n === 4429 ? "tooMany" : void 0);
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
scheduleRetry(t, n, r) {
|
|
213
|
+
if (t !== this.generation) return;
|
|
214
|
+
if (this.attempts += 1, this.attempts > this.tuning.maxAttempts) {
|
|
215
|
+
this.finish("failed", r ?? "unavailable");
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
this.patch({
|
|
219
|
+
phase: "reconnecting",
|
|
220
|
+
attempt: this.attempts,
|
|
221
|
+
hasFrame: !1
|
|
222
|
+
});
|
|
223
|
+
let i = e(this.attempts, this.deps.random);
|
|
224
|
+
this.retryTimer = this.deps.timers.setTimeout(() => {
|
|
225
|
+
this.retryTimer = null, t === this.generation && this.connect(t, n);
|
|
226
|
+
}, i);
|
|
227
|
+
}
|
|
228
|
+
finish(e, t) {
|
|
229
|
+
this.clearTimers(), this.dropSocket(), this.patch({
|
|
230
|
+
phase: e,
|
|
231
|
+
reason: t,
|
|
232
|
+
attempt: 0,
|
|
233
|
+
hasFrame: !1
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
};
|
|
237
|
+
export { l as DeskStreamConnection, o as INITIAL_STREAM_STATE, s as MintError };
|
|
238
|
+
|
|
239
|
+
//# sourceMappingURL=DeskStreamConnection.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"DeskStreamConnection.js","names":["INITIAL_STREAM_STATE","MintError","message","options","DEFAULT_TUNING","DeskStreamConnection","deps","tuning","listener","mode","socket","frame","next","partial","timers","pass","error","generation","url","buildRelayUrl","session","ready","connectFrame","event","data","parseReady","expiresAtMs","KEEPALIVE_FRAME","livedMs","wasReady","action","classifyClose","code","nearExpiry","exhaustedReason","delay","backoffDelay"],"sources":["../../../src/stewards/live/DeskStreamConnection.ts"],"sourcesContent":["/**\n * The viewer's connection to the gateway's `/steward-desk` relay (BOFF-16552): mint a pass, open\n * the socket, authenticate in the first frame, relay desk frames out and input in, and recover\n * from drops. Plain TypeScript with every browser dependency injected, so the whole state machine\n * runs in unit tests with a fake socket and a manual clock.\n *\n * What it guarantees:\n * - A pass works once, so every connection attempt, including a reconnect, mints a new one. The\n * pass and the session tokens live only inside `connect()`; they are not stored in state, the\n * DOM or a URL, and never logged.\n * - Input is written to the socket and forgotten. Nothing in here logs, stores or echoes a frame.\n * - A close is acted on by its code (see `classifyClose`). Only a drop is retried, with backoff\n * and a cap. A finished lease, a refusal or an idle close is shown, not retried.\n * - An old socket can never change the state of a newer one (generation check).\n */\nimport { backoffDelay } from './backoff';\nimport {\n classifyClose,\n buildRelayUrl,\n connectFrame,\n KEEPALIVE_FRAME,\n MAX_FRAME_BYTES,\n parseReady,\n type StreamEndReason,\n type StreamMode,\n} from './protocol';\n\nexport type StreamPhase = 'idle' | 'connecting' | 'live' | 'reconnecting' | 'ended' | 'failed';\n\nexport type DeskHolder = 'steward' | 'person';\n\nexport interface StreamState {\n phase: StreamPhase;\n /** The mode being connected or streamed. */\n mode: StreamMode | null;\n /** Who holds the desk, as the pass said at mint time. */\n holder: DeskHolder | null;\n /** Reconnect attempt number while `reconnecting`, else 0. */\n attempt: number;\n /** Set when `phase` is `ended` or `failed`. */\n reason: StreamEndReason | null;\n /** True once the desk has sent at least one frame on this connection. */\n hasFrame: boolean;\n}\n\nexport const INITIAL_STREAM_STATE: StreamState = {\n phase: 'idle',\n mode: null,\n holder: null,\n attempt: 0,\n reason: null,\n hasFrame: false,\n};\n\n/** What `mint` returns: the API's pass, with the expiry as epoch milliseconds. */\nexport interface StreamPass {\n token: string;\n relayPath: string;\n mode: StreamMode;\n expiresAtMs: number;\n holder: DeskHolder;\n}\n\n/** A refused or failed mint. `retryable` is false for a refusal that asking again will not change. */\nexport class MintError extends Error {\n readonly retryable: boolean;\n readonly forbidden: boolean;\n constructor(message: string, options: { retryable: boolean; forbidden?: boolean }) {\n super(message);\n this.name = 'MintError';\n this.retryable = options.retryable;\n this.forbidden = options.forbidden ?? false;\n }\n}\n\nexport interface SocketLike {\n binaryType: string;\n onopen: (() => void) | null;\n onmessage: ((event: { data: unknown }) => void) | null;\n onclose: ((event: { code: number }) => void) | null;\n onerror: (() => void) | null;\n send(data: string): void;\n close(code?: number, reason?: string): void;\n}\n\nexport interface Timers {\n setTimeout(fn: () => void, ms: number): unknown;\n clearTimeout(id: unknown): void;\n setInterval(fn: () => void, ms: number): unknown;\n clearInterval(id: unknown): void;\n}\n\nexport interface StreamDeps {\n mint(mode: StreamMode): Promise<StreamPass>;\n /** The gateway origin the relay path hangs off, e.g. `https://graphqlworkspaces.burdenoff.com`. */\n gatewayBaseUrl(): string;\n /** The signed-in session's two tokens, or null when there is none. */\n credentials(): { authorization: string; workspaceAuthorization: string } | null;\n createSocket(url: string): SocketLike;\n /** A desk frame (binary). Text frames the viewer does not know are dropped. */\n onFrame(data: ArrayBuffer): void;\n now(): number;\n timers: Timers;\n random(): number;\n /** Whether the person can see the page; keepalives stop while it is hidden so idle works. */\n isVisible(): boolean;\n}\n\nexport interface StreamTuning {\n /** No `ready` within this long after the socket opens: treat as a drop. */\n readyTimeoutMs: number;\n keepaliveMs: number;\n /** Consecutive failed attempts before giving up. */\n maxAttempts: number;\n /** A stream that lived this long counts as healthy and resets the attempt count. */\n healthyAfterMs: number;\n /** Close this close to the pass expiry means \"renew\", not \"sign in\". */\n expirySlackMs: number;\n /** Renewals in a row (no healthy stream between) before treating it as a failure. */\n maxRenewals: number;\n}\n\nconst DEFAULT_TUNING: StreamTuning = {\n readyTimeoutMs: 10_000,\n keepaliveMs: 30_000,\n maxAttempts: 6,\n healthyAfterMs: 10_000,\n expirySlackMs: 5_000,\n maxRenewals: 3,\n};\n\ntype Listener = (state: StreamState) => void;\n\nexport class DeskStreamConnection {\n private state: StreamState = INITIAL_STREAM_STATE;\n private readonly listeners = new Set<Listener>();\n private readonly tuning: StreamTuning;\n private generation = 0;\n private socket: SocketLike | null = null;\n private retryTimer: unknown = null;\n private readyTimer: unknown = null;\n private keepaliveTimer: unknown = null;\n private attempts = 0;\n private signInRetried = false;\n private renewals = 0;\n private liveSince = 0;\n private passExpiresAtMs = 0;\n\n constructor(\n private readonly deps: StreamDeps,\n tuning: Partial<StreamTuning> = {}\n ) {\n this.tuning = { ...DEFAULT_TUNING, ...tuning };\n }\n\n getState = (): StreamState => this.state;\n\n subscribe = (listener: Listener): (() => void) => {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n };\n\n /** Start (or restart in another mode). Any running connection is closed first. */\n start(mode: StreamMode): void {\n this.teardown();\n this.generation += 1;\n this.attempts = 0;\n this.signInRetried = false;\n this.renewals = 0;\n this.set({ ...INITIAL_STREAM_STATE, phase: 'connecting', mode });\n void this.connect(this.generation, mode);\n }\n\n /** Stop on purpose (leaving the page, handing back). Ends quietly; nothing is retried. */\n stop(): void {\n this.teardown();\n this.generation += 1;\n this.set(INITIAL_STREAM_STATE);\n }\n\n /** Whether input can be sent right now: a live control stream. */\n canSend(): boolean {\n return this.state.phase === 'live' && this.state.mode === 'control' && this.socket !== null;\n }\n\n /** Write one input frame. Returns false (and drops it) when the stream is not live control. */\n send(frame: string): boolean {\n const socket = this.socket;\n if (!socket || !this.canSend()) return false;\n try {\n socket.send(frame);\n return true;\n } catch {\n return false;\n }\n }\n\n private set(next: StreamState): void {\n this.state = next;\n for (const listener of this.listeners) listener(next);\n }\n\n private patch(partial: Partial<StreamState>): void {\n this.set({ ...this.state, ...partial });\n }\n\n private clearTimers(): void {\n const { timers } = this.deps;\n if (this.retryTimer !== null) timers.clearTimeout(this.retryTimer);\n if (this.readyTimer !== null) timers.clearTimeout(this.readyTimer);\n if (this.keepaliveTimer !== null) timers.clearInterval(this.keepaliveTimer);\n this.retryTimer = null;\n this.readyTimer = null;\n this.keepaliveTimer = null;\n }\n\n private teardown(): void {\n this.clearTimers();\n const socket = this.socket;\n this.socket = null;\n if (socket) {\n socket.onopen = null;\n socket.onmessage = null;\n socket.onclose = null;\n socket.onerror = null;\n try {\n socket.close(1000, 'viewer closed');\n } catch {\n // Already closed.\n }\n }\n }\n\n private async connect(generation: number, mode: StreamMode): Promise<void> {\n let pass: StreamPass;\n try {\n pass = await this.deps.mint(mode);\n } catch (error) {\n if (generation !== this.generation) return;\n if (error instanceof MintError && !error.retryable) {\n this.finish('failed', error.forbidden ? 'forbidden' : 'mintFailed');\n return;\n }\n this.scheduleRetry(generation, mode);\n return;\n }\n if (generation !== this.generation) return;\n\n const url = buildRelayUrl(this.deps.gatewayBaseUrl(), pass.relayPath);\n const session = this.deps.credentials();\n if (!session) {\n this.finish('failed', 'signIn');\n return;\n }\n if (!url) {\n // The API named a path that is not on the gateway: never send credentials to it.\n this.finish('failed', 'badRequest');\n return;\n }\n\n this.passExpiresAtMs = pass.expiresAtMs;\n this.patch({ holder: pass.holder, mode: pass.mode });\n\n let socket: SocketLike;\n try {\n socket = this.deps.createSocket(url);\n } catch {\n this.scheduleRetry(generation, mode);\n return;\n }\n socket.binaryType = 'arraybuffer';\n this.socket = socket;\n\n let ready = false;\n socket.onopen = () => {\n if (generation !== this.generation) return;\n socket.send(\n connectFrame({\n token: pass.token,\n authorization: session.authorization,\n workspaceAuthorization: session.workspaceAuthorization,\n })\n );\n this.readyTimer = this.deps.timers.setTimeout(() => {\n if (generation !== this.generation || ready) return;\n this.dropSocket();\n this.scheduleRetry(generation, mode);\n }, this.tuning.readyTimeoutMs);\n };\n socket.onmessage = (event) => {\n if (generation !== this.generation) return;\n const { data } = event;\n if (!ready) {\n const frame = typeof data === 'string' ? parseReady(data) : null;\n if (!frame || frame.mode !== pass.mode) {\n this.dropSocket();\n this.finish('failed', 'badRequest');\n return;\n }\n ready = true;\n this.onReady(generation, frame.expiresAt);\n return;\n }\n if (data instanceof ArrayBuffer) {\n if (data.byteLength === 0 || data.byteLength > MAX_FRAME_BYTES) return;\n if (!this.state.hasFrame) this.patch({ hasFrame: true });\n this.deps.onFrame(data);\n }\n // A text frame after `ready` is desk state the viewer has no use for yet.\n };\n socket.onerror = () => {\n // The close event that follows carries the code; nothing to do here.\n };\n socket.onclose = (event) => {\n if (generation !== this.generation) return;\n this.onClosed(generation, mode, event.code, ready);\n };\n }\n\n private onReady(generation: number, expiresAtMs: number): void {\n const { timers } = this.deps;\n if (this.readyTimer !== null) timers.clearTimeout(this.readyTimer);\n this.readyTimer = null;\n this.passExpiresAtMs = expiresAtMs;\n this.liveSince = this.deps.now();\n this.patch({ phase: 'live', attempt: 0, reason: null, hasFrame: false });\n this.keepaliveTimer = timers.setInterval(() => {\n if (generation !== this.generation) return;\n // Hidden tab: stay quiet so the relay's idle timeout can close an abandoned view.\n if (!this.deps.isVisible()) return;\n this.socket?.send(KEEPALIVE_FRAME);\n }, this.tuning.keepaliveMs);\n }\n\n private dropSocket(): void {\n const socket = this.socket;\n this.socket = null;\n if (!socket) return;\n socket.onopen = null;\n socket.onmessage = null;\n socket.onclose = null;\n socket.onerror = null;\n try {\n socket.close(1000, 'viewer closed');\n } catch {\n // Already closed.\n }\n }\n\n private onClosed(generation: number, mode: StreamMode, code: number, wasReady: boolean): void {\n const livedMs = wasReady ? this.deps.now() - this.liveSince : 0;\n this.clearTimers();\n this.socket = null;\n if (wasReady && livedMs >= this.tuning.healthyAfterMs) {\n this.attempts = 0;\n this.renewals = 0;\n }\n const action = classifyClose(code);\n switch (action.kind) {\n case 'ended':\n this.finish('ended', action.reason);\n return;\n case 'failed':\n this.finish('failed', action.reason);\n return;\n case 'renewOrSignIn': {\n const nearExpiry = this.deps.now() >= this.passExpiresAtMs - this.tuning.expirySlackMs;\n if (wasReady && nearExpiry && this.renewals < this.tuning.maxRenewals) {\n // The pass ran out under a healthy stream: mint another and carry on.\n this.renewals += 1;\n this.patch({ phase: 'reconnecting', attempt: 0 });\n void this.connect(generation, mode);\n return;\n }\n if (!this.signInRetried) {\n // One retry with a fresh pass covers a pass that was used or expired in transit.\n this.signInRetried = true;\n this.patch({ phase: 'reconnecting', attempt: 0 });\n void this.connect(generation, mode);\n return;\n }\n this.finish('failed', 'signIn');\n return;\n }\n case 'reconnect':\n this.scheduleRetry(generation, mode, code === 4429 ? 'tooMany' : undefined);\n return;\n }\n }\n\n private scheduleRetry(\n generation: number,\n mode: StreamMode,\n exhaustedReason?: StreamEndReason\n ): void {\n if (generation !== this.generation) return;\n this.attempts += 1;\n if (this.attempts > this.tuning.maxAttempts) {\n this.finish('failed', exhaustedReason ?? 'unavailable');\n return;\n }\n this.patch({ phase: 'reconnecting', attempt: this.attempts, hasFrame: false });\n const delay = backoffDelay(this.attempts, this.deps.random);\n this.retryTimer = this.deps.timers.setTimeout(() => {\n this.retryTimer = null;\n if (generation !== this.generation) return;\n void this.connect(generation, mode);\n }, delay);\n }\n\n private finish(phase: 'ended' | 'failed', reason: StreamEndReason): void {\n this.clearTimers();\n this.dropSocket();\n this.patch({ phase, reason,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+1,8 @@
|
|
|
1
|
+
// src/stewards/live/backoff.ts
|
|
2
|
+
function e(e, t = Math.random, n = 1e3, r = 3e4) {
|
|
3
|
+
let i = Math.min(r, n * 2 ** Math.max(0, e - 1)), a = 1 + (t() * 2 - 1) * .2;
|
|
4
|
+
return Math.round(i * a);
|
|
5
|
+
}
|
|
6
|
+
export { e as backoffDelay };
|
|
7
|
+
|
|
8
|
+
//# sourceMappingURL=backoff.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"backoff.js","names":["backoffDelay","exp","capMs","baseMs","attempt","jitter","random"],"sources":["../../../src/stewards/live/backoff.ts"],"sourcesContent":["/** Reconnect delay: exponential from `baseMs`, capped, with +-20% jitter so a fleet does not stampede. */\nexport function backoffDelay(\n attempt: number,\n random: () => number = Math.random,\n baseMs = 1_000,\n capMs = 30_000\n): number {\n const exp = Math.min(capMs, baseMs * 2 ** Math.max(0, attempt - 1));\n const jitter = 1 + (random() * 2 - 1) * 0.2;\n return Math.round(exp * jitter);\n}\n"],"mappings":";AACA,SAAgBA,EACd,GACA,IAAuB,KAAK,QAC5B,IAAS,KACT,IAAQ,KACA;CACR,IAAMC,IAAM,KAAK,IAAIC,GAAOC,IAAS,KAAK,KAAK,IAAI,GAAGC,IAAU,CAAC,CAAC,GAC5DC,IAAS,KAAKC,EAAO,IAAI,IAAI,KAAK;CACxC,OAAO,KAAK,MAAML,IAAMI,CAAM;AAChC"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { ApolloClient } from '@apollo/client';
|
|
2
|
+
import { DeskStreamConnection } from './DeskStreamConnection';
|
|
3
|
+
export type FrameSink = (frame: ArrayBuffer) => void;
|
|
4
|
+
export interface SessionTokens {
|
|
5
|
+
getAccessToken(): string | null;
|
|
6
|
+
getWorkspaceToken(): string | null;
|
|
7
|
+
}
|
|
8
|
+
export interface BrowserConnection {
|
|
9
|
+
connection: DeskStreamConnection;
|
|
10
|
+
/** Where desk frames go (the canvas). Frames are never kept in React state. */
|
|
11
|
+
setFrameSink(sink: FrameSink | null): void;
|
|
12
|
+
/** The session to read tokens from; read when a connection is made, never captured. */
|
|
13
|
+
setSession(session: SessionTokens | null): void;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Wires a `DeskStreamConnection` to the real browser: the host's Apollo client (to mint passes),
|
|
17
|
+
* the signed-in session (the two tokens for the first frame), `WebSocket`, timers and page
|
|
18
|
+
* visibility. Kept out of the hook so the hook stays a thin React binding.
|
|
19
|
+
*/
|
|
20
|
+
export declare function createBrowserConnection(client: ApolloClient, runId: string): BrowserConnection;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { DeskStreamConnection as e } from "./DeskStreamConnection.js";
|
|
2
|
+
import { createPassMinter as t } from "./mintPass.js";
|
|
3
|
+
import { resolveExternalGatewayUrls as n } from "@burdenoff/fe-libs/shared/config/gatewayUrls";
|
|
4
|
+
// src/stewards/live/browserConnection.ts
|
|
5
|
+
function r(r, i) {
|
|
6
|
+
let a = null, o = null;
|
|
7
|
+
return {
|
|
8
|
+
connection: new e({
|
|
9
|
+
mint: t(r, i),
|
|
10
|
+
gatewayBaseUrl: () => n().workspaceBaseUrl,
|
|
11
|
+
credentials: () => {
|
|
12
|
+
let e = o?.getAccessToken(), t = o?.getWorkspaceToken();
|
|
13
|
+
return e && t ? {
|
|
14
|
+
authorization: e,
|
|
15
|
+
workspaceAuthorization: t
|
|
16
|
+
} : null;
|
|
17
|
+
},
|
|
18
|
+
createSocket: (e) => new WebSocket(e),
|
|
19
|
+
onFrame: (e) => a?.(e),
|
|
20
|
+
now: () => Date.now(),
|
|
21
|
+
timers: {
|
|
22
|
+
setTimeout: (e, t) => window.setTimeout(e, t),
|
|
23
|
+
clearTimeout: (e) => window.clearTimeout(e),
|
|
24
|
+
setInterval: (e, t) => window.setInterval(e, t),
|
|
25
|
+
clearInterval: (e) => window.clearInterval(e)
|
|
26
|
+
},
|
|
27
|
+
random: Math.random,
|
|
28
|
+
isVisible: () => document.visibilityState !== "hidden"
|
|
29
|
+
}),
|
|
30
|
+
setFrameSink: (e) => {
|
|
31
|
+
a = e;
|
|
32
|
+
},
|
|
33
|
+
setSession: (e) => {
|
|
34
|
+
o = e;
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
export { r as createBrowserConnection };
|
|
39
|
+
|
|
40
|
+
//# sourceMappingURL=browserConnection.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"browserConnection.js","names":["createBrowserConnection","sink","session","DeskStreamConnection","createPassMinter","client","runId","resolveExternalGatewayUrls","authorization","workspaceAuthorization","url","data","fn","ms","id","next"],"sources":["../../../src/stewards/live/browserConnection.ts"],"sourcesContent":["import type { ApolloClient } from '@apollo/client';\nimport { resolveExternalGatewayUrls } from '@burdenoff/fe-libs/shared/config/gatewayUrls';\nimport { DeskStreamConnection, type SocketLike } from './DeskStreamConnection';\nimport { createPassMinter } from './mintPass';\n\nexport type FrameSink = (frame: ArrayBuffer) => void;\n\nexport interface SessionTokens {\n getAccessToken(): string | null;\n getWorkspaceToken(): string | null;\n}\n\nexport interface BrowserConnection {\n connection: DeskStreamConnection;\n /** Where desk frames go (the canvas). Frames are never kept in React state. */\n setFrameSink(sink: FrameSink | null): void;\n /** The session to read tokens from; read when a connection is made, never captured. */\n setSession(session: SessionTokens | null): void;\n}\n\n/**\n * Wires a `DeskStreamConnection` to the real browser: the host's Apollo client (to mint passes),\n * the signed-in session (the two tokens for the first frame), `WebSocket`, timers and page\n * visibility. Kept out of the hook so the hook stays a thin React binding.\n */\nexport function createBrowserConnection(client: ApolloClient, runId: string): BrowserConnection {\n let sink: FrameSink | null = null;\n let session: SessionTokens | null = null;\n const connection = new DeskStreamConnection({\n mint: createPassMinter(client, runId),\n gatewayBaseUrl: () => resolveExternalGatewayUrls().workspaceBaseUrl,\n credentials: () => {\n const authorization = session?.getAccessToken();\n const workspaceAuthorization = session?.getWorkspaceToken();\n return authorization && workspaceAuthorization\n ? { authorization, workspaceAuthorization }\n : null;\n },\n // The browser WebSocket is structurally a SocketLike; the cast names that on purpose.\n createSocket: (url) => new WebSocket(url) as unknown as SocketLike,\n onFrame: (data) => sink?.(data),\n now: () => Date.now(),\n timers: {\n setTimeout: (fn, ms) => window.setTimeout(fn, ms),\n clearTimeout: (id) => window.clearTimeout(id as number),\n setInterval: (fn, ms) => window.setInterval(fn, ms),\n clearInterval: (id) => window.clearInterval(id as number),\n },\n random: Math.random,\n isVisible: () => document.visibilityState !== 'hidden',\n });\n return {\n connection,\n setFrameSink: (next) => {\n sink = next;\n },\n setSession: (next) => {\n session = next;\n },\n };\n}\n"],"mappings":";;;;AAyBA,SAAgBA,EAAwB,GAAsB,GAAkC;CAC9F,IAAIC,IAAyB,MACzBC,IAAgC;CAwBpC,OAAO;EACL,YAAA,IAxBqBC,EAAqB;GAC1C,MAAMC,EAAiBC,GAAQC,CAAK;GACpC,sBAAsBC,EAA2B,CAAC,CAAC;GACnD,mBAAmB;IACjB,IAAMC,IAAgBN,GAAS,eAAe,GACxCO,IAAyBP,GAAS,kBAAkB;IAC1D,OAAOM,KAAiBC,IACpB;KAAE;KAAe;IAAuB,IACxC;GACN;GAEA,eAAe,MAAQ,IAAI,UAAUC,CAAG;GACxC,UAAU,MAAST,IAAOU,CAAI;GAC9B,WAAW,KAAK,IAAI;GACpB,QAAQ;IACN,aAAa,GAAI,MAAO,OAAO,WAAWC,GAAIC,CAAE;IAChD,eAAe,MAAO,OAAO,aAAaC,CAAY;IACtD,cAAc,GAAI,MAAO,OAAO,YAAYF,GAAIC,CAAE;IAClD,gBAAgB,MAAO,OAAO,cAAcC,CAAY;GAC1D;GACA,QAAQ,KAAK;GACb,iBAAiB,SAAS,oBAAoB;EAChD,CAEE;EACA,eAAe,MAAS;GACtB,IAAOC;EACT;EACA,aAAa,MAAS;GACpB,IAAUA;EACZ;CACF;AACF"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { StreamState } from './DeskStreamConnection';
|
|
2
|
+
export type BannerTone = 'success' | 'warning' | 'info' | 'error';
|
|
3
|
+
export interface StreamBanner {
|
|
4
|
+
tone: BannerTone;
|
|
5
|
+
/** Translation key of the headline. */
|
|
6
|
+
titleKey: string;
|
|
7
|
+
/** Translation key of the line under it. */
|
|
8
|
+
bodyKey?: string;
|
|
9
|
+
params?: Record<string, number>;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* The control banner for a stream state: who is in control, or why there is no stream.
|
|
13
|
+
* `iAmInControl` is whether the run is taken over by the signed-in person.
|
|
14
|
+
*/
|
|
15
|
+
export declare function describeStream(state: StreamState, iAmInControl: boolean): StreamBanner | null;
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// src/stewards/live/describeStream.ts
|
|
2
|
+
var e = {
|
|
3
|
+
leaseEnded: {
|
|
4
|
+
title: "endedLease",
|
|
5
|
+
body: "endedLeaseBody"
|
|
6
|
+
},
|
|
7
|
+
idle: {
|
|
8
|
+
title: "endedIdle",
|
|
9
|
+
body: "endedIdleBody"
|
|
10
|
+
},
|
|
11
|
+
forbidden: {
|
|
12
|
+
title: "failedForbidden",
|
|
13
|
+
body: "failedForbiddenBody"
|
|
14
|
+
},
|
|
15
|
+
notFound: {
|
|
16
|
+
title: "failedNotFound",
|
|
17
|
+
body: "failedNotFoundBody"
|
|
18
|
+
},
|
|
19
|
+
signIn: {
|
|
20
|
+
title: "failedSignIn",
|
|
21
|
+
body: "failedSignInBody"
|
|
22
|
+
},
|
|
23
|
+
badRequest: {
|
|
24
|
+
title: "failedBadRequest",
|
|
25
|
+
body: "failedBadRequestBody"
|
|
26
|
+
},
|
|
27
|
+
tooMany: {
|
|
28
|
+
title: "failedTooMany",
|
|
29
|
+
body: "failedTooManyBody"
|
|
30
|
+
},
|
|
31
|
+
unavailable: {
|
|
32
|
+
title: "failedUnavailable",
|
|
33
|
+
body: "failedUnavailableBody"
|
|
34
|
+
},
|
|
35
|
+
mintFailed: {
|
|
36
|
+
title: "failedMint",
|
|
37
|
+
body: "failedMintBody"
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
function t(t, n) {
|
|
41
|
+
switch (t.phase) {
|
|
42
|
+
case "idle": return null;
|
|
43
|
+
case "connecting": return {
|
|
44
|
+
tone: "info",
|
|
45
|
+
titleKey: "stewards.desk.bannerConnecting"
|
|
46
|
+
};
|
|
47
|
+
case "reconnecting": return {
|
|
48
|
+
tone: "warning",
|
|
49
|
+
titleKey: "stewards.desk.bannerReconnecting",
|
|
50
|
+
params: { attempt: Math.max(1, t.attempt) }
|
|
51
|
+
};
|
|
52
|
+
case "live": return t.mode === "control" ? {
|
|
53
|
+
tone: "success",
|
|
54
|
+
titleKey: "stewards.desk.bannerYou",
|
|
55
|
+
bodyKey: "stewards.desk.bannerYouBody"
|
|
56
|
+
} : t.holder === "person" ? {
|
|
57
|
+
tone: "warning",
|
|
58
|
+
titleKey: "stewards.desk.bannerOther",
|
|
59
|
+
bodyKey: "stewards.desk.bannerOtherBody"
|
|
60
|
+
} : {
|
|
61
|
+
tone: "info",
|
|
62
|
+
titleKey: "stewards.desk.bannerSteward",
|
|
63
|
+
bodyKey: "stewards.desk.bannerStewardBody"
|
|
64
|
+
};
|
|
65
|
+
case "ended":
|
|
66
|
+
case "failed": {
|
|
67
|
+
let r = t.reason ?? "unavailable", i = e[r], a = r === "leaseEnded" && n;
|
|
68
|
+
return {
|
|
69
|
+
tone: t.phase === "failed" ? "error" : "info",
|
|
70
|
+
titleKey: `stewards.desk.${i.title}`,
|
|
71
|
+
bodyKey: a ? "stewards.desk.endedLeaseControlBody" : `stewards.desk.${i.body}`
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
export { t as describeStream };
|
|
77
|
+
|
|
78
|
+
//# sourceMappingURL=describeStream.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"describeStream.js","names":["REASON_KEYS","describeStream","state","reason","keys","controlLease","iAmInControl"],"sources":["../../../src/stewards/live/describeStream.ts"],"sourcesContent":["import type { StreamState } from './DeskStreamConnection';\nimport type { StreamEndReason } from './protocol';\n\nexport type BannerTone = 'success' | 'warning' | 'info' | 'error';\n\nexport interface StreamBanner {\n tone: BannerTone;\n /** Translation key of the headline. */\n titleKey: string;\n /** Translation key of the line under it. */\n bodyKey?: string;\n params?: Record<string, number>;\n}\n\nconst REASON_KEYS: Record<StreamEndReason, { title: string; body: string }> = {\n leaseEnded: { title: 'endedLease', body: 'endedLeaseBody' },\n idle: { title: 'endedIdle', body: 'endedIdleBody' },\n forbidden: { title: 'failedForbidden', body: 'failedForbiddenBody' },\n notFound: { title: 'failedNotFound', body: 'failedNotFoundBody' },\n signIn: { title: 'failedSignIn', body: 'failedSignInBody' },\n badRequest: { title: 'failedBadRequest', body: 'failedBadRequestBody' },\n tooMany: { title: 'failedTooMany', body: 'failedTooManyBody' },\n unavailable: { title: 'failedUnavailable', body: 'failedUnavailableBody' },\n mintFailed: { title: 'failedMint', body: 'failedMintBody' },\n};\n\n/**\n * The control banner for a stream state: who is in control, or why there is no stream.\n * `iAmInControl` is whether the run is taken over by the signed-in person.\n */\nexport function describeStream(state: StreamState, iAmInControl: boolean): StreamBanner | null {\n switch (state.phase) {\n case 'idle':\n return null;\n case 'connecting':\n return { tone: 'info', titleKey: 'stewards.desk.bannerConnecting' };\n case 'reconnecting':\n return {\n tone: 'warning',\n titleKey: 'stewards.desk.bannerReconnecting',\n params: { attempt: Math.max(1, state.attempt) },\n };\n case 'live':\n if (state.mode === 'control') {\n return {\n tone: 'success',\n titleKey: 'stewards.desk.bannerYou',\n bodyKey: 'stewards.desk.bannerYouBody',\n };\n }\n if (state.holder === 'person') {\n return {\n tone: 'warning',\n titleKey: 'stewards.desk.bannerOther',\n bodyKey: 'stewards.desk.bannerOtherBody',\n };\n }\n return {\n tone: 'info',\n titleKey: 'stewards.desk.bannerSteward',\n bodyKey: 'stewards.desk.bannerStewardBody',\n };\n case 'ended':\n case 'failed': {\n const reason = state.reason ?? 'unavailable';\n const keys = REASON_KEYS[reason];\n const controlLease = reason === 'leaseEnded' && iAmInControl;\n return {\n tone: state.phase === 'failed' ? 'error' : 'info',\n titleKey: `stewards.desk.${keys.title}`,\n bodyKey: controlLease\n ? 'stewards.desk.endedLeaseControlBody'\n : `stewards.desk.${keys.body}`,\n };\n }\n }\n}\n"],"mappings":";AAcA,IAAMA,IAAwE;CAC5E,YAAY;EAAE,OAAO;EAAc,MAAM;CAAiB;CAC1D,MAAM;EAAE,OAAO;EAAa,MAAM;CAAgB;CAClD,WAAW;EAAE,OAAO;EAAmB,MAAM;CAAsB;CACnE,UAAU;EAAE,OAAO;EAAkB,MAAM;CAAqB;CAChE,QAAQ;EAAE,OAAO;EAAgB,MAAM;CAAmB;CAC1D,YAAY;EAAE,OAAO;EAAoB,MAAM;CAAuB;CACtE,SAAS;EAAE,OAAO;EAAiB,MAAM;CAAoB;CAC7D,aAAa;EAAE,OAAO;EAAqB,MAAM;CAAwB;CACzE,YAAY;EAAE,OAAO;EAAc,MAAM;CAAiB;AAC5D;AAMA,SAAgBC,EAAe,GAAoB,GAA4C;CAC7F,QAAQC,EAAM,OAAd;EACE,KAAK,QACH,OAAO;EACT,KAAK,cACH,OAAO;GAAE,MAAM;GAAQ,UAAU;EAAiC;EACpE,KAAK,gBACH,OAAO;GACL,MAAM;GACN,UAAU;GACV,QAAQ,EAAE,SAAS,KAAK,IAAI,GAAGA,EAAM,OAAO,EAAE;EAChD;EACF,KAAK,QAeH,OAdIA,EAAM,SAAS,YACV;GACL,MAAM;GACN,UAAU;GACV,SAAS;EACX,IAEEA,EAAM,WAAW,WACZ;GACL,MAAM;GACN,UAAU;GACV,SAAS;EACX,IAEK;GACL,MAAM;GACN,UAAU;GACV,SAAS;EACX;EACF,KAAK;EACL,KAAK,UAAU;GACb,IAAMC,IAASD,EAAM,UAAU,eACzBE,IAAOJ,EAAYG,IACnBE,IAAeF,MAAW,gBAAgBG;GAChD,OAAO;IACL,MAAMJ,EAAM,UAAU,WAAW,UAAU;IAC3C,UAAU,iBAAiBE,EAAK;IAChC,SAASC,IACL,wCACA,iBAAiBD,EAAK;GAC5B;EACF;CACF;AACF"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { ApolloClient } from '@apollo/client';
|
|
2
|
+
import { StreamPass } from './DeskStreamConnection';
|
|
3
|
+
import { StreamMode } from './protocol';
|
|
4
|
+
/**
|
|
5
|
+
* Mints a one-use pass for the relay: `createBotmanorStewardDeskControl` for control (the caller
|
|
6
|
+
* must have taken the run over) and `createBotmanorStewardLiveView` for watching. Mutations are
|
|
7
|
+
* never cached, so a pass is never replayed from the Apollo cache.
|
|
8
|
+
*/
|
|
9
|
+
export declare function createPassMinter(client: ApolloClient, runId: string): (mode: StreamMode) => Promise<StreamPass>;
|